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, WitnessVersion } 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 WitnessVersionArrToBytes(inputArray: Array<WitnessVersion>): Uint8Array {
154 const arr = new Uint8Array(inputArray.length);
155 for (var i = 0; i < inputArray.length; i++) {
156 arr[i] = inputArray[i].getVal();
164 export function encodeUint8Array (inputArray: Uint8Array): number {
165 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
166 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
167 arrayLengthView[0] = inputArray.length;
168 const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
169 arrayMemoryView.set(inputArray);
170 return cArrayPointer;
173 export function encodeUint32Array (inputArray: Uint32Array|Array<number>): number {
174 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
175 const arrayMemoryView = new Uint32Array(wasm.memory.buffer, cArrayPointer, inputArray.length);
176 arrayMemoryView.set(inputArray, 1);
177 arrayMemoryView[0] = inputArray.length;
178 return cArrayPointer;
181 export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>): number {
182 const cArrayPointer = wasm.TS_malloc(inputArray.length * 8 + 1);
183 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
184 arrayLengthView[0] = inputArray.length;
185 const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
186 arrayMemoryView.set(inputArray);
187 return cArrayPointer;
191 export function check_arr_len(arr: Uint8Array, len: number): Uint8Array {
192 if (arr.length != len) { throw new Error("Expected array of length " + len + "got " + arr.length); }
197 export function getArrayLength(arrayPointer: number): number {
198 const arraySizeViewer = new Uint32Array(wasm.memory.buffer, arrayPointer, 1);
199 return arraySizeViewer[0];
202 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
203 const arraySize = getArrayLength(arrayPointer);
204 const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 4, arraySize);
205 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
206 // will free the underlying memory when it becomes unreachable instead of copying here.
207 // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
208 const actualArray = actualArrayViewer.slice(0, arraySize);
210 wasm.TS_free(arrayPointer);
214 const decodeUint32Array = (arrayPointer: number, free = true) => {
215 const arraySize = getArrayLength(arrayPointer);
216 const actualArrayViewer = new Uint32Array(
217 wasm.memory.buffer, // value
218 arrayPointer + 4, // offset (ignoring length bytes)
219 arraySize // uint32 count
221 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
222 // will free the underlying memory when it becomes unreachable instead of copying here.
223 const actualArray = actualArrayViewer.slice(0, arraySize);
225 wasm.TS_free(arrayPointer);
231 export function freeWasmMemory(pointer: number) { wasm.TS_free(pointer); }
234 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
235 const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 4, idx + 1);
236 return actualArrayViewer[idx];
240 export function getU8ArrayElem(arrayPointer: number, idx: number): number {
241 const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 4, idx + 1);
242 return actualArrayViewer[idx];
247 export function encodeString(str: string): number {
248 const charArray = new TextEncoder().encode(str);
249 return encodeUint8Array(charArray);
253 export function decodeString(stringPointer: number, free = true): string {
254 const arraySize = getArrayLength(stringPointer);
255 const memoryView = new Uint8Array(wasm.memory.buffer, stringPointer + 4, arraySize);
256 const result = new TextDecoder("utf-8").decode(memoryView);
259 wasm.TS_free(stringPointer);
266 self.bindings_header += """
268 export function getRemainingAllocationCount(): number {
269 return wasm.TS_allocs_remaining();
272 export function debugPrintRemainingAllocs() {
273 wasm.TS_print_leaks();
277 self.bindings_header += "\n/* @internal */ export function getRemainingAllocationCount(): number { return 0; }\n"
278 self.bindings_header += "/* @internal */ export function debugPrintRemainingAllocs() { }\n"
280 with open(outdir + "/index.mts", 'a') as index:
281 index.write("""import { initializeWasmFetch, initializeWasmFromUint8Array } from './bindings.mjs';
282 /** Initializes the WASM backend by calling `fetch()` on the given URI - Browser only */
283 export async function initializeWasmWebFetch(uri: string) {
284 await initializeWasmFetch(uri);
286 /** Initializes the WASM backend given a Uint8Array of the .wasm binary file - Browser or Node.JS */
287 export async function initializeWasmFromBinary(bin: Uint8Array) {
288 await initializeWasmFromUint8Array(bin);
293 self.bindings_version_file = """export function get_ldk_java_bindings_version(): String {
294 return "<git_version_ldk_garbagecollected>";
297 self.bindings_footer = ""
299 self.common_base = """
300 function freer(f: () => void) { f() }
301 const finalizer = new FinalizationRegistry(freer);
302 function get_freeer(ptr: number, free_fn: (ptr: number) => void) {
308 export class CommonBase {
309 protected ptr: number;
310 protected ptrs_to: object[] = [];
311 protected constructor(ptr: number, free_fn: (ptr: number) => void) {
313 if (Number.isFinite(ptr) && ptr != 0){
314 finalizer.register(this, get_freeer(ptr, free_fn));
317 // In Java, protected means "any subclass can access fields on any other subclass'"
318 // In TypeScript, protected means "any subclass can access parent fields on instances of itself"
319 // To work around this, we add accessors for other instances' protected fields here.
320 protected static add_ref_from(holder: CommonBase, referent: object) {
321 holder.ptrs_to.push(referent);
323 protected static get_ptr_of(o: CommonBase) {
326 protected static set_null_skip_free(o: CommonBase) {
328 finalizer.unregister(o);
333 public constructor(private val: number) {
334 if (val > 32 || val < 0) throw new Error("UInt5 value is out of range");
336 public getVal(): number {
341 export class WitnessVersion {
342 public constructor(private val: number) {
343 if (val > 16 || val < 0) throw new Error("WitnessVersion value is out of range");
345 public getVal(): number {
350 export class UnqualifiedError {
351 public constructor(val: number) {}
355 self.txout_defn = """export class TxOut extends CommonBase {
356 /** The script_pubkey in this output */
357 public script_pubkey: Uint8Array;
358 /** The value, in satoshis, of this output */
359 public value: bigint;
362 public constructor(_dummy: object, ptr: number) {
363 super(ptr, bindings.TxOut_free);
364 this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
365 this.value = bindings.TxOut_get_value(ptr);
367 public constructor_new(value: bigint, script_pubkey: Uint8Array): TxOut {
368 return new TxOut(null, bindings.TxOut_new(bindings.encodeUint8Array(script_pubkey), value));
371 self.obj_defined(["TxOut"], "structs")
373 self.c_file_pfx = """#include "js-wasm.h"
374 #include <stdatomic.h>
375 #include <lightning.h>
377 // These should be provided...somehow...
378 void *memset(void *s, int c, size_t n);
379 void *memcpy(void *dest, const void *src, size_t n);
380 int memcmp(const void *s1, const void *s2, size_t n);
382 extern void __attribute__((noreturn)) abort(void);
383 static inline void assert(bool expression) {
384 if (!expression) { abort(); }
387 uint32_t __attribute__((export_name("test_bigint_pass_deadbeef0badf00d"))) test_bigint_pass_deadbeef0badf00d(uint64_t val) {
388 return val == 0xdeadbeef0badf00dULL;
394 self.c_file_pfx += """
395 void *malloc(size_t size);
396 void free(void *ptr);
398 #define MALLOC(a, _) malloc(a)
399 #define do_MALLOC(a, _b, _c) malloc(a)
400 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
401 #define DO_ASSERT(a) (void)(a)
403 #define CHECK_ACCESS(p)
404 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
407 self.c_file_pfx += """
408 extern int snprintf(char *str, size_t size, const char *format, ...);
409 typedef int32_t ssize_t;
410 ssize_t write(int fd, const void *buf, size_t count);
411 #define DEBUG_PRINT(...) do { \\
412 char debug_str[1024]; \\
413 int s_len = snprintf(debug_str, 1023, __VA_ARGS__); \\
414 write(2, debug_str, s_len); \\
417 // Always run a, then assert it is true:
418 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
419 // Assert a is true or do nothing
420 #define CHECK(a) DO_ASSERT(a)
422 // Running a leak check across all the allocations and frees of the JDK is a mess,
423 // so instead we implement our own naive leak checker here, relying on the -wrap
424 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
425 // and free'd in Rust or C across the generated bindings shared library.
428 typedef struct allocation {
429 struct allocation* next;
431 const char* struct_name;
434 static allocation* allocation_ll = NULL;
435 static allocation* freed_ll = NULL;
437 extern void* __real_malloc(size_t len);
438 extern void* __real_calloc(size_t nmemb, size_t len);
439 extern void* __real_aligned_alloc(size_t alignment, size_t size);
440 static void new_allocation(void* res, const char* struct_name, int lineno) {
441 allocation* new_alloc = __real_malloc(sizeof(allocation));
442 new_alloc->ptr = res;
443 new_alloc->struct_name = struct_name;
444 new_alloc->next = allocation_ll;
445 new_alloc->lineno = lineno;
446 allocation_ll = new_alloc;
448 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
449 void* res = __real_malloc(len);
450 new_allocation(res, struct_name, lineno);
453 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
455 void __real_free(void* ptr);
456 static void alloc_freed(void* ptr, int lineno) {
457 allocation* p = NULL;
458 allocation* it = allocation_ll;
459 while (it->ptr != ptr) {
460 p = it; it = it->next;
464 while (it && it->ptr != ptr) { p = it; it = it->next; }
466 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n", ptr, lineno);
468 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);
473 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
474 DO_ASSERT(it->ptr == ptr);
478 static void do_FREE(void* ptr, int lineno) {
479 if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
480 alloc_freed(ptr, lineno);
483 #define FREE(ptr) do_FREE(ptr, __LINE__)
485 static void CHECK_ACCESS(const void* ptr) {
486 allocation* it = allocation_ll;
487 while (it->ptr != ptr) {
490 return; // addrsan should catch malloc-unknown and print more info than we have
494 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
495 if (v.is_owned && v.inner != NULL) { \\
496 const void *p = __unmangle_inner_ptr(v.inner); \\
502 void* __wrap_malloc(size_t len) {
503 void* res = __real_malloc(len);
504 new_allocation(res, "malloc call", 0);
507 void* __wrap_calloc(size_t nmemb, size_t len) {
508 void* res = __real_calloc(nmemb, len);
509 new_allocation(res, "calloc call", 0);
512 void* __wrap_aligned_alloc(size_t alignment, size_t size) {
513 void* res = __real_aligned_alloc(alignment, size);
514 new_allocation(res, "aligned_alloc call", 0);
517 void __wrap_free(void* ptr) {
518 if (ptr == NULL) return;
523 void* __real_realloc(void* ptr, size_t newlen);
524 void* __wrap_realloc(void* ptr, size_t len) {
525 if (ptr != NULL) alloc_freed(ptr, 0);
526 void* res = __real_realloc(ptr, len);
527 new_allocation(res, "realloc call", 0);
530 void __wrap_reallocarray(void* ptr, size_t new_sz) {
531 // Rust doesn't seem to use reallocarray currently
535 uint32_t __attribute__((export_name("TS_allocs_remaining"))) allocs_remaining() {
537 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
542 void __attribute__((export_name("TS_print_leaks"))) print_leaks() {
543 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
544 DEBUG_PRINT("%s %p remains. Allocated on line %d\\n", a->struct_name, a->ptr, a->lineno);
548 self.c_file_pfx = self.c_file_pfx + """
549 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
550 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
551 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
552 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
554 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
556 #define DECL_ARR_TYPE(ty, name) \\
557 struct name##array { \\
561 typedef struct name##array * name##Array; \\
562 static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
563 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint32_t), #name" array init", lineno); \\
564 arr->arr_len = arr_len; \\
568 DECL_ARR_TYPE(int64_t, int64_t);
569 DECL_ARR_TYPE(int8_t, int8_t);
570 DECL_ARR_TYPE(uint32_t, uint32_t);
571 DECL_ARR_TYPE(void*, ptr);
572 DECL_ARR_TYPE(char, char);
573 typedef charArray jstring;
575 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
576 charArray arr = init_charArray(len, __LINE__);
577 memcpy(arr->elems, chars, len);
580 static inline LDKStr str_ref_to_owned_c(const jstring str) {
581 char* newchars = MALLOC(str->arr_len + 1, "String chars");
582 memcpy(newchars, str->elems, str->arr_len);
583 newchars[str->arr_len] = 0;
587 .chars_is_owned = true
592 typedef bool jboolean;
594 uint32_t __attribute__((export_name("TS_malloc"))) TS_malloc(uint32_t size) {
595 return (uint32_t)MALLOC(size, "JS-Called malloc");
597 void __attribute__((export_name("TS_free"))) TS_free(uint32_t ptr) {
601 jstring __attribute__((export_name("TS_get_ldk_c_bindings_version"))) TS_get_ldk_c_bindings_version() {
602 const char *res = check_get_ldk_bindings_version();
603 if (res == NULL) return NULL;
604 return str_ref_to_ts(res, strlen(res));
606 jstring __attribute__((export_name("TS_get_ldk_version"))) get_ldk_version() {
607 const char *res = check_get_ldk_version();
608 if (res == NULL) return NULL;
609 return str_ref_to_ts(res, strlen(res));
614 self.c_version_file = """jstring __attribute__((export_name("TS_get_lib_version_string"))) TS_get_lib_version_string() {
615 return str_ref_to_ts("<git_version_ldk_garbagecollected>", strlen("<git_version_ldk_garbagecollected>"));
618 self.hu_struct_file_prefix = """
619 import { CommonBase, UInt5, WitnessVersion, UnqualifiedError } from './CommonBase.mjs';
620 import * as bindings from '../bindings.mjs'
623 self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
624 self.util_fn_sfx = "}"
625 self.c_fn_ty_pfx = ""
626 self.file_ext = ".mts"
627 self.ptr_c_ty = "uint32_t"
628 self.ptr_native_ty = "number"
629 self.result_c_ty = "uint32_t"
630 self.ptr_arr = "ptrArray"
631 self.is_arr_some_check = ("", " != 0")
632 self.get_native_arr_len_call = ("", "->arr_len")
634 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
636 def create_native_arr_call(self, arr_len, ty_info):
637 if ty_info.c_ty == "ptrArray":
638 assert ty_info.rust_obj == "LDKCVec_u5Z" or (ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"))
639 return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
640 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
641 if ty_info.c_ty == "int8_tArray":
642 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
645 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
646 if ty_info.c_ty == "int8_tArray":
648 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + "); FREE(" + arr_name + ")"
649 if ty_info.c_ty == "ptrArray":
650 return "(void*) " + arr_name + "->elems /* XXX " + arr_name + " leaks */"
653 return arr_name + "->elems /* XXX " + arr_name + " leaks */"
654 def get_native_arr_elem(self, arr_name, idxc, ty_info):
655 assert False # Only called if above is None
656 def get_native_arr_ptr_call(self, ty_info):
657 if ty_info.subty is not None:
658 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 4)"
659 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 4)"
660 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
662 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
663 if ty_info.c_ty == "int8_tArray":
668 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
669 if elem_ty.rust_obj == "LDKu5":
670 return arr_name + " != null ? bindings.uint5ArrToBytes(" + arr_name + ") : null"
671 assert elem_ty.c_ty == "uint32_t" or elem_ty.c_ty.endswith("Array")
672 return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
674 def str_ref_to_native_call(self, var_name, str_len):
675 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
676 def str_ref_to_c_call(self, var_name):
677 return "str_ref_to_owned_c(" + var_name + ")"
678 def str_to_hu_conv(self, var_name):
679 return "const " + var_name + "_conv: string = bindings.decodeString(" + var_name + ");"
680 def str_from_hu_conv(self, var_name):
681 return ("bindings.encodeString(" + var_name + ")", "")
683 def c_fn_name_define_pfx(self, fn_name, have_args):
684 return " __attribute__((export_name(\"TS_" + fn_name + "\"))) TS_" + fn_name + "("
689 def get_java_arr_len(self, arr_name):
690 return "bindings.getArrayLength(" + arr_name + ")"
691 def get_java_arr_elem(self, elem_ty, arr_name, idx):
692 if elem_ty.c_ty == "uint32_t" or elem_ty.c_ty == "uintptr_t" or elem_ty.c_ty.endswith("Array"):
693 return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
694 elif elem_ty.rust_obj == "LDKu5":
695 return "bindings.getU8ArrayElem(" + arr_name + ", " + idx + ")"
698 def constr_hu_array(self, ty_info, arr_len):
699 return "new Array(" + arr_len + ").fill(null)"
700 def cleanup_converted_native_array(self, ty_info, arr_name):
701 return "bindings.freeWasmMemory(" + arr_name + ")"
703 def primitive_arr_from_hu(self, mapped_ty, fixed_len, arr_name):
705 if fixed_len is not None:
706 assert mapped_ty.c_ty == "int8_t"
707 inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
708 if mapped_ty.c_ty.endswith("Array"):
709 return ("bindings.encodeUint32Array(" + inner + ")", "")
710 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
711 return ("bindings.encodeUint8Array(" + inner + ")", "")
712 elif mapped_ty.c_ty == "uint32_t":
713 return ("bindings.encodeUint32Array(" + inner + ")", "")
714 elif mapped_ty.c_ty == "int64_t":
715 return ("bindings.encodeUint64Array(" + inner + ")", "")
717 print(mapped_ty.c_ty)
720 def primitive_arr_to_hu(self, mapped_ty, fixed_len, arr_name, conv_name):
721 assert mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t"
722 return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
724 def var_decl_statement(self, ty_string, var_name, statement):
725 return "const " + var_name + ": " + ty_string + " = " + statement
727 def java_arr_ty_str(self, elem_ty_str):
730 def for_n_in_range(self, n, minimum, maximum):
731 return "for (var " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
732 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
733 return (arr_name + ".forEach((" + n + ": " + arr_elem_ty.java_hu_ty + ") => { ", " })")
735 def get_ptr(self, var):
736 return "CommonBase.get_ptr_of(" + var + ")"
737 def set_null_skip_free(self, var):
738 return "CommonBase.set_null_skip_free(" + var + ");"
740 def add_ref(self, holder, referent):
741 return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
743 def obj_defined(self, struct_names, folder):
744 with open(self.outdir + "/index.mts", 'a') as index:
745 index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
746 with open(self.outdir + "/imports.mts.part", 'a') as imports:
747 imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
749 def fully_qualified_hu_ty_path(self, ty):
752 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
753 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
754 out_c = out_c + "\tswitch (ord) {\n"
757 out_typescript_enum_fields = ""
759 for var, var_docs in variants:
760 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
762 if var_docs is not None:
763 var_docs_repld = var_docs.replace("\n", "\n\t")
764 out_typescript_enum_fields += f"/**\n\t * {var_docs_repld}\n\t */\n"
765 out_typescript_enum_fields += f"\t{var},\n\t"
766 out_c = out_c + "\t}\n"
767 out_c = out_c + "\tabort();\n"
768 out_c = out_c + "}\n"
770 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
771 out_c = out_c + "\tswitch (val) {\n"
773 for var, _ in variants:
774 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
776 out_c = out_c + "\t\tdefault: abort();\n"
777 out_c = out_c + "\t}\n"
778 out_c = out_c + "}\n"
780 out_typescript = f"""
782 export enum {struct_name} {{
783 {out_typescript_enum_fields}
786 out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
787 self.obj_defined([struct_name], "enums")
788 return (out_c, out_typescript_enum, out_typescript)
790 def c_unitary_enum_to_native_call(self, ty_info):
791 return (ty_info.rust_obj + "_to_js(", ")")
792 def native_unitary_enum_to_c_call(self, ty_info):
793 return (ty_info.rust_obj + "_from_js(", ")")
795 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
796 out_typescript_bindings = ""
797 super_instantiator = ""
798 bindings_instantiator = ""
799 pointer_to_adder = ""
800 impl_constructor_arguments = ""
801 for var in flattened_field_var_conversions:
802 if isinstance(var, ConvInfo):
803 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
804 super_instantiator += first_to_lower(var.arg_name) + ", "
805 if var.from_hu_conv is not None:
806 bindings_instantiator += ", " + var.from_hu_conv[0]
807 if var.from_hu_conv[1] != "":
808 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
810 bindings_instantiator += ", " + first_to_lower(var.arg_name)
812 bindings_instantiator += ", " + first_to_lower(var[1]) + ".bindings_instance"
813 super_instantiator += first_to_lower(var[1]) + "_impl, "
814 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
815 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
817 super_constructor_statements = ""
818 trait_constructor_arguments = ""
819 for var in field_var_conversions:
820 if isinstance(var, ConvInfo):
821 trait_constructor_arguments += ", " + var.arg_name
823 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
824 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".bindings_instance"
825 for suparg in var[2]:
826 if isinstance(suparg, ConvInfo):
827 trait_constructor_arguments += ", " + suparg.arg_name
829 trait_constructor_arguments += ", " + suparg[1]
831 # BUILD INTERFACE METHODS
832 out_java_interface = ""
833 out_interface_implementation_overrides = ""
835 for fn_line in field_function_lines:
836 java_method_descriptor = ""
837 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
838 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
839 out_java_interface += "\t" + fn_line.fn_name + "("
840 out_interface_implementation_overrides += f"\t\t\t{fn_line.fn_name} ("
842 for idx, arg_conv_info in enumerate(fn_line.args_ty):
844 out_java_interface += ", "
845 out_interface_implementation_overrides += ", "
846 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
847 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
848 java_method_descriptor += arg_conv_info.java_fn_ty_arg
849 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n"
850 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
851 java_methods.append((fn_line.fn_name, java_method_descriptor))
853 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
855 for arg_info in fn_line.args_ty:
856 if arg_info.to_hu_conv is not None:
857 out_interface_implementation_overrides += "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
859 if fn_line.ret_ty_info.java_ty != "void":
860 out_interface_implementation_overrides += "\t\t\t\tconst ret: " + fn_line.ret_ty_info.java_hu_ty + " = arg." + fn_line.fn_name + "("
862 out_interface_implementation_overrides += f"\t\t\t\targ." + fn_line.fn_name + "("
864 for idx, arg_info in enumerate(fn_line.args_ty):
866 out_interface_implementation_overrides += ", "
867 if arg_info.to_hu_conv_name is not None:
868 out_interface_implementation_overrides += arg_info.to_hu_conv_name
870 out_interface_implementation_overrides += arg_info.arg_name
872 out_interface_implementation_overrides += ");\n"
873 if fn_line.ret_ty_info.java_ty != "void":
874 if fn_line.ret_ty_info.from_hu_conv is not None:
875 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"
876 if fn_line.ret_ty_info.from_hu_conv[1] != "":
877 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"
878 #if fn_line.ret_ty_info.rust_obj in result_types:
879 # XXX: We need to handle this in conversion logic so that its cross-language!
880 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
881 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
882 out_interface_implementation_overrides += "\t\t\t\treturn result;\n"
884 out_interface_implementation_overrides += "\t\t\t\treturn ret;\n"
885 out_interface_implementation_overrides += f"\t\t\t}},\n"
887 formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
888 out_typescript_human = f"""
889 {self.hu_struct_file_prefix}
891 /** An implementation of {struct_name.replace("LDK","")} */
892 export interface {struct_name.replace("LDK", "")}Interface {{
893 {out_java_interface}}}
895 class {struct_name}Holder {{
896 held: {struct_name.replace("LDK", "")};
900 * {formatted_trait_docs}
902 export class {struct_name.replace("LDK","")} extends CommonBase {{
904 public bindings_instance?: bindings.{struct_name};
907 constructor(_dummy: object, ptr: number) {{
908 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
909 this.bindings_instance = null;
912 /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
913 public static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
914 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
915 let structImplementation = {{
916 {out_interface_implementation_overrides} }} as bindings.{struct_name};
917 {super_constructor_statements} const ptr: number = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
919 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr);
920 impl_holder.held.bindings_instance = structImplementation;
921 {pointer_to_adder} return impl_holder.held;
925 self.obj_defined([struct_name.replace("LDK", ""), struct_name.replace("LDK", "") + "Interface"], "structs")
927 out_typescript_bindings += "/* @internal */\nexport interface " + struct_name + " {\n"
929 for fn_line in field_function_lines:
930 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
931 out_typescript_bindings += f"\t{fn_line.fn_name} ("
933 for idx, arg_conv_info in enumerate(fn_line.args_ty):
935 out_typescript_bindings = out_typescript_bindings + ", "
936 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
938 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
940 out_typescript_bindings += "}\n\n"
942 out_typescript_bindings += f"/* @internal */\nexport function {struct_name}_new(impl: {struct_name}"
943 for var in flattened_field_var_conversions:
944 if isinstance(var, ConvInfo):
945 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
947 out_typescript_bindings += f", {var[1]}: {var[0]}"
949 out_typescript_bindings += f"""): number {{
950 if(!isWasmInitialized) {{
951 throw new Error("initializeWasm() must be awaited first!");
953 var new_obj_idx = js_objs.length;
954 for (var i = 0; i < js_objs.length; i++) {{
955 if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
957 js_objs[i] = new WeakRef(impl);
958 return wasm.TS_{struct_name}_new(i);
962 # Now that we've written out our java code (and created java_meths), generate C
963 out_c = "typedef struct " + struct_name + "_JCalls {\n"
964 out_c += "\tatomic_size_t refcnt;\n"
965 out_c += "\tuint32_t instance_ptr;\n"
966 for var in flattened_field_var_conversions:
967 if isinstance(var, ConvInfo):
968 # We're a regular ol' field
972 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
973 out_c = out_c + "} " + struct_name + "_JCalls;\n"
975 for fn_line in field_function_lines:
976 if fn_line.fn_name == "free":
977 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
978 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
979 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
980 out_c = out_c + "\t\tFREE(j_calls);\n"
981 out_c = out_c + "\t}\n}\n"
983 for idx, fn_line in enumerate(field_function_lines):
984 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
985 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
986 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
987 if fn_line.self_is_const:
988 out_c = out_c + "const void* this_arg"
990 out_c = out_c + "void* this_arg"
992 for idx, arg in enumerate(fn_line.args_ty):
993 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
995 out_c = out_c + ") {\n"
996 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
998 for arg_info in fn_line.args_ty:
999 if arg_info.ret_conv is not None:
1000 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
1001 out_c = out_c + arg_info.arg_name
1002 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
1004 if fn_line.ret_ty_info.c_ty.endswith("Array"):
1005 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
1006 out_c += "js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1007 elif fn_line.ret_ty_info.java_ty == "void":
1008 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1009 elif fn_line.ret_ty_info.java_hu_ty == "string":
1010 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)
1011 elif not fn_line.ret_ty_info.passed_as_ptr:
1012 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
1014 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)
1016 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
1017 self.function_ptr_counter += 1
1019 for idx, arg_info in enumerate(fn_line.args_ty):
1020 if arg_info.ret_conv is not None:
1021 out_c = out_c + ", (uint32_t)" + arg_info.ret_conv_name
1023 out_c = out_c + ", (uint32_t)" + arg_info.arg_name
1024 out_c = out_c + ");\n"
1025 if fn_line.ret_ty_info.arg_conv is not None:
1026 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"
1028 out_c = out_c + "}\n"
1030 # Write out a clone function whether we need one or not, as we use them in moving to rust
1031 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
1032 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
1033 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
1034 for var in field_var_conversions:
1035 if not isinstance(var, ConvInfo):
1036 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
1037 out_c = out_c + "}\n"
1039 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
1040 for var in flattened_field_var_conversions:
1041 if isinstance(var, ConvInfo):
1042 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1044 out_c = out_c + ", JSValue " + var[1]
1045 out_c = out_c + ") {\n"
1047 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
1048 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
1049 out_c = out_c + "\tcalls->instance_ptr = o;\n"
1051 for (fn_name, java_meth_descr) in java_meths:
1052 if fn_name != "free" and fn_name != "cloned":
1053 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1054 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1056 for var in flattened_field_var_conversions:
1057 if isinstance(var, ConvInfo) and var.arg_conv is not None:
1058 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1059 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1060 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1061 for fn_line in field_function_lines:
1062 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1063 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1064 elif fn_line.fn_name == "free":
1065 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1067 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1068 for var in field_var_conversions:
1069 if isinstance(var, ConvInfo):
1070 if var.arg_conv_name is not None:
1071 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1072 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1074 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1075 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1077 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1078 for suparg in var[2]:
1079 if isinstance(suparg, ConvInfo):
1080 out_c += ", " + suparg.arg_name
1082 out_c += ", " + suparg[1]
1084 out_c = out_c + "\t};\n"
1085 for var in flattened_field_var_conversions:
1086 if not isinstance(var, ConvInfo):
1087 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
1088 out_c = out_c + "\treturn ret;\n"
1089 out_c = out_c + "}\n"
1091 out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "JSValue o"
1092 for var in flattened_field_var_conversions:
1093 if isinstance(var, ConvInfo):
1094 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1096 out_c = out_c + ", JSValue " + var[1]
1097 out_c = out_c + ") {\n"
1098 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1099 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1100 for var in flattened_field_var_conversions:
1101 if isinstance(var, ConvInfo):
1102 out_c = out_c + ", " + var.arg_name
1104 out_c = out_c + ", " + var[1]
1105 out_c = out_c + ");\n"
1106 out_c = out_c + "\treturn (long)res_ptr;\n"
1107 out_c = out_c + "}\n"
1109 return (out_typescript_bindings, out_typescript_human, out_c)
1111 def trait_struct_inc_refcnt(self, ty_info):
1112 base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
1113 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
1114 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
1117 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1118 bindings_type = struct_name.replace("LDK", "")
1119 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1125 out_java_enum += (self.hu_struct_file_prefix)
1127 java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1128 java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
1129 java_hu_class += "\tprotected constructor(_dummy: object, ptr: number) { super(ptr, bindings." + bindings_type + "_free); }\n"
1130 java_hu_class += "\t/* @internal */\n"
1131 java_hu_class += f"\tpublic static constr_from_ptr(ptr: number): {java_hu_type} {{\n"
1132 java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1133 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"
1134 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
1135 out_c += "\tswitch(obj->tag) {\n"
1136 java_hu_class += "\t\tswitch (raw_ty) {\n"
1137 java_hu_subclasses = ""
1139 out_java += "/* @internal */\nexport class " + struct_name + " {\n"
1140 out_java += "\tprotected constructor() {}\n"
1142 for var in variant_list:
1143 java_hu_subclasses += "/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1144 java_hu_subclasses += "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
1145 java_hu_class += f"\t\t\tcase {var_idx}: "
1146 java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1147 out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1149 for idx, (field_ty, field_docs) in enumerate(var.fields):
1150 if field_docs is not None:
1151 java_hu_subclasses += "\t/**\n\t * " + field_docs.replace("\n", "\n\t * ") + "\n\t */\n"
1152 java_hu_subclasses += "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
1153 if field_ty.to_hu_conv is not None:
1154 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"
1155 hu_conv_body += f"\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1156 hu_conv_body += f"\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1158 hu_conv_body += f"\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1159 java_hu_subclasses += "\t/* @internal */\n"
1160 java_hu_subclasses += "\tpublic constructor(ptr: number) {\n\t\tsuper(null, ptr);\n"
1161 java_hu_subclasses = java_hu_subclasses + hu_conv_body
1162 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
1165 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"
1166 out_java += self.fn_call_body(struct_name + "_ty_from_ptr", "uint32_t", "number", "ptr: number", "ptr")
1167 out_c += ("\t\tdefault: abort();\n")
1168 out_c += ("\t}\n}\n")
1170 for var in variant_list:
1171 for idx, (field_map, _) in enumerate(var.fields):
1172 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1173 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"
1174 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
1175 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1176 if field_map.ret_conv is not None:
1177 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1178 if var.tuple_variant:
1179 out_c += "obj->" + camel_to_snake(var.var_name)
1181 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1182 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1183 out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1185 if var.tuple_variant:
1186 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1188 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1190 out_java += self.fn_call_body(fn_name, field_map.c_ty, field_map.java_ty, "ptr: number", "ptr")
1191 out_java_enum += java_hu_class
1192 self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
1193 self.obj_defined([java_hu_type], "structs")
1194 return (out_java, out_java_enum, out_c)
1196 def map_opaque_struct(self, struct_name, struct_doc_comment):
1197 implementations = ""
1200 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1201 out_opaque_struct_human = f"{self.hu_struct_file_prefix}"
1202 if struct_name.startswith("LDKLocked"):
1203 out_opaque_struct_human += "/** XXX: DO NOT USE THIS - it remains locked until the GC runs (if that ever happens */"
1204 formatted_doc_comment = struct_doc_comment.replace("\n", "\n * ")
1205 out_opaque_struct_human += f"""
1207 * {formatted_doc_comment}
1209 export class {hu_name} extends CommonBase {implementations}{{
1211 public constructor(_dummy: object, ptr: number) {{
1212 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1216 self.obj_defined([hu_name], "structs")
1217 return out_opaque_struct_human
1219 def map_tuple(self, struct_name):
1220 return self.map_opaque_struct(struct_name, "A Tuple")
1222 def map_result(self, struct_name, res_map, err_map):
1223 human_ty = struct_name.replace("LDKCResult", "Result")
1225 suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1226 if res_map.java_hu_ty != "void":
1227 suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1230 public constructor(_dummy: object, ptr: number) {{
1233 if res_map.java_hu_ty == "void":
1235 elif res_map.to_hu_conv is not None:
1236 suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1237 suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1238 suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1240 suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1241 suffixes += "\t}\n}\n"
1243 suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1244 if err_map.java_hu_ty != "void":
1245 suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1248 public constructor(_dummy: object, ptr: number) {{
1251 if err_map.java_hu_ty == "void":
1253 elif err_map.to_hu_conv is not None:
1254 suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1255 suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1256 suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1258 suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1259 suffixes += "\t}\n}"
1261 self.struct_file_suffixes[human_ty] = suffixes
1262 self.obj_defined([human_ty], "structs")
1264 return f"""{self.hu_struct_file_prefix}
1266 export class {human_ty} extends CommonBase {{
1267 protected constructor(_dummy: object, ptr: number) {{
1268 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1271 public static constr_from_ptr(ptr: number): {human_ty} {{
1272 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1273 return new {human_ty}_OK(null, ptr);
1275 return new {human_ty}_Err(null, ptr);
1280 def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1281 has_return_value = return_c_ty != 'void'
1282 return_statement = 'return nativeResponseValue;'
1283 if not has_return_value:
1284 return_statement = '// debug statements here'
1286 return f"""/* @internal */
1287 export function {method_name}({method_argument_string}): {return_java_ty} {{
1288 if(!isWasmInitialized) {{
1289 throw new Error("initializeWasm() must be awaited first!");
1291 const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1295 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):
1298 out_java_struct = None
1301 out_c += (self.c_fn_ty_pfx)
1302 out_c += (return_type_info.c_ty)
1303 out_java += (return_type_info.java_ty)
1304 if return_type_info.ret_conv is not None:
1305 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1306 out_java += (" " + method_name + "(")
1307 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
1309 method_argument_string = ""
1310 native_call_argument_string = ""
1311 for idx, arg_conv_info in enumerate(argument_types):
1313 method_argument_string += (", ")
1314 native_call_argument_string += ', '
1316 if arg_conv_info.c_ty != "void":
1317 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1318 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1319 native_call_argument_string += arg_conv_info.arg_name
1320 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)
1322 out_java_struct = ""
1323 if doc_comment is not None:
1324 out_java_struct = "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1327 out_java_struct += ("\t// Skipped " + method_name + "\n")
1330 out_java_struct += (
1331 "\tpublic static constructor_" + meth_n + "(")
1333 out_java_struct += ("\tpublic " + meth_n + "(")
1334 for idx, arg in enumerate(argument_types):
1336 if not takes_self or idx > 1:
1337 out_java_struct += (", ")
1340 if arg.java_ty != "void":
1341 if arg.arg_name in default_constructor_args:
1342 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1343 if explode_idx != 0:
1344 out_java_struct += (", ")
1345 out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1347 out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1350 if out_java_struct is not None:
1351 out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1352 for info in argument_types:
1353 if info.arg_conv is not None:
1354 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1355 if return_type_info.ret_conv is not None:
1356 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1357 elif return_type_info.c_ty != "void":
1358 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1361 if c_call_string is None:
1362 out_c += (method_name + "(")
1364 out_c += (c_call_string)
1365 for idx, info in enumerate(argument_types):
1366 if info.arg_conv_name is not None:
1369 elif c_call_string is not None:
1371 out_c += (info.arg_conv_name)
1373 if return_type_info.ret_conv is not None:
1374 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1377 for info in argument_types:
1378 if info.arg_conv_cleanup is not None:
1379 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1380 if return_type_info.ret_conv is not None:
1381 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1382 elif return_type_info.c_ty != "void":
1383 out_c += ("\n\treturn ret_val;")
1384 out_c += ("\n}\n\n")
1387 out_java_struct += ("\t\t")
1388 if return_type_info.java_ty != "void":
1389 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1390 out_java_struct += ("bindings." + method_name + "(")
1391 for idx, info in enumerate(argument_types):
1393 out_java_struct += (", ")
1394 if idx == 0 and takes_self:
1395 out_java_struct += ("this.ptr")
1396 elif info.arg_name in default_constructor_args:
1397 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1398 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1399 if explode_idx != 0:
1400 out_java_struct += (", ")
1401 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1402 if explode_arg.from_hu_conv is not None:
1403 out_java_struct += (
1404 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1406 out_java_struct += (expl_arg_name)
1407 out_java_struct += (")")
1408 elif info.from_hu_conv is not None:
1409 out_java_struct += (info.from_hu_conv[0])
1411 out_java_struct += (info.arg_name)
1412 out_java_struct += (");\n")
1413 if return_type_info.to_hu_conv is not None:
1415 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1416 return_type_info.to_hu_conv_name) + "\n")
1418 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1420 for idx, info in enumerate(argument_types):
1421 if idx == 0 and takes_self:
1423 elif info.arg_name in default_constructor_args:
1424 for explode_arg in default_constructor_args[info.arg_name]:
1425 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1426 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1427 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1428 expl_arg_name).replace(
1429 "this", return_type_info.to_hu_conv_name) + ";\n")
1430 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1431 if not takes_self and return_type_info.to_hu_conv_name is not None:
1432 out_java_struct += (
1433 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1435 out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1437 if return_type_info.to_hu_conv_name is not None:
1438 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1439 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1440 out_java_struct += ("\t\treturn ret;\n")
1441 out_java_struct += ("\t}\n\n")
1443 return (out_java, out_c, out_java_struct)
1446 for struct in self.struct_file_suffixes:
1447 with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1448 src.write(self.struct_file_suffixes[struct])
1450 with open(self.outdir + "/bindings.mts", "a") as bindings:
1453 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) {
1454 const weak: WeakRef<object> = js_objs[obj_ptr];
1455 if (weak == null || weak == undefined) {
1456 console.error("Got function call on unknown/free'd JS object!");
1457 throw new Error("Got function call on unknown/free'd JS object!");
1459 const obj: object = weak.deref();
1460 if (obj == null || obj == undefined) {
1461 console.error("Got function call on GC'd JS object!");
1462 throw new Error("Got function call on GC'd JS object!");
1466 bindings.write("\tswitch (fn_id) {\n")
1467 for f in self.function_ptrs:
1468 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
1470 bindings.write("""\t\tdefault:
1471 console.error("Got unknown function call from C!");
1472 throw new Error("Got unknown function call from C!");
1474 if (fn == null || fn == undefined) {
1475 console.error("Got function call on incorrect JS object!");
1476 throw new Error("Got function call on incorrect JS object!");
1478 return fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);