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 = self.wasm_import_header(target)
39 self.bindings_version_file = """export function get_ldk_java_bindings_version(): String {
40 return "<git_version_ldk_garbagecollected>";
43 self.bindings_footer = ""
45 self.common_base = """
46 function freer(f: () => void) { f() }
47 const finalizer = new FinalizationRegistry(freer);
48 function get_freeer(ptr: number, free_fn: (ptr: number) => void) {
54 export default class CommonBase {
55 protected ptr: number;
56 protected ptrs_to: object[] = [];
57 protected constructor(ptr: number, free_fn: (ptr: number) => void) {
59 if (Number.isFinite(ptr) && ptr != 0){
60 finalizer.register(this, get_freeer(ptr, free_fn));
63 // In Java, protected means "any subclass can access fields on any other subclass'"
64 // In TypeScript, protected means "any subclass can access parent fields on instances of itself"
65 // To work around this, we add accessors for other instances' protected fields here.
66 protected static add_ref_from(holder: CommonBase, referent: object) {
67 holder.ptrs_to.push(referent);
69 protected static get_ptr_of(o: CommonBase) {
72 protected static set_null_skip_free(o: CommonBase) {
74 finalizer.unregister(o);
79 self.txout_defn = """export class TxOut extends CommonBase {
80 /** The script_pubkey in this output */
81 public script_pubkey: Uint8Array;
82 /** The value, in satoshis, of this output */
86 public constructor(_dummy: object, ptr: number) {
87 super(ptr, bindings.TxOut_free);
88 this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
89 this.value = bindings.TxOut_get_value(ptr);
91 public constructor_new(value: bigint, script_pubkey: Uint8Array): TxOut {
92 return new TxOut(null, bindings.TxOut_new(bindings.encodeUint8Array(script_pubkey), value));
95 self.obj_defined(["TxOut"], "structs")
97 self.c_file_pfx = """#include "js-wasm.h"
98 #include <stdatomic.h>
99 #include <lightning.h>
101 // These should be provided...somehow...
102 void *memset(void *s, int c, size_t n);
103 void *memcpy(void *dest, const void *src, size_t n);
104 int memcmp(const void *s1, const void *s2, size_t n);
106 extern void __attribute__((noreturn)) abort(void);
107 static inline void assert(bool expression) {
108 if (!expression) { abort(); }
111 uint32_t __attribute__((export_name("test_bigint_pass_deadbeef0badf00d"))) test_bigint_pass_deadbeef0badf00d(uint64_t val) {
112 return val == 0xdeadbeef0badf00dULL;
118 self.c_file_pfx = self.c_file_pfx + """
119 void *malloc(size_t size);
120 void free(void *ptr);
122 #define MALLOC(a, _) malloc(a)
123 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
124 #define DO_ASSERT(a) (void)(a)
126 #define CHECK_ACCESS(p)
127 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
130 self.c_file_pfx = self.c_file_pfx + """
131 // Always run a, then assert it is true:
132 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
133 // Assert a is true or do nothing
134 #define CHECK(a) DO_ASSERT(a)
136 // Running a leak check across all the allocations and frees of the JDK is a mess,
137 // so instead we implement our own naive leak checker here, relying on the -wrap
138 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
139 // and free'd in Rust or C across the generated bindings shared library.
142 typedef struct allocation {
143 struct allocation* next;
145 const char* struct_name;
147 static allocation* allocation_ll = NULL;
149 void* __real_malloc(size_t len);
150 void* __real_calloc(size_t nmemb, size_t len);
151 static void new_allocation(void* res, const char* struct_name) {
152 allocation* new_alloc = __real_malloc(sizeof(allocation));
153 new_alloc->ptr = res;
154 new_alloc->struct_name = struct_name;
155 new_alloc->next = allocation_ll;
156 allocation_ll = new_alloc;
158 static void* MALLOC(size_t len, const char* struct_name) {
159 void* res = __real_malloc(len);
160 new_allocation(res, struct_name);
163 void __real_free(void* ptr);
164 static void alloc_freed(void* ptr) {
165 allocation* p = NULL;
166 allocation* it = allocation_ll;
167 while (it->ptr != ptr) {
168 p = it; it = it->next;
170 //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
171 return; // addrsan should catch malloc-unknown and print more info than we have
174 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
175 DO_ASSERT(it->ptr == ptr);
178 static void FREE(void* ptr) {
179 if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
184 static void CHECK_ACCESS(const void* ptr) {
185 allocation* it = allocation_ll;
186 while (it->ptr != ptr) {
189 return; // addrsan should catch malloc-unknown and print more info than we have
193 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
194 if (v.is_owned && v.inner != NULL) { \\
195 const void *p = __unmangle_inner_ptr(v.inner); \\
201 void* __wrap_malloc(size_t len) {
202 void* res = __real_malloc(len);
203 new_allocation(res, "malloc call");
206 void* __wrap_calloc(size_t nmemb, size_t len) {
207 void* res = __real_calloc(nmemb, len);
208 new_allocation(res, "calloc call");
211 void __wrap_free(void* ptr) {
212 if (ptr == NULL) return;
217 void* __real_realloc(void* ptr, size_t newlen);
218 void* __wrap_realloc(void* ptr, size_t len) {
219 if (ptr != NULL) alloc_freed(ptr);
220 void* res = __real_realloc(ptr, len);
221 new_allocation(res, "realloc call");
224 void __wrap_reallocarray(void* ptr, size_t new_sz) {
225 // Rust doesn't seem to use reallocarray currently
229 void __attribute__((destructor)) check_leaks() {
230 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
231 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
233 DO_ASSERT(allocation_ll == NULL);
236 self.c_file_pfx = self.c_file_pfx + """
237 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
238 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
239 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
240 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
242 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
244 #define DECL_ARR_TYPE(ty, name) \\
245 struct name##array { \\
249 typedef struct name##array * name##Array; \\
250 static inline name##Array init_##name##Array(size_t arr_len) { \\
251 name##Array arr = (name##Array)MALLOC(arr_len * sizeof(ty) + sizeof(uint32_t), "##name array init"); \\
252 arr->arr_len = arr_len; \\
256 DECL_ARR_TYPE(int64_t, int64_t);
257 DECL_ARR_TYPE(int8_t, int8_t);
258 DECL_ARR_TYPE(uint32_t, uint32_t);
259 DECL_ARR_TYPE(void*, ptr);
260 DECL_ARR_TYPE(char, char);
261 typedef charArray jstring;
263 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
264 charArray arr = init_charArray(len);
265 memcpy(arr->elems, chars, len);
268 static inline LDKStr str_ref_to_owned_c(const jstring str) {
269 char* newchars = MALLOC(str->arr_len + 1, "String chars");
270 memcpy(newchars, str->elems, str->arr_len);
271 newchars[str->arr_len] = 0;
275 .chars_is_owned = true
280 typedef bool jboolean;
282 uint32_t __attribute__((export_name("TS_malloc"))) TS_malloc(uint32_t size) {
283 return (uint32_t)MALLOC(size, "JS-Called malloc");
285 void __attribute__((export_name("TS_free"))) TS_free(uint32_t ptr) {
289 jstring __attribute__((export_name("TS_get_ldk_c_bindings_version"))) TS_get_ldk_c_bindings_version() {
290 const char *res = check_get_ldk_bindings_version();
291 if (res == NULL) return NULL;
292 return str_ref_to_ts(res, strlen(res));
294 jstring __attribute__((export_name("TS_get_ldk_version"))) get_ldk_version() {
295 const char *res = check_get_ldk_version();
296 if (res == NULL) return NULL;
297 return str_ref_to_ts(res, strlen(res));
302 self.c_version_file = """jstring __attribute__((export_name("TS_get_lib_version_string"))) TS_get_lib_version_string() {
303 return str_ref_to_ts("<git_version_ldk_garbagecollected>", strlen("<git_version_ldk_garbagecollected>"));
306 self.hu_struct_file_prefix = """
307 import CommonBase from './CommonBase.mjs';
308 import * as bindings from '../bindings.mjs'
311 self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
312 self.util_fn_sfx = "}"
313 self.c_fn_ty_pfx = ""
314 self.file_ext = ".mts"
315 self.ptr_c_ty = "uint32_t"
316 self.ptr_native_ty = "number"
317 self.result_c_ty = "uint32_t"
318 self.ptr_arr = "ptrArray"
319 self.is_arr_some_check = ("", " != 0")
320 self.get_native_arr_len_call = ("", "->arr_len")
322 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
324 def create_native_arr_call(self, arr_len, ty_info):
325 if ty_info.c_ty == "ptrArray":
326 assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
327 return "init_" + ty_info.c_ty + "(" + arr_len + ")"
328 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
329 if ty_info.c_ty == "int8_tArray":
330 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
333 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
334 if ty_info.c_ty == "int8_tArray":
336 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + ")"
337 if ty_info.c_ty == "ptrArray":
338 return "(void*) " + arr_name + "->elems"
341 return arr_name + "->elems"
342 def get_native_arr_elem(self, arr_name, idxc, ty_info):
343 assert False # Only called if above is None
344 def get_native_arr_ptr_call(self, ty_info):
345 if ty_info.subty is not None:
346 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 4)"
347 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 4)"
348 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
350 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
351 if ty_info.c_ty == "int8_tArray":
356 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
357 assert elem_ty.c_ty == "uint32_t" or elem_ty.c_ty.endswith("Array")
358 return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
360 def str_ref_to_native_call(self, var_name, str_len):
361 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
362 def str_ref_to_c_call(self, var_name):
363 return "str_ref_to_owned_c(" + var_name + ")"
364 def str_to_hu_conv(self, var_name):
365 return "const " + var_name + "_conv: string = bindings.decodeString(" + var_name + ");"
366 def str_from_hu_conv(self, var_name):
367 return ("bindings.encodeString(" + var_name + ")", "")
369 def c_fn_name_define_pfx(self, fn_name, have_args):
370 return " __attribute__((export_name(\"TS_" + fn_name + "\"))) TS_" + fn_name + "("
372 def wasm_import_header(self, target):
374 import * as version from './version.mjs';
376 const imports: any = {};
379 var js_objs: Array<WeakRef<object>> = [];
380 var js_invoke: Function;
382 imports.wasi_snapshot_preview1 = {
383 "fd_write": (fd: number, iovec_array_ptr: number, iovec_array_len: number) => {
384 // This should generally only be used to print panic messages
385 console.log("FD_WRITE to " + fd + " in " + iovec_array_len + " chunks.");
386 const ptr_len_view = new Uint32Array(wasm.memory.buffer, iovec_array_ptr, iovec_array_len * 2);
387 for (var i = 0; i < iovec_array_len; i++) {
388 const bytes_view = new Uint8Array(wasm.memory.buffer, ptr_len_view[i*2], ptr_len_view[i*2+1]);
389 console.log(String.fromCharCode(...bytes_view));
393 "random_get": (buf_ptr: number, buf_len: number) => {
394 const buf = new Uint8Array(wasm.memory.buffer, buf_ptr, buf_len);
395 crypto.getRandomValues(buf);
398 "environ_sizes_get": (environ_var_count_ptr: number, environ_len_ptr: number) => {
399 // This is called before fd_write to format + print panic messages
400 console.log("wasi_snapshot_preview1:environ_sizes_get");
401 const out_count_view = new Uint32Array(wasm.memory.buffer, environ_var_count_ptr, 1);
402 out_count_view[0] = 1;
403 const out_len_view = new Uint32Array(wasm.memory.buffer, environ_len_ptr, 1);
404 out_len_view[0] = "RUST_BACKTRACE=1".length + 1; // Note that string must be NULL-terminated
407 "environ_get": (environ_ptr: number, environ_buf_ptr: number) => {
408 // This is called before fd_write to format + print panic messages
409 console.log("wasi_snapshot_preview1:environ_get");
410 const out_ptrs = new Uint32Array(wasm.memory.buffer, environ_ptr, 2);
411 out_ptrs[0] = environ_buf_ptr;
412 out_ptrs[1] = "RUST_BACKTRACE=1".length;
413 const out_environ = new Uint8Array(wasm.memory.buffer, environ_buf_ptr, out_ptrs[1]);
414 for (var i = 0; i < out_ptrs[1]; i++) { out_environ[i] = "RUST_BACKTRACE=1".codePointAt(i); }
415 out_environ[out_ptrs[1]] = 0;
418 "proc_exit" : () => {
419 console.log("wasi_snapshot_preview1:proc_exit");
423 var wasm: any = null;
424 let isWasmInitialized: boolean = false;
427 if target == Target.NODEJS:
428 res += """import * as fs from 'fs';
429 import { webcrypto as crypto } from 'crypto';
430 export async function initializeWasm(path: string) {
431 const source = fs.readFileSync(path);
432 imports.env["js_invoke_function"] = js_invoke;
433 const { instance: wasmInstance } = await WebAssembly.instantiate(source, imports);"""
436 export async function initializeWasm(uri: string) {
437 const stream = fetch(uri);
438 imports.env["js_invoke_function"] = js_invoke;
439 const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);"""
442 wasm = wasmInstance.exports;
443 if (!wasm.test_bigint_pass_deadbeef0badf00d(BigInt("0xdeadbeef0badf00d"))) {
444 throw new Error(\"Currently need BigInt-as-u64 support, try ----experimental-wasm-bigint");
447 if (decodeString(wasm.TS_get_lib_version_string()) !== version.get_ldk_java_bindings_version())
448 throw new Error(\"Compiled LDK library and LDK class failes do not match\");
449 // Fetching the LDK versions from C also checks that the header and binaries match
450 if (wasm.TS_get_ldk_c_bindings_version() == 0)
451 throw new Error(\"LDK version did not match the header we built against\");
452 if (wasm.TS_get_ldk_version() == 0)
453 throw new Error(\"LDK C bindings version did not match the header we built against\");
454 const c_bindings_version: string = decodeString(wasm.TS_get_ldk_c_bindings_version());
455 const ldk_version: string = decodeString(wasm.TS_get_ldk_version());
456 console.log(\"Loaded LDK-Java Bindings with LDK \" + ldk_version + \" and LDK-C-Bindings \" + c_bindings_version);
458 isWasmInitialized = true;
463 const nextMultipleOfFour = (value: number) => {
464 return Math.ceil(value / 4) * 4;
467 export function encodeUint8Array (inputArray: Uint8Array): number {
468 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
469 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
470 arrayLengthView[0] = inputArray.length;
471 const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
472 arrayMemoryView.set(inputArray);
473 return cArrayPointer;
475 export function encodeUint32Array (inputArray: Uint32Array|Array<number>): number {
476 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
477 const arrayMemoryView = new Uint32Array(wasm.memory.buffer, cArrayPointer, inputArray.length);
478 arrayMemoryView.set(inputArray, 1);
479 arrayMemoryView[0] = inputArray.length;
480 return cArrayPointer;
482 export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>): number {
483 const cArrayPointer = wasm.TS_malloc(inputArray.length * 8 + 1);
484 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
485 arrayLengthView[0] = inputArray.length;
486 const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
487 arrayMemoryView.set(inputArray);
488 return cArrayPointer;
491 export function check_arr_len(arr: Uint8Array, len: number): Uint8Array {
492 if (arr.length != len) { throw new Error("Expected array of length " + len + "got " + arr.length); }
496 export function getArrayLength(arrayPointer: number): number {
497 const arraySizeViewer = new Uint32Array(wasm.memory.buffer, arrayPointer, 1);
498 return arraySizeViewer[0];
500 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
501 const arraySize = getArrayLength(arrayPointer);
502 const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 4, arraySize);
503 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
504 // will free the underlying memory when it becomes unreachable instead of copying here.
505 // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
506 const actualArray = actualArrayViewer.slice(0, arraySize);
508 wasm.TS_free(arrayPointer);
512 const decodeUint32Array = (arrayPointer: number, free = true) => {
513 const arraySize = getArrayLength(arrayPointer);
514 const actualArrayViewer = new Uint32Array(
515 wasm.memory.buffer, // value
516 arrayPointer + 4, // offset (ignoring length bytes)
517 arraySize // uint32 count
519 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
520 // will free the underlying memory when it becomes unreachable instead of copying here.
521 const actualArray = actualArrayViewer.slice(0, arraySize);
523 wasm.TS_free(arrayPointer);
528 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
529 const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 4, idx + 1);
530 return actualArrayViewer[idx];
533 export function encodeString(str: string): number {
534 const charArray = new TextEncoder().encode(str);
535 return encodeUint8Array(charArray);
538 export function decodeString(stringPointer: number, free = true): string {
539 const arraySize = getArrayLength(stringPointer);
540 const memoryView = new Uint8Array(wasm.memory.buffer, stringPointer + 4, arraySize);
541 const result = new TextDecoder("utf-8").decode(memoryView);
544 wasm.TS_free(stringPointer);
554 def get_java_arr_len(self, arr_name):
555 return "bindings.getArrayLength(" + arr_name + ")"
556 def get_java_arr_elem(self, elem_ty, arr_name, idx):
557 if elem_ty.c_ty == "uint32_t" or elem_ty.c_ty == "uintptr_t" or elem_ty.c_ty.endswith("Array"):
558 return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
561 def constr_hu_array(self, ty_info, arr_len):
562 return "new Array(" + arr_len + ").fill(null)"
564 def primitive_arr_from_hu(self, mapped_ty, fixed_len, arr_name):
566 if fixed_len is not None:
567 assert mapped_ty.c_ty == "int8_t"
568 inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
569 if mapped_ty.c_ty.endswith("Array"):
570 return ("bindings.encodeUint32Array(" + inner + ")", "")
571 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
572 return ("bindings.encodeUint8Array(" + inner + ")", "")
573 elif mapped_ty.c_ty == "uint32_t":
574 return ("bindings.encodeUint32Array(" + inner + ")", "")
575 elif mapped_ty.c_ty == "int64_t":
576 return ("bindings.encodeUint64Array(" + inner + ")", "")
578 print(mapped_ty.c_ty)
581 def primitive_arr_to_hu(self, mapped_ty, fixed_len, arr_name, conv_name):
582 assert mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t"
583 return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
585 def var_decl_statement(self, ty_string, var_name, statement):
586 return "const " + var_name + ": " + ty_string + " = " + statement
588 def java_arr_ty_str(self, elem_ty_str):
591 def for_n_in_range(self, n, minimum, maximum):
592 return "for (var " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
593 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
594 return (arr_name + ".forEach((" + n + ": " + arr_elem_ty.java_hu_ty + ") => { ", " })")
596 def get_ptr(self, var):
597 return "CommonBase.get_ptr_of(" + var + ")"
598 def set_null_skip_free(self, var):
599 return "CommonBase.set_null_skip_free(" + var + ");"
601 def add_ref(self, holder, referent):
602 return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
604 def obj_defined(self, struct_names, folder):
605 with open(self.outdir + "/index.mts", 'a') as index:
606 index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
607 with open(self.outdir + "/imports.mts.part", 'a') as imports:
608 imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
610 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
611 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
612 out_c = out_c + "\tswitch (ord) {\n"
615 out_typescript_enum_fields = ""
617 for var, var_docs in variants:
618 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
620 if var_docs is not None:
621 out_typescript_enum_fields += f"/**\n * {var_docs}\n */\n"
622 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
623 out_c = out_c + "\t}\n"
624 out_c = out_c + "\tabort();\n"
625 out_c = out_c + "}\n"
627 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
628 out_c = out_c + "\tswitch (val) {\n"
630 for var, _ in variants:
631 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
633 out_c = out_c + "\t\tdefault: abort();\n"
634 out_c = out_c + "\t}\n"
635 out_c = out_c + "}\n"
637 out_typescript = f"""
638 export enum {struct_name} {{
639 {out_typescript_enum_fields}
642 out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
643 self.obj_defined([struct_name], "enums")
644 return (out_c, out_typescript_enum, out_typescript)
646 def c_unitary_enum_to_native_call(self, ty_info):
647 return (ty_info.rust_obj + "_to_js(", ")")
648 def native_unitary_enum_to_c_call(self, ty_info):
649 return (ty_info.rust_obj + "_from_js(", ")")
651 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
652 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
654 super_instantiator = ""
655 bindings_instantiator = ""
656 pointer_to_adder = ""
657 impl_constructor_arguments = ""
658 for var in flattened_field_var_conversions:
659 if isinstance(var, ConvInfo):
660 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
661 super_instantiator += first_to_lower(var.arg_name) + ", "
662 if var.from_hu_conv is not None:
663 bindings_instantiator += ", " + var.from_hu_conv[0]
664 if var.from_hu_conv[1] != "":
665 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
667 bindings_instantiator += ", " + first_to_lower(var.arg_name)
669 bindings_instantiator += ", " + first_to_lower(var[1]) + ".bindings_instance"
670 super_instantiator += first_to_lower(var[1]) + "_impl, "
671 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
672 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
674 super_constructor_statements = ""
675 trait_constructor_arguments = ""
676 for var in field_var_conversions:
677 if isinstance(var, ConvInfo):
678 trait_constructor_arguments += ", " + var.arg_name
680 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
681 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".bindings_instance"
682 for suparg in var[2]:
683 if isinstance(suparg, ConvInfo):
684 trait_constructor_arguments += ", " + suparg.arg_name
686 trait_constructor_arguments += ", " + suparg[1]
688 # BUILD INTERFACE METHODS
689 out_java_interface = ""
690 out_interface_implementation_overrides = ""
692 for fn_line in field_function_lines:
693 java_method_descriptor = ""
694 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
695 out_java_interface += "\t" + fn_line.fn_name + "("
696 out_interface_implementation_overrides += f"\t\t\t{fn_line.fn_name} ("
698 for idx, arg_conv_info in enumerate(fn_line.args_ty):
700 out_java_interface += ", "
701 out_interface_implementation_overrides += ", "
702 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
703 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
704 java_method_descriptor += arg_conv_info.java_fn_ty_arg
705 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n"
706 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
707 java_methods.append((fn_line.fn_name, java_method_descriptor))
709 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
711 for arg_info in fn_line.args_ty:
712 if arg_info.to_hu_conv is not None:
713 out_interface_implementation_overrides += "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
715 if fn_line.ret_ty_info.java_ty != "void":
716 out_interface_implementation_overrides += "\t\t\t\tconst ret: " + fn_line.ret_ty_info.java_hu_ty + " = arg." + fn_line.fn_name + "("
718 out_interface_implementation_overrides += f"\t\t\t\targ." + fn_line.fn_name + "("
720 for idx, arg_info in enumerate(fn_line.args_ty):
722 out_interface_implementation_overrides += ", "
723 if arg_info.to_hu_conv_name is not None:
724 out_interface_implementation_overrides += arg_info.to_hu_conv_name
726 out_interface_implementation_overrides += arg_info.arg_name
728 out_interface_implementation_overrides += ");\n"
729 if fn_line.ret_ty_info.java_ty != "void":
730 if fn_line.ret_ty_info.from_hu_conv is not None:
731 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"
732 if fn_line.ret_ty_info.from_hu_conv[1] != "":
733 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"
734 #if fn_line.ret_ty_info.rust_obj in result_types:
735 # XXX: We need to handle this in conversion logic so that its cross-language!
736 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
737 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
738 out_interface_implementation_overrides += "\t\t\t\treturn result;\n"
740 out_interface_implementation_overrides += "\t\t\t\treturn ret;\n"
741 out_interface_implementation_overrides += f"\t\t\t}},\n"
743 out_typescript_human = f"""
744 {self.hu_struct_file_prefix}
746 export interface {struct_name.replace("LDK", "")}Interface {{
747 {out_java_interface}}}
749 class {struct_name}Holder {{
750 held: {struct_name.replace("LDK", "")};
753 export class {struct_name.replace("LDK","")} extends CommonBase {{
755 public bindings_instance?: bindings.{struct_name};
758 constructor(_dummy: object, ptr: number) {{
759 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
760 this.bindings_instance = null;
763 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
764 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
765 let structImplementation = {{
766 {out_interface_implementation_overrides} }} as bindings.{struct_name};
767 {super_constructor_statements} const ptr: number = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
769 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr);
770 impl_holder.held.bindings_instance = structImplementation;
771 {pointer_to_adder} return impl_holder.held;
774 self.obj_defined([struct_name.replace("LDK", ""), struct_name.replace("LDK", "") + "Interface"], "structs")
776 out_typescript_bindings += "export interface " + struct_name + " {\n"
778 for fn_line in field_function_lines:
779 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
780 out_typescript_bindings += f"\t{fn_line.fn_name} ("
782 for idx, arg_conv_info in enumerate(fn_line.args_ty):
784 out_typescript_bindings = out_typescript_bindings + ", "
785 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
787 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
789 out_typescript_bindings += "}\n\n"
791 out_typescript_bindings += f"export function {struct_name}_new(impl: {struct_name}"
792 for var in flattened_field_var_conversions:
793 if isinstance(var, ConvInfo):
794 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
796 out_typescript_bindings += f", {var[1]}: {var[0]}"
798 out_typescript_bindings += f"""): number {{
799 if(!isWasmInitialized) {{
800 throw new Error("initializeWasm() must be awaited first!");
802 var new_obj_idx = js_objs.length;
803 for (var i = 0; i < js_objs.length; i++) {{
804 if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
806 js_objs[i] = new WeakRef(impl);
807 return wasm.TS_{struct_name}_new(i);
811 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
813 # Now that we've written out our java code (and created java_meths), generate C
814 out_c = "typedef struct " + struct_name + "_JCalls {\n"
815 out_c += "\tatomic_size_t refcnt;\n"
816 out_c += "\tuint32_t instance_ptr;\n"
817 for var in flattened_field_var_conversions:
818 if isinstance(var, ConvInfo):
819 # We're a regular ol' field
823 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
824 out_c = out_c + "} " + struct_name + "_JCalls;\n"
826 for fn_line in field_function_lines:
827 if fn_line.fn_name == "free":
828 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
829 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
830 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
831 out_c = out_c + "\t\tFREE(j_calls);\n"
832 out_c = out_c + "\t}\n}\n"
834 for idx, fn_line in enumerate(field_function_lines):
835 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
836 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
837 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
838 if fn_line.self_is_const:
839 out_c = out_c + "const void* this_arg"
841 out_c = out_c + "void* this_arg"
843 for idx, arg in enumerate(fn_line.args_ty):
844 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
846 out_c = out_c + ") {\n"
847 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
849 for arg_info in fn_line.args_ty:
850 if arg_info.ret_conv is not None:
851 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
852 out_c = out_c + arg_info.arg_name
853 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
855 if fn_line.ret_ty_info.c_ty.endswith("Array"):
856 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
857 out_c += "js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
858 elif fn_line.ret_ty_info.java_ty == "void":
859 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
860 elif fn_line.ret_ty_info.java_hu_ty == "string":
861 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)
862 elif not fn_line.ret_ty_info.passed_as_ptr:
863 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
865 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)
867 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
868 self.function_ptr_counter += 1
870 for idx, arg_info in enumerate(fn_line.args_ty):
871 if arg_info.ret_conv is not None:
872 out_c = out_c + ", (uint32_t)" + arg_info.ret_conv_name
874 out_c = out_c + ", (uint32_t)" + arg_info.arg_name
875 out_c = out_c + ");\n"
876 if fn_line.ret_ty_info.arg_conv is not None:
877 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"
879 out_c = out_c + "}\n"
881 # Write out a clone function whether we need one or not, as we use them in moving to rust
882 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
883 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
884 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
885 for var in field_var_conversions:
886 if not isinstance(var, ConvInfo):
887 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
888 out_c = out_c + "}\n"
890 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
891 for var in flattened_field_var_conversions:
892 if isinstance(var, ConvInfo):
893 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
895 out_c = out_c + ", JSValue " + var[1]
896 out_c = out_c + ") {\n"
898 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
899 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
900 out_c = out_c + "\tcalls->instance_ptr = o;\n"
902 for (fn_name, java_meth_descr) in java_meths:
903 if fn_name != "free" and fn_name != "cloned":
904 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
905 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
907 for var in flattened_field_var_conversions:
908 if isinstance(var, ConvInfo) and var.arg_conv is not None:
909 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
910 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
911 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
912 for fn_line in field_function_lines:
913 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
914 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
915 elif fn_line.fn_name == "free":
916 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
918 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
919 for var in field_var_conversions:
920 if isinstance(var, ConvInfo):
921 if var.arg_conv_name is not None:
922 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
923 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
925 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
926 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
928 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
929 for suparg in var[2]:
930 if isinstance(suparg, ConvInfo):
931 out_c += ", " + suparg.arg_name
933 out_c += ", " + suparg[1]
935 out_c = out_c + "\t};\n"
936 for var in flattened_field_var_conversions:
937 if not isinstance(var, ConvInfo):
938 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
939 out_c = out_c + "\treturn ret;\n"
940 out_c = out_c + "}\n"
942 out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "JSValue o"
943 for var in flattened_field_var_conversions:
944 if isinstance(var, ConvInfo):
945 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
947 out_c = out_c + ", JSValue " + var[1]
948 out_c = out_c + ") {\n"
949 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
950 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
951 for var in flattened_field_var_conversions:
952 if isinstance(var, ConvInfo):
953 out_c = out_c + ", " + var.arg_name
955 out_c = out_c + ", " + var[1]
956 out_c = out_c + ");\n"
957 out_c = out_c + "\treturn (long)res_ptr;\n"
958 out_c = out_c + "}\n"
960 return (out_typescript_bindings, out_typescript_human, out_c)
962 def trait_struct_inc_refcnt(self, ty_info):
965 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
966 bindings_type = struct_name.replace("LDK", "")
967 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
973 out_java_enum += (self.hu_struct_file_prefix)
976 java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
977 java_hu_class += "\tprotected constructor(_dummy: object, ptr: number) { super(ptr, bindings." + bindings_type + "_free); }\n"
978 java_hu_class += "\t/* @internal */\n"
979 java_hu_class += f"\tpublic static constr_from_ptr(ptr: number): {java_hu_type} {{\n"
980 java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
981 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"
982 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
983 out_c += "\tswitch(obj->tag) {\n"
984 java_hu_class += "\t\tswitch (raw_ty) {\n"
985 java_hu_subclasses = ""
987 out_java += "export class " + struct_name + " {\n"
988 out_java += "\tprotected constructor() {}\n"
990 for var in variant_list:
991 java_hu_subclasses = java_hu_subclasses + "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
992 java_hu_class += f"\t\t\tcase {var_idx}: "
993 java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
994 out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
996 for idx, (field_ty, field_docs) in enumerate(var.fields):
997 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
998 if field_ty.to_hu_conv is not None:
999 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"
1000 hu_conv_body += f"\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1001 hu_conv_body += f"\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1003 hu_conv_body += f"\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1004 java_hu_subclasses += "\t/* @internal */\n"
1005 java_hu_subclasses += "\tpublic constructor(ptr: number) {\n\t\tsuper(null, ptr);\n"
1006 java_hu_subclasses = java_hu_subclasses + hu_conv_body
1007 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
1010 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"
1011 out_java += self.fn_call_body(struct_name + "_ty_from_ptr", "uint32_t", "number", "ptr: number", "ptr")
1012 out_c += ("\t\tdefault: abort();\n")
1013 out_c += ("\t}\n}\n")
1015 for var in variant_list:
1016 for idx, (field_map, _) in enumerate(var.fields):
1017 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1018 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"
1019 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
1020 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1021 if field_map.ret_conv is not None:
1022 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1023 if var.tuple_variant:
1024 out_c += "obj->" + camel_to_snake(var.var_name)
1026 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1027 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1028 out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1030 if var.tuple_variant:
1031 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1033 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1035 out_java += self.fn_call_body(fn_name, field_map.c_ty, field_map.java_ty, "ptr: number", "ptr")
1036 out_java_enum += java_hu_class
1037 self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
1038 self.obj_defined([java_hu_type], "structs")
1039 return (out_java, out_java_enum, out_c)
1041 def map_opaque_struct(self, struct_name, struct_doc_comment):
1042 implementations = ""
1045 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1046 out_opaque_struct_human = f"{self.hu_struct_file_prefix}"
1047 if struct_name.startswith("LDKLocked"):
1048 out_opaque_struct_human += "/** XXX: DO NOT USE THIS - it remains locked until the GC runs (if that ever happens */"
1049 out_opaque_struct_human += f"""
1050 export class {hu_name} extends CommonBase {implementations}{{
1052 public constructor(_dummy: object, ptr: number) {{
1053 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1057 self.obj_defined([hu_name], "structs")
1058 return out_opaque_struct_human
1060 def map_tuple(self, struct_name):
1061 return self.map_opaque_struct(struct_name, "A Tuple")
1063 def map_result(self, struct_name, res_map, err_map):
1064 human_ty = struct_name.replace("LDKCResult", "Result")
1066 suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1067 if res_map.java_hu_ty != "void":
1068 suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1071 public constructor(_dummy: object, ptr: number) {{
1074 if res_map.java_hu_ty == "void":
1076 elif res_map.to_hu_conv is not None:
1077 suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1078 suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1079 suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1081 suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1082 suffixes += "\t}\n}\n"
1084 suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1085 if err_map.java_hu_ty != "void":
1086 suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1089 public constructor(_dummy: object, ptr: number) {{
1092 if err_map.java_hu_ty == "void":
1094 elif err_map.to_hu_conv is not None:
1095 suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1096 suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1097 suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1099 suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1100 suffixes += "\t}\n}"
1102 self.struct_file_suffixes[human_ty] = suffixes
1103 self.obj_defined([human_ty], "structs")
1105 return f"""{self.hu_struct_file_prefix}
1107 export class {human_ty} extends CommonBase {{
1108 protected constructor(_dummy: object, ptr: number) {{
1109 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1112 public static constr_from_ptr(ptr: number): {human_ty} {{
1113 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1114 return new {human_ty}_OK(null, ptr);
1116 return new {human_ty}_Err(null, ptr);
1121 def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1122 has_return_value = return_c_ty != 'void'
1123 return_statement = 'return nativeResponseValue;'
1124 if not has_return_value:
1125 return_statement = '// debug statements here'
1127 return f"""export function {method_name}({method_argument_string}): {return_java_ty} {{
1128 if(!isWasmInitialized) {{
1129 throw new Error("initializeWasm() must be awaited first!");
1131 const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1135 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):
1138 out_java_struct = None
1141 out_c += (self.c_fn_ty_pfx)
1142 out_c += (return_type_info.c_ty)
1143 out_java += (return_type_info.java_ty)
1144 if return_type_info.ret_conv is not None:
1145 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1146 out_java += (" " + method_name + "(")
1147 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
1149 method_argument_string = ""
1150 native_call_argument_string = ""
1151 for idx, arg_conv_info in enumerate(argument_types):
1153 method_argument_string += (", ")
1154 native_call_argument_string += ', '
1156 if arg_conv_info.c_ty != "void":
1157 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1158 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1159 native_call_argument_string += arg_conv_info.arg_name
1160 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)
1162 out_java_struct = ""
1164 out_java_struct += ("\t// Skipped " + method_name + "\n")
1167 out_java_struct += (
1168 "\tpublic static constructor_" + meth_n + "(")
1170 out_java_struct += ("\tpublic " + meth_n + "(")
1171 for idx, arg in enumerate(argument_types):
1173 if not takes_self or idx > 1:
1174 out_java_struct += (", ")
1177 if arg.java_ty != "void":
1178 if arg.arg_name in default_constructor_args:
1179 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1180 if explode_idx != 0:
1181 out_java_struct += (", ")
1182 out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1184 out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1187 if out_java_struct is not None:
1188 out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1189 for info in argument_types:
1190 if info.arg_conv is not None:
1191 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1192 if return_type_info.ret_conv is not None:
1193 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1194 elif return_type_info.c_ty != "void":
1195 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1198 if c_call_string is None:
1199 out_c += (method_name + "(")
1201 out_c += (c_call_string)
1202 for idx, info in enumerate(argument_types):
1203 if info.arg_conv_name is not None:
1206 elif c_call_string is not None:
1208 out_c += (info.arg_conv_name)
1210 if return_type_info.ret_conv is not None:
1211 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1214 for info in argument_types:
1215 if info.arg_conv_cleanup is not None:
1216 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1217 if return_type_info.ret_conv is not None:
1218 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1219 elif return_type_info.c_ty != "void":
1220 out_c += ("\n\treturn ret_val;")
1221 out_c += ("\n}\n\n")
1224 out_java_struct += ("\t\t")
1225 if return_type_info.java_ty != "void":
1226 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1227 out_java_struct += ("bindings." + method_name + "(")
1228 for idx, info in enumerate(argument_types):
1230 out_java_struct += (", ")
1231 if idx == 0 and takes_self:
1232 out_java_struct += ("this.ptr")
1233 elif info.arg_name in default_constructor_args:
1234 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1235 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1236 if explode_idx != 0:
1237 out_java_struct += (", ")
1238 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1239 if explode_arg.from_hu_conv is not None:
1240 out_java_struct += (
1241 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1243 out_java_struct += (expl_arg_name)
1244 out_java_struct += (")")
1245 elif info.from_hu_conv is not None:
1246 out_java_struct += (info.from_hu_conv[0])
1248 out_java_struct += (info.arg_name)
1249 out_java_struct += (");\n")
1250 if return_type_info.to_hu_conv is not None:
1252 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1253 return_type_info.to_hu_conv_name) + "\n")
1255 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1257 for idx, info in enumerate(argument_types):
1258 if idx == 0 and takes_self:
1260 elif info.arg_name in default_constructor_args:
1261 for explode_arg in default_constructor_args[info.arg_name]:
1262 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1263 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1264 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1265 expl_arg_name).replace(
1266 "this", return_type_info.to_hu_conv_name) + ";\n")
1267 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1268 if not takes_self and return_type_info.to_hu_conv_name is not None:
1269 out_java_struct += (
1270 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1272 out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1274 if return_type_info.to_hu_conv_name is not None:
1275 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1276 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1277 out_java_struct += ("\t\treturn ret;\n")
1278 out_java_struct += ("\t}\n\n")
1280 return (out_java, out_c, out_java_struct)
1283 for struct in self.struct_file_suffixes:
1284 with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1285 src.write(self.struct_file_suffixes[struct])
1287 with open(self.outdir + "/bindings.mts", "a") as bindings:
1290 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) {
1291 const weak: WeakRef<object> = js_objs[obj_ptr];
1292 if (weak == null || weak == undefined) {
1293 console.error("Got function call on unknown/free'd JS object!");
1294 throw new Error("Got function call on unknown/free'd JS object!");
1296 const obj: object = weak.deref();
1297 if (obj == null || obj == undefined) {
1298 console.error("Got function call on GC'd JS object!");
1299 throw new Error("Got function call on GC'd JS object!");
1303 bindings.write("\tswitch (fn_id) {\n")
1304 for f in self.function_ptrs:
1305 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
1307 bindings.write("""\t\tdefault:
1308 console.error("Got unknown function call from C!");
1309 throw new Error("Got unknown function call from C!");
1311 if (fn == null || fn == undefined) {
1312 console.error("Got function call on incorrect JS object!");
1313 throw new Error("Got function call on incorrect JS object!");
1315 return fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);