1 from bindingstypes import ConvInfo
4 def first_to_lower(string: str) -> str:
6 return first.lower() + string[1:]
14 def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
16 self.struct_file_suffixes = {}
17 self.function_ptr_counter = 0
18 self.function_ptrs = {}
19 self.c_type_map = dict(
20 uint8_t = ['number', 'number', 'Uint8Array'],
21 uint16_t = ['number', 'number', 'Uint16Array'],
22 uint32_t = ['number', 'number', 'Uint32Array'],
23 uint64_t = ['bigint', 'bigint', 'BigUint64Array'],
25 self.java_type_map = dict(
28 self.java_hu_type_map = dict(
32 self.to_hu_conv_templates = dict(
33 ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
34 default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
37 self.bindings_header = """
38 import * as version from './version.mjs';
40 const imports: any = {};
43 var js_objs: Array<WeakRef<object>> = [];
44 var js_invoke: Function;
46 imports.wasi_snapshot_preview1 = {
47 "fd_write": (fd: number, iovec_array_ptr: number, iovec_array_len: number) => {
48 // This should generally only be used to print panic messages
49 console.log("FD_WRITE to " + fd + " in " + iovec_array_len + " chunks.");
50 const ptr_len_view = new Uint32Array(wasm.memory.buffer, iovec_array_ptr, iovec_array_len * 2);
51 for (var i = 0; i < iovec_array_len; i++) {
52 const bytes_view = new Uint8Array(wasm.memory.buffer, ptr_len_view[i*2], ptr_len_view[i*2+1]);
53 console.log(String.fromCharCode(...bytes_view));
57 "fd_close": (_fd: number) => {
58 // This is not generally called, but may be referenced in debug builds
59 console.log("wasi_snapshot_preview1:fd_close");
60 return 58; // Not Supported
62 "fd_seek": (_fd: number, _offset: bigint, _whence: number, _new_offset: number) => {
63 // This is not generally called, but may be referenced in debug builds
64 console.log("wasi_snapshot_preview1:fd_seek");
65 return 58; // Not Supported
67 "random_get": (buf_ptr: number, buf_len: number) => {
68 const buf = new Uint8Array(wasm.memory.buffer, buf_ptr, buf_len);
69 crypto.getRandomValues(buf);
72 "environ_sizes_get": (environ_var_count_ptr: number, environ_len_ptr: number) => {
73 // This is called before fd_write to format + print panic messages
74 console.log("wasi_snapshot_preview1:environ_sizes_get");
75 const out_count_view = new Uint32Array(wasm.memory.buffer, environ_var_count_ptr, 1);
76 out_count_view[0] = 0;
77 const out_len_view = new Uint32Array(wasm.memory.buffer, environ_len_ptr, 1);
81 "environ_get": (environ_ptr: number, environ_buf_ptr: number) => {
82 // This is called before fd_write to format + print panic messages
83 console.log("wasi_snapshot_preview1:environ_get");
84 return 58; // Note supported - we said there were 0 environment entries!
87 console.log("wasi_snapshot_preview1:proc_exit");
92 let isWasmInitialized: boolean = false;
95 if target == Target.NODEJS:
96 self.bindings_header += """import * as fs from 'fs';
97 import { webcrypto as crypto } from 'crypto';
99 export async function initializeWasm(path: string) {
100 const source = fs.readFileSync(path);
101 imports.env["js_invoke_function"] = js_invoke;
102 const { instance: wasmInstance } = await WebAssembly.instantiate(source, imports);"""
104 self.bindings_header += """
106 export async function initializeWasm(uri: string) {
107 const stream = fetch(uri);
108 imports.env["js_invoke_function"] = js_invoke;
109 const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);"""
111 self.bindings_header += """
112 wasm = wasmInstance.exports;
113 if (!wasm.test_bigint_pass_deadbeef0badf00d(BigInt("0xdeadbeef0badf00d"))) {
114 throw new Error(\"Currently need BigInt-as-u64 support, try ----experimental-wasm-bigint");
117 if (decodeString(wasm.TS_get_lib_version_string()) !== version.get_ldk_java_bindings_version())
118 throw new Error(\"Compiled LDK library and LDK class failes do not match\");
119 // Fetching the LDK versions from C also checks that the header and binaries match
120 const c_bindings_ver: number = wasm.TS_get_ldk_c_bindings_version();
121 const ldk_ver: number = wasm.TS_get_ldk_version();
122 if (c_bindings_ver == 0)
123 throw new Error(\"LDK version did not match the header we built against\");
125 throw new Error(\"LDK C bindings version did not match the header we built against\");
126 const c_bindings_version: string = decodeString(c_bindings_ver)
127 const ldk_version: string = decodeString(ldk_ver);
128 console.log(\"Loaded LDK-Java Bindings with LDK \" + ldk_version + \" and LDK-C-Bindings \" + c_bindings_version);
130 isWasmInitialized = true;
135 const nextMultipleOfFour = (value: number) => {
136 return Math.ceil(value / 4) * 4;
140 export function encodeUint8Array (inputArray: Uint8Array): number {
141 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
142 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
143 arrayLengthView[0] = inputArray.length;
144 const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
145 arrayMemoryView.set(inputArray);
146 return cArrayPointer;
149 export function encodeUint32Array (inputArray: Uint32Array|Array<number>): number {
150 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
151 const arrayMemoryView = new Uint32Array(wasm.memory.buffer, cArrayPointer, inputArray.length);
152 arrayMemoryView.set(inputArray, 1);
153 arrayMemoryView[0] = inputArray.length;
154 return cArrayPointer;
157 export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>): number {
158 const cArrayPointer = wasm.TS_malloc(inputArray.length * 8 + 1);
159 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
160 arrayLengthView[0] = inputArray.length;
161 const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
162 arrayMemoryView.set(inputArray);
163 return cArrayPointer;
167 export function check_arr_len(arr: Uint8Array, len: number): Uint8Array {
168 if (arr.length != len) { throw new Error("Expected array of length " + len + "got " + arr.length); }
173 export function getArrayLength(arrayPointer: number): number {
174 const arraySizeViewer = new Uint32Array(wasm.memory.buffer, arrayPointer, 1);
175 return arraySizeViewer[0];
178 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
179 const arraySize = getArrayLength(arrayPointer);
180 const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 4, arraySize);
181 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
182 // will free the underlying memory when it becomes unreachable instead of copying here.
183 // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
184 const actualArray = actualArrayViewer.slice(0, arraySize);
186 wasm.TS_free(arrayPointer);
190 const decodeUint32Array = (arrayPointer: number, free = true) => {
191 const arraySize = getArrayLength(arrayPointer);
192 const actualArrayViewer = new Uint32Array(
193 wasm.memory.buffer, // value
194 arrayPointer + 4, // offset (ignoring length bytes)
195 arraySize // uint32 count
197 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
198 // will free the underlying memory when it becomes unreachable instead of copying here.
199 const actualArray = actualArrayViewer.slice(0, arraySize);
201 wasm.TS_free(arrayPointer);
207 export function freeWasmMemory(pointer: number) { wasm.TS_free(pointer); }
210 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
211 const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 4, idx + 1);
212 return actualArrayViewer[idx];
216 export function encodeString(str: string): number {
217 const charArray = new TextEncoder().encode(str);
218 return encodeUint8Array(charArray);
222 export function decodeString(stringPointer: number, free = true): string {
223 const arraySize = getArrayLength(stringPointer);
224 const memoryView = new Uint8Array(wasm.memory.buffer, stringPointer + 4, arraySize);
225 const result = new TextDecoder("utf-8").decode(memoryView);
228 wasm.TS_free(stringPointer);
235 self.bindings_header += """
237 export function getRemainingAllocationCount(): number {
238 return wasm.TS_allocs_remaining();
241 export function debugPrintRemainingAllocs() {
242 wasm.TS_print_leaks();
246 self.bindings_header += "\n/* @internal */ export function getRemainingAllocationCount(): number { return 0; }\n"
247 self.bindings_header += "/* @internal */ export function debugPrintRemainingAllocs() { }\n"
249 with open(outdir + "/index.mts", 'a') as index:
250 index.write("""import { initializeWasm as bindingsInit } from './bindings.mjs';
251 export function initializeWasm(path: string) {
256 self.bindings_version_file = """export function get_ldk_java_bindings_version(): String {
257 return "<git_version_ldk_garbagecollected>";
260 self.bindings_footer = ""
262 self.common_base = """
263 function freer(f: () => void) { f() }
264 const finalizer = new FinalizationRegistry(freer);
265 function get_freeer(ptr: number, free_fn: (ptr: number) => void) {
271 export default class CommonBase {
272 protected ptr: number;
273 protected ptrs_to: object[] = [];
274 protected constructor(ptr: number, free_fn: (ptr: number) => void) {
276 if (Number.isFinite(ptr) && ptr != 0){
277 finalizer.register(this, get_freeer(ptr, free_fn));
280 // In Java, protected means "any subclass can access fields on any other subclass'"
281 // In TypeScript, protected means "any subclass can access parent fields on instances of itself"
282 // To work around this, we add accessors for other instances' protected fields here.
283 protected static add_ref_from(holder: CommonBase, referent: object) {
284 holder.ptrs_to.push(referent);
286 protected static get_ptr_of(o: CommonBase) {
289 protected static set_null_skip_free(o: CommonBase) {
291 finalizer.unregister(o);
296 self.txout_defn = """export class TxOut extends CommonBase {
297 /** The script_pubkey in this output */
298 public script_pubkey: Uint8Array;
299 /** The value, in satoshis, of this output */
300 public value: bigint;
303 public constructor(_dummy: object, ptr: number) {
304 super(ptr, bindings.TxOut_free);
305 this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
306 this.value = bindings.TxOut_get_value(ptr);
308 public constructor_new(value: bigint, script_pubkey: Uint8Array): TxOut {
309 return new TxOut(null, bindings.TxOut_new(bindings.encodeUint8Array(script_pubkey), value));
312 self.obj_defined(["TxOut"], "structs")
314 self.c_file_pfx = """#include "js-wasm.h"
315 #include <stdatomic.h>
316 #include <lightning.h>
318 // These should be provided...somehow...
319 void *memset(void *s, int c, size_t n);
320 void *memcpy(void *dest, const void *src, size_t n);
321 int memcmp(const void *s1, const void *s2, size_t n);
323 extern void __attribute__((noreturn)) abort(void);
324 static inline void assert(bool expression) {
325 if (!expression) { abort(); }
328 uint32_t __attribute__((export_name("test_bigint_pass_deadbeef0badf00d"))) test_bigint_pass_deadbeef0badf00d(uint64_t val) {
329 return val == 0xdeadbeef0badf00dULL;
335 self.c_file_pfx += """
336 void *malloc(size_t size);
337 void free(void *ptr);
339 #define MALLOC(a, _) malloc(a)
340 #define do_MALLOC(a, _b, _c) malloc(a)
341 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
342 #define DO_ASSERT(a) (void)(a)
344 #define CHECK_ACCESS(p)
345 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
348 self.c_file_pfx += """
349 extern int snprintf(char *str, size_t size, const char *format, ...);
350 typedef int32_t ssize_t;
351 ssize_t write(int fd, const void *buf, size_t count);
352 #define DEBUG_PRINT(...) do { \\
353 char debug_str[1024]; \\
354 int s_len = snprintf(debug_str, 1023, __VA_ARGS__); \\
355 write(2, debug_str, s_len); \\
358 // Always run a, then assert it is true:
359 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
360 // Assert a is true or do nothing
361 #define CHECK(a) DO_ASSERT(a)
363 // Running a leak check across all the allocations and frees of the JDK is a mess,
364 // so instead we implement our own naive leak checker here, relying on the -wrap
365 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
366 // and free'd in Rust or C across the generated bindings shared library.
369 typedef struct allocation {
370 struct allocation* next;
372 const char* struct_name;
375 static allocation* allocation_ll = NULL;
376 static allocation* freed_ll = NULL;
378 extern void* __real_malloc(size_t len);
379 extern void* __real_calloc(size_t nmemb, size_t len);
380 extern void* __real_aligned_alloc(size_t alignment, size_t size);
381 static void new_allocation(void* res, const char* struct_name, int lineno) {
382 allocation* new_alloc = __real_malloc(sizeof(allocation));
383 new_alloc->ptr = res;
384 new_alloc->struct_name = struct_name;
385 new_alloc->next = allocation_ll;
386 new_alloc->lineno = lineno;
387 allocation_ll = new_alloc;
389 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
390 void* res = __real_malloc(len);
391 new_allocation(res, struct_name, lineno);
394 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
396 void __real_free(void* ptr);
397 static void alloc_freed(void* ptr, int lineno) {
398 allocation* p = NULL;
399 allocation* it = allocation_ll;
400 while (it->ptr != ptr) {
401 p = it; it = it->next;
405 while (it && it->ptr != ptr) { p = it; it = it->next; }
407 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n", ptr, lineno);
409 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);
414 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
415 DO_ASSERT(it->ptr == ptr);
419 static void do_FREE(void* ptr, int lineno) {
420 if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
421 alloc_freed(ptr, lineno);
424 #define FREE(ptr) do_FREE(ptr, __LINE__)
426 static void CHECK_ACCESS(const void* ptr) {
427 allocation* it = allocation_ll;
428 while (it->ptr != ptr) {
431 return; // addrsan should catch malloc-unknown and print more info than we have
435 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
436 if (v.is_owned && v.inner != NULL) { \\
437 const void *p = __unmangle_inner_ptr(v.inner); \\
443 void* __wrap_malloc(size_t len) {
444 void* res = __real_malloc(len);
445 new_allocation(res, "malloc call", 0);
448 void* __wrap_calloc(size_t nmemb, size_t len) {
449 void* res = __real_calloc(nmemb, len);
450 new_allocation(res, "calloc call", 0);
453 void* __wrap_aligned_alloc(size_t alignment, size_t size) {
454 void* res = __real_aligned_alloc(alignment, size);
455 new_allocation(res, "aligned_alloc call", 0);
458 void __wrap_free(void* ptr) {
459 if (ptr == NULL) return;
464 void* __real_realloc(void* ptr, size_t newlen);
465 void* __wrap_realloc(void* ptr, size_t len) {
466 if (ptr != NULL) alloc_freed(ptr, 0);
467 void* res = __real_realloc(ptr, len);
468 new_allocation(res, "realloc call", 0);
471 void __wrap_reallocarray(void* ptr, size_t new_sz) {
472 // Rust doesn't seem to use reallocarray currently
476 uint32_t __attribute__((export_name("TS_allocs_remaining"))) allocs_remaining() {
478 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
483 void __attribute__((export_name("TS_print_leaks"))) print_leaks() {
484 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
485 DEBUG_PRINT("%s %p remains. Allocated on line %d\\n", a->struct_name, a->ptr, a->lineno);
489 self.c_file_pfx = self.c_file_pfx + """
490 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
491 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
492 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
493 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
495 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
497 #define DECL_ARR_TYPE(ty, name) \\
498 struct name##array { \\
502 typedef struct name##array * name##Array; \\
503 static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
504 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint32_t), #name" array init", lineno); \\
505 arr->arr_len = arr_len; \\
509 DECL_ARR_TYPE(int64_t, int64_t);
510 DECL_ARR_TYPE(int8_t, int8_t);
511 DECL_ARR_TYPE(uint32_t, uint32_t);
512 DECL_ARR_TYPE(void*, ptr);
513 DECL_ARR_TYPE(char, char);
514 typedef charArray jstring;
516 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
517 charArray arr = init_charArray(len, __LINE__);
518 memcpy(arr->elems, chars, len);
521 static inline LDKStr str_ref_to_owned_c(const jstring str) {
522 char* newchars = MALLOC(str->arr_len + 1, "String chars");
523 memcpy(newchars, str->elems, str->arr_len);
524 newchars[str->arr_len] = 0;
528 .chars_is_owned = true
533 typedef bool jboolean;
535 uint32_t __attribute__((export_name("TS_malloc"))) TS_malloc(uint32_t size) {
536 return (uint32_t)MALLOC(size, "JS-Called malloc");
538 void __attribute__((export_name("TS_free"))) TS_free(uint32_t ptr) {
542 jstring __attribute__((export_name("TS_get_ldk_c_bindings_version"))) TS_get_ldk_c_bindings_version() {
543 const char *res = check_get_ldk_bindings_version();
544 if (res == NULL) return NULL;
545 return str_ref_to_ts(res, strlen(res));
547 jstring __attribute__((export_name("TS_get_ldk_version"))) get_ldk_version() {
548 const char *res = check_get_ldk_version();
549 if (res == NULL) return NULL;
550 return str_ref_to_ts(res, strlen(res));
555 self.c_version_file = """jstring __attribute__((export_name("TS_get_lib_version_string"))) TS_get_lib_version_string() {
556 return str_ref_to_ts("<git_version_ldk_garbagecollected>", strlen("<git_version_ldk_garbagecollected>"));
559 self.hu_struct_file_prefix = """
560 import CommonBase from './CommonBase.mjs';
561 import * as bindings from '../bindings.mjs'
564 self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
565 self.util_fn_sfx = "}"
566 self.c_fn_ty_pfx = ""
567 self.file_ext = ".mts"
568 self.ptr_c_ty = "uint32_t"
569 self.ptr_native_ty = "number"
570 self.result_c_ty = "uint32_t"
571 self.ptr_arr = "ptrArray"
572 self.is_arr_some_check = ("", " != 0")
573 self.get_native_arr_len_call = ("", "->arr_len")
575 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
577 def create_native_arr_call(self, arr_len, ty_info):
578 if ty_info.c_ty == "ptrArray":
579 assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
580 return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
581 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
582 if ty_info.c_ty == "int8_tArray":
583 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
586 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
587 if ty_info.c_ty == "int8_tArray":
589 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + "); FREE(" + arr_name + ")"
590 if ty_info.c_ty == "ptrArray":
591 return "(void*) " + arr_name + "->elems /* XXX " + arr_name + " leaks */"
594 return arr_name + "->elems /* XXX " + arr_name + " leaks */"
595 def get_native_arr_elem(self, arr_name, idxc, ty_info):
596 assert False # Only called if above is None
597 def get_native_arr_ptr_call(self, ty_info):
598 if ty_info.subty is not None:
599 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 4)"
600 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 4)"
601 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
603 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
604 if ty_info.c_ty == "int8_tArray":
609 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
610 assert elem_ty.c_ty == "uint32_t" or elem_ty.c_ty.endswith("Array")
611 return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
613 def str_ref_to_native_call(self, var_name, str_len):
614 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
615 def str_ref_to_c_call(self, var_name):
616 return "str_ref_to_owned_c(" + var_name + ")"
617 def str_to_hu_conv(self, var_name):
618 return "const " + var_name + "_conv: string = bindings.decodeString(" + var_name + ");"
619 def str_from_hu_conv(self, var_name):
620 return ("bindings.encodeString(" + var_name + ")", "")
622 def c_fn_name_define_pfx(self, fn_name, have_args):
623 return " __attribute__((export_name(\"TS_" + fn_name + "\"))) TS_" + fn_name + "("
628 def get_java_arr_len(self, arr_name):
629 return "bindings.getArrayLength(" + arr_name + ")"
630 def get_java_arr_elem(self, elem_ty, arr_name, idx):
631 if elem_ty.c_ty == "uint32_t" or elem_ty.c_ty == "uintptr_t" or elem_ty.c_ty.endswith("Array"):
632 return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
635 def constr_hu_array(self, ty_info, arr_len):
636 return "new Array(" + arr_len + ").fill(null)"
637 def cleanup_converted_native_array(self, ty_info, arr_name):
638 return "bindings.freeWasmMemory(" + arr_name + ")"
640 def primitive_arr_from_hu(self, mapped_ty, fixed_len, arr_name):
642 if fixed_len is not None:
643 assert mapped_ty.c_ty == "int8_t"
644 inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
645 if mapped_ty.c_ty.endswith("Array"):
646 return ("bindings.encodeUint32Array(" + inner + ")", "")
647 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
648 return ("bindings.encodeUint8Array(" + inner + ")", "")
649 elif mapped_ty.c_ty == "uint32_t":
650 return ("bindings.encodeUint32Array(" + inner + ")", "")
651 elif mapped_ty.c_ty == "int64_t":
652 return ("bindings.encodeUint64Array(" + inner + ")", "")
654 print(mapped_ty.c_ty)
657 def primitive_arr_to_hu(self, mapped_ty, fixed_len, arr_name, conv_name):
658 assert mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t"
659 return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
661 def var_decl_statement(self, ty_string, var_name, statement):
662 return "const " + var_name + ": " + ty_string + " = " + statement
664 def java_arr_ty_str(self, elem_ty_str):
667 def for_n_in_range(self, n, minimum, maximum):
668 return "for (var " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
669 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
670 return (arr_name + ".forEach((" + n + ": " + arr_elem_ty.java_hu_ty + ") => { ", " })")
672 def get_ptr(self, var):
673 return "CommonBase.get_ptr_of(" + var + ")"
674 def set_null_skip_free(self, var):
675 return "CommonBase.set_null_skip_free(" + var + ");"
677 def add_ref(self, holder, referent):
678 return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
680 def obj_defined(self, struct_names, folder):
681 with open(self.outdir + "/index.mts", 'a') as index:
682 index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
683 with open(self.outdir + "/imports.mts.part", 'a') as imports:
684 imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
686 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
687 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
688 out_c = out_c + "\tswitch (ord) {\n"
691 out_typescript_enum_fields = ""
693 for var, var_docs in variants:
694 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
696 if var_docs is not None:
697 var_docs_repld = var_docs.replace("\n", "\n\t")
698 out_typescript_enum_fields += f"/**\n\t * {var_docs_repld}\n\t */\n"
699 out_typescript_enum_fields += f"\t{var},\n\t"
700 out_c = out_c + "\t}\n"
701 out_c = out_c + "\tabort();\n"
702 out_c = out_c + "}\n"
704 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
705 out_c = out_c + "\tswitch (val) {\n"
707 for var, _ in variants:
708 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
710 out_c = out_c + "\t\tdefault: abort();\n"
711 out_c = out_c + "\t}\n"
712 out_c = out_c + "}\n"
714 out_typescript = f"""
716 export enum {struct_name} {{
717 {out_typescript_enum_fields}
720 out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
721 self.obj_defined([struct_name], "enums")
722 return (out_c, out_typescript_enum, out_typescript)
724 def c_unitary_enum_to_native_call(self, ty_info):
725 return (ty_info.rust_obj + "_to_js(", ")")
726 def native_unitary_enum_to_c_call(self, ty_info):
727 return (ty_info.rust_obj + "_from_js(", ")")
729 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
730 out_typescript_bindings = ""
731 super_instantiator = ""
732 bindings_instantiator = ""
733 pointer_to_adder = ""
734 impl_constructor_arguments = ""
735 for var in flattened_field_var_conversions:
736 if isinstance(var, ConvInfo):
737 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
738 super_instantiator += first_to_lower(var.arg_name) + ", "
739 if var.from_hu_conv is not None:
740 bindings_instantiator += ", " + var.from_hu_conv[0]
741 if var.from_hu_conv[1] != "":
742 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
744 bindings_instantiator += ", " + first_to_lower(var.arg_name)
746 bindings_instantiator += ", " + first_to_lower(var[1]) + ".bindings_instance"
747 super_instantiator += first_to_lower(var[1]) + "_impl, "
748 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
749 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
751 super_constructor_statements = ""
752 trait_constructor_arguments = ""
753 for var in field_var_conversions:
754 if isinstance(var, ConvInfo):
755 trait_constructor_arguments += ", " + var.arg_name
757 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
758 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".bindings_instance"
759 for suparg in var[2]:
760 if isinstance(suparg, ConvInfo):
761 trait_constructor_arguments += ", " + suparg.arg_name
763 trait_constructor_arguments += ", " + suparg[1]
765 # BUILD INTERFACE METHODS
766 out_java_interface = ""
767 out_interface_implementation_overrides = ""
769 for fn_line in field_function_lines:
770 java_method_descriptor = ""
771 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
772 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
773 out_java_interface += "\t" + fn_line.fn_name + "("
774 out_interface_implementation_overrides += f"\t\t\t{fn_line.fn_name} ("
776 for idx, arg_conv_info in enumerate(fn_line.args_ty):
778 out_java_interface += ", "
779 out_interface_implementation_overrides += ", "
780 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
781 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
782 java_method_descriptor += arg_conv_info.java_fn_ty_arg
783 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n"
784 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
785 java_methods.append((fn_line.fn_name, java_method_descriptor))
787 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
789 for arg_info in fn_line.args_ty:
790 if arg_info.to_hu_conv is not None:
791 out_interface_implementation_overrides += "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
793 if fn_line.ret_ty_info.java_ty != "void":
794 out_interface_implementation_overrides += "\t\t\t\tconst ret: " + fn_line.ret_ty_info.java_hu_ty + " = arg." + fn_line.fn_name + "("
796 out_interface_implementation_overrides += f"\t\t\t\targ." + fn_line.fn_name + "("
798 for idx, arg_info in enumerate(fn_line.args_ty):
800 out_interface_implementation_overrides += ", "
801 if arg_info.to_hu_conv_name is not None:
802 out_interface_implementation_overrides += arg_info.to_hu_conv_name
804 out_interface_implementation_overrides += arg_info.arg_name
806 out_interface_implementation_overrides += ");\n"
807 if fn_line.ret_ty_info.java_ty != "void":
808 if fn_line.ret_ty_info.from_hu_conv is not None:
809 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"
810 if fn_line.ret_ty_info.from_hu_conv[1] != "":
811 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"
812 #if fn_line.ret_ty_info.rust_obj in result_types:
813 # XXX: We need to handle this in conversion logic so that its cross-language!
814 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
815 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
816 out_interface_implementation_overrides += "\t\t\t\treturn result;\n"
818 out_interface_implementation_overrides += "\t\t\t\treturn ret;\n"
819 out_interface_implementation_overrides += f"\t\t\t}},\n"
821 formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
822 out_typescript_human = f"""
823 {self.hu_struct_file_prefix}
825 /** An implementation of {struct_name.replace("LDK","")} */
826 export interface {struct_name.replace("LDK", "")}Interface {{
827 {out_java_interface}}}
829 class {struct_name}Holder {{
830 held: {struct_name.replace("LDK", "")};
834 * {formatted_trait_docs}
836 export class {struct_name.replace("LDK","")} extends CommonBase {{
838 public bindings_instance?: bindings.{struct_name};
841 constructor(_dummy: object, ptr: number) {{
842 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
843 this.bindings_instance = null;
846 /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
847 public static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
848 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
849 let structImplementation = {{
850 {out_interface_implementation_overrides} }} as bindings.{struct_name};
851 {super_constructor_statements} const ptr: number = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
853 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr);
854 impl_holder.held.bindings_instance = structImplementation;
855 {pointer_to_adder} return impl_holder.held;
859 self.obj_defined([struct_name.replace("LDK", ""), struct_name.replace("LDK", "") + "Interface"], "structs")
861 out_typescript_bindings += "/* @internal */\nexport interface " + struct_name + " {\n"
863 for fn_line in field_function_lines:
864 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
865 out_typescript_bindings += f"\t{fn_line.fn_name} ("
867 for idx, arg_conv_info in enumerate(fn_line.args_ty):
869 out_typescript_bindings = out_typescript_bindings + ", "
870 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
872 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
874 out_typescript_bindings += "}\n\n"
876 out_typescript_bindings += f"/* @internal */\nexport function {struct_name}_new(impl: {struct_name}"
877 for var in flattened_field_var_conversions:
878 if isinstance(var, ConvInfo):
879 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
881 out_typescript_bindings += f", {var[1]}: {var[0]}"
883 out_typescript_bindings += f"""): number {{
884 if(!isWasmInitialized) {{
885 throw new Error("initializeWasm() must be awaited first!");
887 var new_obj_idx = js_objs.length;
888 for (var i = 0; i < js_objs.length; i++) {{
889 if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
891 js_objs[i] = new WeakRef(impl);
892 return wasm.TS_{struct_name}_new(i);
896 # Now that we've written out our java code (and created java_meths), generate C
897 out_c = "typedef struct " + struct_name + "_JCalls {\n"
898 out_c += "\tatomic_size_t refcnt;\n"
899 out_c += "\tuint32_t instance_ptr;\n"
900 for var in flattened_field_var_conversions:
901 if isinstance(var, ConvInfo):
902 # We're a regular ol' field
906 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
907 out_c = out_c + "} " + struct_name + "_JCalls;\n"
909 for fn_line in field_function_lines:
910 if fn_line.fn_name == "free":
911 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
912 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
913 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
914 out_c = out_c + "\t\tFREE(j_calls);\n"
915 out_c = out_c + "\t}\n}\n"
917 for idx, fn_line in enumerate(field_function_lines):
918 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
919 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
920 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
921 if fn_line.self_is_const:
922 out_c = out_c + "const void* this_arg"
924 out_c = out_c + "void* this_arg"
926 for idx, arg in enumerate(fn_line.args_ty):
927 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
929 out_c = out_c + ") {\n"
930 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
932 for arg_info in fn_line.args_ty:
933 if arg_info.ret_conv is not None:
934 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
935 out_c = out_c + arg_info.arg_name
936 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
938 if fn_line.ret_ty_info.c_ty.endswith("Array"):
939 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
940 out_c += "js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
941 elif fn_line.ret_ty_info.java_ty == "void":
942 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
943 elif fn_line.ret_ty_info.java_hu_ty == "string":
944 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)
945 elif not fn_line.ret_ty_info.passed_as_ptr:
946 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
948 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)
950 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
951 self.function_ptr_counter += 1
953 for idx, arg_info in enumerate(fn_line.args_ty):
954 if arg_info.ret_conv is not None:
955 out_c = out_c + ", (uint32_t)" + arg_info.ret_conv_name
957 out_c = out_c + ", (uint32_t)" + arg_info.arg_name
958 out_c = out_c + ");\n"
959 if fn_line.ret_ty_info.arg_conv is not None:
960 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"
962 out_c = out_c + "}\n"
964 # Write out a clone function whether we need one or not, as we use them in moving to rust
965 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
966 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
967 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
968 for var in field_var_conversions:
969 if not isinstance(var, ConvInfo):
970 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
971 out_c = out_c + "}\n"
973 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
974 for var in flattened_field_var_conversions:
975 if isinstance(var, ConvInfo):
976 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
978 out_c = out_c + ", JSValue " + var[1]
979 out_c = out_c + ") {\n"
981 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
982 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
983 out_c = out_c + "\tcalls->instance_ptr = o;\n"
985 for (fn_name, java_meth_descr) in java_meths:
986 if fn_name != "free" and fn_name != "cloned":
987 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
988 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
990 for var in flattened_field_var_conversions:
991 if isinstance(var, ConvInfo) and var.arg_conv is not None:
992 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
993 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
994 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
995 for fn_line in field_function_lines:
996 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
997 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
998 elif fn_line.fn_name == "free":
999 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1001 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1002 for var in field_var_conversions:
1003 if isinstance(var, ConvInfo):
1004 if var.arg_conv_name is not None:
1005 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1006 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1008 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1009 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1011 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1012 for suparg in var[2]:
1013 if isinstance(suparg, ConvInfo):
1014 out_c += ", " + suparg.arg_name
1016 out_c += ", " + suparg[1]
1018 out_c = out_c + "\t};\n"
1019 for var in flattened_field_var_conversions:
1020 if not isinstance(var, ConvInfo):
1021 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
1022 out_c = out_c + "\treturn ret;\n"
1023 out_c = out_c + "}\n"
1025 out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "JSValue o"
1026 for var in flattened_field_var_conversions:
1027 if isinstance(var, ConvInfo):
1028 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1030 out_c = out_c + ", JSValue " + var[1]
1031 out_c = out_c + ") {\n"
1032 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1033 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1034 for var in flattened_field_var_conversions:
1035 if isinstance(var, ConvInfo):
1036 out_c = out_c + ", " + var.arg_name
1038 out_c = out_c + ", " + var[1]
1039 out_c = out_c + ");\n"
1040 out_c = out_c + "\treturn (long)res_ptr;\n"
1041 out_c = out_c + "}\n"
1043 return (out_typescript_bindings, out_typescript_human, out_c)
1045 def trait_struct_inc_refcnt(self, ty_info):
1048 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1049 bindings_type = struct_name.replace("LDK", "")
1050 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1056 out_java_enum += (self.hu_struct_file_prefix)
1058 java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1059 java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
1060 java_hu_class += "\tprotected constructor(_dummy: object, ptr: number) { super(ptr, bindings." + bindings_type + "_free); }\n"
1061 java_hu_class += "\t/* @internal */\n"
1062 java_hu_class += f"\tpublic static constr_from_ptr(ptr: number): {java_hu_type} {{\n"
1063 java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1064 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"
1065 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
1066 out_c += "\tswitch(obj->tag) {\n"
1067 java_hu_class += "\t\tswitch (raw_ty) {\n"
1068 java_hu_subclasses = ""
1070 out_java += "/* @internal */\nexport class " + struct_name + " {\n"
1071 out_java += "\tprotected constructor() {}\n"
1073 for var in variant_list:
1074 java_hu_subclasses += "/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1075 java_hu_subclasses += "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
1076 java_hu_class += f"\t\t\tcase {var_idx}: "
1077 java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1078 out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1080 for idx, (field_ty, field_docs) in enumerate(var.fields):
1081 if field_docs is not None:
1082 java_hu_subclasses += "\t/**\n\t * " + field_docs.replace("\n", "\n\t * ") + "\n\t */\n"
1083 java_hu_subclasses += "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
1084 if field_ty.to_hu_conv is not None:
1085 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"
1086 hu_conv_body += f"\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1087 hu_conv_body += f"\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1089 hu_conv_body += f"\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1090 java_hu_subclasses += "\t/* @internal */\n"
1091 java_hu_subclasses += "\tpublic constructor(ptr: number) {\n\t\tsuper(null, ptr);\n"
1092 java_hu_subclasses = java_hu_subclasses + hu_conv_body
1093 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
1096 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"
1097 out_java += self.fn_call_body(struct_name + "_ty_from_ptr", "uint32_t", "number", "ptr: number", "ptr")
1098 out_c += ("\t\tdefault: abort();\n")
1099 out_c += ("\t}\n}\n")
1101 for var in variant_list:
1102 for idx, (field_map, _) in enumerate(var.fields):
1103 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1104 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"
1105 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
1106 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1107 if field_map.ret_conv is not None:
1108 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1109 if var.tuple_variant:
1110 out_c += "obj->" + camel_to_snake(var.var_name)
1112 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1113 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1114 out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1116 if var.tuple_variant:
1117 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1119 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1121 out_java += self.fn_call_body(fn_name, field_map.c_ty, field_map.java_ty, "ptr: number", "ptr")
1122 out_java_enum += java_hu_class
1123 self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
1124 self.obj_defined([java_hu_type], "structs")
1125 return (out_java, out_java_enum, out_c)
1127 def map_opaque_struct(self, struct_name, struct_doc_comment):
1128 implementations = ""
1131 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1132 out_opaque_struct_human = f"{self.hu_struct_file_prefix}"
1133 if struct_name.startswith("LDKLocked"):
1134 out_opaque_struct_human += "/** XXX: DO NOT USE THIS - it remains locked until the GC runs (if that ever happens */"
1135 formatted_doc_comment = struct_doc_comment.replace("\n", "\n * ")
1136 out_opaque_struct_human += f"""
1138 * {formatted_doc_comment}
1140 export class {hu_name} extends CommonBase {implementations}{{
1142 public constructor(_dummy: object, ptr: number) {{
1143 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1147 self.obj_defined([hu_name], "structs")
1148 return out_opaque_struct_human
1150 def map_tuple(self, struct_name):
1151 return self.map_opaque_struct(struct_name, "A Tuple")
1153 def map_result(self, struct_name, res_map, err_map):
1154 human_ty = struct_name.replace("LDKCResult", "Result")
1156 suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1157 if res_map.java_hu_ty != "void":
1158 suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1161 public constructor(_dummy: object, ptr: number) {{
1164 if res_map.java_hu_ty == "void":
1166 elif res_map.to_hu_conv is not None:
1167 suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1168 suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1169 suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1171 suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1172 suffixes += "\t}\n}\n"
1174 suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1175 if err_map.java_hu_ty != "void":
1176 suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1179 public constructor(_dummy: object, ptr: number) {{
1182 if err_map.java_hu_ty == "void":
1184 elif err_map.to_hu_conv is not None:
1185 suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1186 suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1187 suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1189 suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1190 suffixes += "\t}\n}"
1192 self.struct_file_suffixes[human_ty] = suffixes
1193 self.obj_defined([human_ty], "structs")
1195 return f"""{self.hu_struct_file_prefix}
1197 export class {human_ty} extends CommonBase {{
1198 protected constructor(_dummy: object, ptr: number) {{
1199 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1202 public static constr_from_ptr(ptr: number): {human_ty} {{
1203 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1204 return new {human_ty}_OK(null, ptr);
1206 return new {human_ty}_Err(null, ptr);
1211 def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1212 has_return_value = return_c_ty != 'void'
1213 return_statement = 'return nativeResponseValue;'
1214 if not has_return_value:
1215 return_statement = '// debug statements here'
1217 return f"""/* @internal */
1218 export function {method_name}({method_argument_string}): {return_java_ty} {{
1219 if(!isWasmInitialized) {{
1220 throw new Error("initializeWasm() must be awaited first!");
1222 const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1226 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):
1229 out_java_struct = None
1232 out_c += (self.c_fn_ty_pfx)
1233 out_c += (return_type_info.c_ty)
1234 out_java += (return_type_info.java_ty)
1235 if return_type_info.ret_conv is not None:
1236 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1237 out_java += (" " + method_name + "(")
1238 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
1240 method_argument_string = ""
1241 native_call_argument_string = ""
1242 for idx, arg_conv_info in enumerate(argument_types):
1244 method_argument_string += (", ")
1245 native_call_argument_string += ', '
1247 if arg_conv_info.c_ty != "void":
1248 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1249 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1250 native_call_argument_string += arg_conv_info.arg_name
1251 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)
1253 out_java_struct = ""
1254 if doc_comment is not None:
1255 out_java_struct = "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1258 out_java_struct += ("\t// Skipped " + method_name + "\n")
1261 out_java_struct += (
1262 "\tpublic static constructor_" + meth_n + "(")
1264 out_java_struct += ("\tpublic " + meth_n + "(")
1265 for idx, arg in enumerate(argument_types):
1267 if not takes_self or idx > 1:
1268 out_java_struct += (", ")
1271 if arg.java_ty != "void":
1272 if arg.arg_name in default_constructor_args:
1273 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1274 if explode_idx != 0:
1275 out_java_struct += (", ")
1276 out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1278 out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1281 if out_java_struct is not None:
1282 out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1283 for info in argument_types:
1284 if info.arg_conv is not None:
1285 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1286 if return_type_info.ret_conv is not None:
1287 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1288 elif return_type_info.c_ty != "void":
1289 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1292 if c_call_string is None:
1293 out_c += (method_name + "(")
1295 out_c += (c_call_string)
1296 for idx, info in enumerate(argument_types):
1297 if info.arg_conv_name is not None:
1300 elif c_call_string is not None:
1302 out_c += (info.arg_conv_name)
1304 if return_type_info.ret_conv is not None:
1305 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1308 for info in argument_types:
1309 if info.arg_conv_cleanup is not None:
1310 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1311 if return_type_info.ret_conv is not None:
1312 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1313 elif return_type_info.c_ty != "void":
1314 out_c += ("\n\treturn ret_val;")
1315 out_c += ("\n}\n\n")
1318 out_java_struct += ("\t\t")
1319 if return_type_info.java_ty != "void":
1320 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1321 out_java_struct += ("bindings." + method_name + "(")
1322 for idx, info in enumerate(argument_types):
1324 out_java_struct += (", ")
1325 if idx == 0 and takes_self:
1326 out_java_struct += ("this.ptr")
1327 elif info.arg_name in default_constructor_args:
1328 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1329 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1330 if explode_idx != 0:
1331 out_java_struct += (", ")
1332 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1333 if explode_arg.from_hu_conv is not None:
1334 out_java_struct += (
1335 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1337 out_java_struct += (expl_arg_name)
1338 out_java_struct += (")")
1339 elif info.from_hu_conv is not None:
1340 out_java_struct += (info.from_hu_conv[0])
1342 out_java_struct += (info.arg_name)
1343 out_java_struct += (");\n")
1344 if return_type_info.to_hu_conv is not None:
1346 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1347 return_type_info.to_hu_conv_name) + "\n")
1349 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1351 for idx, info in enumerate(argument_types):
1352 if idx == 0 and takes_self:
1354 elif info.arg_name in default_constructor_args:
1355 for explode_arg in default_constructor_args[info.arg_name]:
1356 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1357 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1358 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1359 expl_arg_name).replace(
1360 "this", return_type_info.to_hu_conv_name) + ";\n")
1361 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1362 if not takes_self and return_type_info.to_hu_conv_name is not None:
1363 out_java_struct += (
1364 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1366 out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1368 if return_type_info.to_hu_conv_name is not None:
1369 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1370 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1371 out_java_struct += ("\t\treturn ret;\n")
1372 out_java_struct += ("\t}\n\n")
1374 return (out_java, out_c, out_java_struct)
1377 for struct in self.struct_file_suffixes:
1378 with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1379 src.write(self.struct_file_suffixes[struct])
1381 with open(self.outdir + "/bindings.mts", "a") as bindings:
1384 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) {
1385 const weak: WeakRef<object> = js_objs[obj_ptr];
1386 if (weak == null || weak == undefined) {
1387 console.error("Got function call on unknown/free'd JS object!");
1388 throw new Error("Got function call on unknown/free'd JS object!");
1390 const obj: object = weak.deref();
1391 if (obj == null || obj == undefined) {
1392 console.error("Got function call on GC'd JS object!");
1393 throw new Error("Got function call on GC'd JS object!");
1397 bindings.write("\tswitch (fn_id) {\n")
1398 for f in self.function_ptrs:
1399 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
1401 bindings.write("""\t\tdefault:
1402 console.error("Got unknown function call from C!");
1403 throw new Error("Got unknown function call from C!");
1405 if (fn == null || fn == undefined) {
1406 console.error("Got function call on incorrect JS object!");
1407 throw new Error("Got function call on incorrect JS object!");
1409 return fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);