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, **kwargs):
16 self.c_type_map = dict(
17 uint8_t = ['number', 'Uint8Array'],
18 uint16_t = ['number', 'Uint16Array'],
19 uint32_t = ['number', 'Uint32Array'],
20 uint64_t = ['number'],
23 self.wasm_decoding_map = dict(
24 int8_tArray = 'decodeArray'
27 self.wasm_encoding_map = dict(
28 int8_tArray = 'encodeArray',
31 self.to_hu_conv_templates = dict(
32 ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
33 default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
36 self.bindings_header = self.wasm_import_header(target) + """
37 export class VecOrSliceDef {
38 public dataptr: number;
39 public datalen: number;
40 public stride: number;
41 public constructor(dataptr: number, datalen: number, stride: number) {
42 this.dataptr = dataptr;
43 this.datalen = datalen;
51 System.loadLibrary(\"lightningjni\");
52 init(java.lang.Enum.class, VecOrSliceDef.class);
56 static native void init(java.lang.Class c, java.lang.Class slicedef);
57 static native void init_class_cache();
59 public static native boolean deref_bool(long ptr);
60 public static native long deref_long(long ptr);
61 public static native void free_heap_ptr(long ptr);
62 public static native byte[] read_bytes(long ptr, long len);
63 public static native byte[] get_u8_slice_bytes(long slice_ptr);
64 public static native long bytes_to_u8_vec(byte[] bytes);
65 public static native long new_txpointer_copy_data(byte[] txdata);
66 public static native void txpointer_free(long ptr);
67 public static native byte[] txpointer_get_buffer(long ptr);
68 public static native long vec_slice_len(long vec);
69 public static native long new_empty_slice_vec();
74 self.bindings_footer = """
75 export async function initializeWasm(allowDoubleInitialization: boolean = false): Promise<void> {
76 if(isWasmInitialized && !allowDoubleInitialization) {
79 const wasmInstance = await WebAssembly.instantiate(wasmModule, imports)
80 wasm = wasmInstance.exports;
81 isWasmInitialized = true;
85 self.common_base = """
86 export default class CommonBase {
88 ptrs_to: object[] = []; // new LinkedList(); TODO: build linked list implementation
89 protected constructor(ptr: number) { this.ptr = ptr; }
90 public _test_only_get_ptr(): number { return this.ptr; }
91 protected finalize() {
92 // TODO: finalize myself
97 self.c_file_pfx = """#include <rust_types.h>
99 #include <stdatomic.h>
100 #include <lightning.h>
102 // These should be provided...somehow...
103 void *memset(void *s, int c, size_t n);
104 void *memcpy(void *dest, const void *src, size_t n);
105 int memcmp(const void *s1, const void *s2, size_t n);
107 void __attribute__((noreturn)) abort(void);
108 static inline void assert(bool expression) {
109 if (!expression) { abort(); }
114 self.c_file_pfx = self.c_file_pfx + """
115 void *malloc(size_t size);
116 void free(void *ptr);
118 #define MALLOC(a, _) malloc(a)
119 #define FREE(p) if ((long)(p) > 1024) { free(p); }
120 #define DO_ASSERT(a) (void)(a)
124 self.c_file_pfx = self.c_file_pfx + """
125 // Always run a, then assert it is true:
126 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
127 // Assert a is true or do nothing
128 #define CHECK(a) DO_ASSERT(a)
130 // Running a leak check across all the allocations and frees of the JDK is a mess,
131 // so instead we implement our own naive leak checker here, relying on the -wrap
132 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
133 // and free'd in Rust or C across the generated bindings shared library.
136 typedef struct allocation {
137 struct allocation* next;
139 const char* struct_name;
141 static allocation* allocation_ll = NULL;
143 void* __real_malloc(size_t len);
144 void* __real_calloc(size_t nmemb, size_t len);
145 static void new_allocation(void* res, const char* struct_name) {
146 allocation* new_alloc = __real_malloc(sizeof(allocation));
147 new_alloc->ptr = res;
148 new_alloc->struct_name = struct_name;
149 new_alloc->next = allocation_ll;
150 allocation_ll = new_alloc;
152 static void* MALLOC(size_t len, const char* struct_name) {
153 void* res = __real_malloc(len);
154 new_allocation(res, struct_name);
157 void __real_free(void* ptr);
158 static void alloc_freed(void* ptr) {
159 allocation* p = NULL;
160 allocation* it = allocation_ll;
161 while (it->ptr != ptr) {
162 p = it; it = it->next;
164 //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
165 return; // addrsan should catch malloc-unknown and print more info than we have
168 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
169 DO_ASSERT(it->ptr == ptr);
172 static void FREE(void* ptr) {
173 if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
178 void* __wrap_malloc(size_t len) {
179 void* res = __real_malloc(len);
180 new_allocation(res, "malloc call");
183 void* __wrap_calloc(size_t nmemb, size_t len) {
184 void* res = __real_calloc(nmemb, len);
185 new_allocation(res, "calloc call");
188 void __wrap_free(void* ptr) {
189 if (ptr == NULL) return;
194 void* __real_realloc(void* ptr, size_t newlen);
195 void* __wrap_realloc(void* ptr, size_t len) {
196 if (ptr != NULL) alloc_freed(ptr);
197 void* res = __real_realloc(ptr, len);
198 new_allocation(res, "realloc call");
201 void __wrap_reallocarray(void* ptr, size_t new_sz) {
202 // Rust doesn't seem to use reallocarray currently
206 void __attribute__((destructor)) check_leaks() {
207 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
208 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
210 DO_ASSERT(allocation_ll == NULL);
213 self.c_file_pfx = self.c_file_pfx + """
214 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
215 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
216 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
217 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
219 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
221 //typedef struct int64_tArray { uint32_t *len; /* len + 1 is data */ } int64_tArray;
222 //typedef struct uint32_tArray { uint32_t *len; /* len + 1 is data */ } uint32_tArray;
223 //typedef struct ptrArray { uint32_t *len; /* len + 1 is data */ } ptrArray;
224 //typedef struct int8_tArray { uint32_t *len; /* len + 1 is data */ } int8_tArray;
225 typedef uint32_t int64_tArray;
226 typedef uint32_t int8_tArray;
227 typedef uint32_t uint32_tArray;
228 typedef uint32_t ptrArray;
229 typedef uint32_t jstring;
231 static inline uint32_t init_arr(size_t arr_len, size_t elem_size, const char *type_desc) {
232 uint32_t *elems = (uint32_t*)MALLOC(arr_len * elem_size + 4, type_desc);
234 return (uint32_t)elems;
237 jstring str_ref_to_ts(const char* chars, size_t len) {
238 char* err_buf = MALLOC(len + 4, "str conv buf");
239 *((uint32_t*)err_buf) = len;
240 memcpy(err_buf + 4, chars, len);
241 return (uint32_t) err_buf;
244 typedef bool jboolean;
248 self.hu_struct_file_prefix = f"""
249 import CommonBase from './CommonBase';
250 import * as bindings from '../bindings' // TODO: figure out location
253 self.c_fn_ty_pfx = ""
254 self.file_ext = ".ts"
255 self.ptr_c_ty = "uint32_t"
256 self.ptr_native_ty = "number"
257 self.result_c_ty = "uint32_t"
258 self.ptr_arr = "ptrArray"
259 self.get_native_arr_len_call = ("*((uint32_t*)", ")")
261 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
263 def create_native_arr_call(self, arr_len, ty_info):
264 if ty_info.c_ty == "int8_tArray":
265 return "init_arr(" + arr_len + ", sizeof(uint8_t), \"Native int8_tArray Bytes\")"
266 elif ty_info.c_ty == "int64_tArray":
267 return "init_arr(" + arr_len + ", sizeof(uint64_t), \"Native int64_tArray Bytes\")"
268 elif ty_info.c_ty == "uint32_tArray":
269 return "init_arr(" + arr_len + ", sizeof(uint32_t), \"Native uint32_tArray Bytes\")"
270 elif ty_info.c_ty == "ptrArray":
271 assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
272 return "init_arr(" + arr_len + ", sizeof(uint32_t), \"Native ptrArray Bytes\")"
274 print("Need to create arr!", ty_info.c_ty)
276 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
277 if ty_info.c_ty == "int8_tArray":
278 return ("memcpy((uint8_t*)(" + arr_name + " + 4), ", ", " + arr_len + ")")
281 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
282 if ty_info.c_ty == "int8_tArray":
284 return "memcpy(" + dest_name + ", (uint8_t*)(" + arr_name + " + 4), " + arr_len + ")"
286 return "(int8_t*)(" + arr_name + " + 4)"
288 return "(" + ty_info.subty.c_ty + "*)(" + arr_name + " + 4)"
289 def get_native_arr_elem(self, arr_name, idxc, ty_info):
290 assert False # Only called if above is None
291 def get_native_arr_ptr_call(self, ty_info):
292 if ty_info.subty is not None:
293 return "(" + ty_info.subty.c_ty + "*)(", " + 4)"
294 return "(" + ty_info.c_ty + "*)(", " + 4)"
295 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
297 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
298 if ty_info.c_ty == "int8_tArray":
303 def str_ref_to_c_call(self, var_name, str_len):
304 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
306 def c_fn_name_define_pfx(self, fn_name, have_args):
307 return " __attribute__((visibility(\"default\"))) TS_" + fn_name + "("
309 def wasm_import_header(self, target):
310 if target == Target.NODEJS:
312 import * as fs from 'fs';
313 const source = fs.readFileSync('./ldk.wasm');
315 const memory = new WebAssembly.Memory({initial: 256});
316 const wasmModule = new WebAssembly.Module(source);
318 const imports: any = {};
321 imports.env.memoryBase = 0;
322 imports.env.memory = memory;
323 imports.env.tableBase = 0;
324 imports.env.table = new WebAssembly.Table({initial: 4, element: 'anyfunc'});
326 imports.env["abort"] = function () {
327 console.error("ABORT");
331 let isWasmInitialized: boolean = false;
336 const nextMultipleOfFour = (value: number) => {
337 return Math.ceil(value / 4) * 4;
340 const encodeArray = (inputArray) => {
341 const cArrayPointer = wasm.wasm_malloc((inputArray.length + 1) * 4);
342 const arrayMemoryView = new Uint32Array(memory.buffer, cArrayPointer + 4, inputArray.length);
343 arrayMemoryView.set(inputArray, 1);
344 arrayMemoryView[0] = inputArray.length;
345 return cArrayPointer;
348 const getArrayLength = (arrayPointer) => {
349 const arraySizeViewer = new Uint32Array(
350 memory.buffer, // value
351 arrayPointer, // offset
354 return arraySizeViewer[0];
356 const decodeUint8Array = (arrayPointer, free = true) => {
357 const arraySize = getArrayLength(arrayPointer);
358 const actualArrayViewer = new Uint8Array(
359 memory.buffer, // value
360 arrayPointer + 4, // offset (ignoring length bytes)
361 arraySize // uint8 count
363 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
364 // will free the underlying memory when it becomes unreachable instead of copying here.
365 const actualArray = actualArrayViewer.slice(0, arraySize);
367 wasm.free(arrayPointer);
371 const decodeUint32Array = (arrayPointer, free = true) => {
372 const arraySize = getArrayLength(arrayPointer);
373 const actualArrayViewer = new Uint32Array(
374 memory.buffer, // value
375 arrayPointer + 4, // offset (ignoring length bytes)
376 arraySize // uint32 count
378 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
379 // will free the underlying memory when it becomes unreachable instead of copying here.
380 const actualArray = actualArrayViewer.slice(0, arraySize);
382 wasm.free(arrayPointer);
387 const encodeString = (string) => {
388 // make malloc count divisible by 4
389 const memoryNeed = nextMultipleOfFour(string.length + 1);
390 const stringPointer = wasm.wasm_malloc(memoryNeed);
391 const stringMemoryView = new Uint8Array(
392 memory.buffer, // value
393 stringPointer, // offset
394 string.length + 1 // length
396 for (let i = 0; i < string.length; i++) {
397 stringMemoryView[i] = string.charCodeAt(i);
399 stringMemoryView[string.length] = 0;
400 return stringPointer;
403 const decodeString = (stringPointer, free = true) => {
404 const memoryView = new Uint8Array(memory.buffer, stringPointer);
408 while (memoryView[cursor] !== 0) {
409 result += String.fromCharCode(memoryView[cursor]);
414 wasm.wasm_free(stringPointer);
425 def native_c_unitary_enum_map(self, struct_name, variants):
426 out_c = "static inline " + struct_name + " " + struct_name + "_from_js(int32_t ord) {\n"
427 out_c = out_c + "\tswitch (ord) {\n"
430 out_typescript_enum_fields = ""
433 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
435 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
436 out_c = out_c + "\t}\n"
437 out_c = out_c + "\tabort();\n"
438 out_c = out_c + "}\n"
440 out_c = out_c + "static inline int32_t " + struct_name + "_to_js(" + struct_name + " val) {\n"
441 out_c = out_c + "\tswitch (val) {\n"
444 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
446 out_c = out_c + "\t\tdefault: abort();\n"
447 out_c = out_c + "\t}\n"
448 out_c = out_c + "}\n"
450 out_typescript_enum = f"""
451 export enum {struct_name} {{
452 {out_typescript_enum_fields}
456 return (out_c, out_typescript_enum, "")
458 def c_unitary_enum_to_native_call(self, ty_info):
459 return (ty_info.rust_obj + "_to_js(", ")")
460 def native_unitary_enum_to_c_call(self, ty_info):
461 return (ty_info.rust_obj + "_from_js(", ")")
463 def c_complex_enum_pass_ty(self, struct_name):
466 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
467 ret = "0 /* " + struct_name + " - " + variant + " */"
468 for param in c_params:
469 ret = ret + "; (void) " + param
472 def native_c_map_trait(self, struct_name, field_var_conversions, field_function_lines):
473 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
475 constructor_arguments = ""
476 super_instantiator = ""
477 pointer_to_adder = ""
478 impl_constructor_arguments = ""
479 for var in field_var_conversions:
480 if isinstance(var, ConvInfo):
481 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
482 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
483 if var.from_hu_conv is not None:
484 super_instantiator += ", " + var.from_hu_conv[0]
485 if var.from_hu_conv[1] != "":
486 pointer_to_adder += var.from_hu_conv[1] + ";\n"
488 super_instantiator += ", " + first_to_lower(var.arg_name)
490 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
491 super_instantiator += ", " + first_to_lower(var[1])
492 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
493 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
495 # BUILD INTERFACE METHODS
496 out_java_interface = ""
497 out_interface_implementation_overrides = ""
499 for fn_line in field_function_lines:
500 java_method_descriptor = ""
501 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
502 out_java_interface += fn_line.fn_name + "("
503 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
505 for idx, arg_conv_info in enumerate(fn_line.args_ty):
507 out_java_interface += ", "
508 out_interface_implementation_overrides += ", "
509 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
510 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
511 java_method_descriptor += arg_conv_info.java_fn_ty_arg
512 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
513 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
514 java_methods.append((fn_line.fn_name, java_method_descriptor))
516 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
518 interface_method_override_inset = "\t\t\t\t\t\t"
519 interface_implementation_inset = "\t\t\t\t\t\t\t"
520 for arg_info in fn_line.args_ty:
521 if arg_info.to_hu_conv is not None:
522 out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
524 if fn_line.ret_ty_info.java_ty != "void":
525 out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
527 out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
529 for idx, arg_info in enumerate(fn_line.args_ty):
531 out_interface_implementation_overrides += ", "
532 if arg_info.to_hu_conv_name is not None:
533 out_interface_implementation_overrides += arg_info.to_hu_conv_name
535 out_interface_implementation_overrides += arg_info.arg_name
537 out_interface_implementation_overrides += ");\n"
538 if fn_line.ret_ty_info.java_ty != "void":
539 if fn_line.ret_ty_info.from_hu_conv is not None:
540 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\t" + f"result: {fn_line.ret_ty_info.java_ty} = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
541 if fn_line.ret_ty_info.from_hu_conv[1] != "":
542 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
543 #if fn_line.ret_ty_info.rust_obj in result_types:
544 # XXX: We need to handle this in conversion logic so that its cross-language!
545 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
546 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
547 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
549 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
550 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
552 trait_constructor_arguments = ""
553 for var in field_var_conversions:
554 if isinstance(var, ConvInfo):
555 trait_constructor_arguments += ", " + var.arg_name
557 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl).bindings_instance"
559 out_typescript_human = f"""
560 {self.hu_struct_file_prefix}
562 export class {struct_name.replace("LDK","")} extends CommonBase {{
564 bindings_instance?: bindings.{struct_name};
566 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
567 if (Number.isFinite(ptr)) {{
569 this.bindings_instance = null;
571 // TODO: private constructor instantiation
572 super(bindings.{struct_name}_new(arg{super_instantiator}));
573 this.ptrs_to.push(arg);
578 protected finalize() {{
579 if (this.ptr != 0) {{
580 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
585 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
586 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
587 let structImplementation = <bindings.{struct_name}>{{
588 // todo: in-line interface filling
589 {out_interface_implementation_overrides}
591 impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
595 export interface {struct_name.replace("LDK", "")}Interface {{
599 class {struct_name}Holder {{
600 held: {struct_name.replace("LDK", "")};
604 out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
606 for fn_line in field_function_lines:
607 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
608 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
610 for idx, arg_conv_info in enumerate(fn_line.args_ty):
612 out_typescript_bindings = out_typescript_bindings + ", "
613 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
615 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
617 out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
619 out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
620 for var in field_var_conversions:
621 if isinstance(var, ConvInfo):
622 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
624 out_typescript_bindings += f", {var[1]}: {var[0]}"
626 out_typescript_bindings += f"""): number {{
627 throw new Error('unimplemented'); // TODO: bind to WASM
631 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
633 # Now that we've written out our java code (and created java_meths), generate C
634 out_c = "typedef struct " + struct_name + "_JCalls {\n"
635 out_c = out_c + "\tatomic_size_t refcnt;\n"
636 for var in field_var_conversions:
637 if isinstance(var, ConvInfo):
638 # We're a regular ol' field
642 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
643 for fn in field_function_lines:
644 if fn.fn_name != "free" and fn.fn_name != "clone":
645 out_c = out_c + "\tuint32_t " + fn.fn_name + "_meth;\n"
646 out_c = out_c + "} " + struct_name + "_JCalls;\n"
648 for fn_line in field_function_lines:
649 if fn_line.fn_name == "free":
650 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
651 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
652 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
653 for fn in field_function_lines:
654 if fn.fn_name != "free" and fn.fn_name != "clone":
655 out_c = out_c + "\t\tjs_free(j_calls->" + fn.fn_name + "_meth);\n"
656 out_c = out_c + "\t\tFREE(j_calls);\n"
657 out_c = out_c + "\t}\n}\n"
659 for idx, fn_line in enumerate(field_function_lines):
660 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
661 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
662 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_jcall("
663 if fn_line.self_is_const:
664 out_c = out_c + "const void* this_arg"
666 out_c = out_c + "void* this_arg"
668 for idx, arg in enumerate(fn_line.args_ty):
669 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
671 out_c = out_c + ") {\n"
672 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
674 for arg_info in fn_line.args_ty:
675 if arg_info.ret_conv is not None:
676 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
677 out_c = out_c + arg_info.arg_name
678 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
680 if fn_line.ret_ty_info.c_ty.endswith("Array"):
681 out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " arg = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
682 elif fn_line.ret_ty_info.java_ty == "void":
683 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
684 elif not fn_line.ret_ty_info.passed_as_ptr:
685 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
687 out_c = out_c + "\t" + fn_line.ret_ty_info.rust_obj + "* ret = (" + fn_line.ret_ty_info.rust_obj + "*)js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
689 for idx, arg_info in enumerate(fn_line.args_ty):
690 if arg_info.ret_conv is not None:
691 out_c = out_c + ", " + arg_info.ret_conv_name
693 out_c = out_c + ", " + arg_info.arg_name
694 out_c = out_c + ");\n"
695 if fn_line.ret_ty_info.arg_conv is not None:
696 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"
698 out_c = out_c + "}\n"
700 # Write out a clone function whether we need one or not, as we use them in moving to rust
701 out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
702 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
703 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
704 for var in field_var_conversions:
705 if not isinstance(var, ConvInfo):
706 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
707 out_c = out_c + "\treturn (void*) this_arg;\n"
708 out_c = out_c + "}\n"
710 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (/*TODO: JS Object Reference */void* o"
711 for var in field_var_conversions:
712 if isinstance(var, ConvInfo):
713 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
715 out_c = out_c + ", /*TODO: JS Object Reference */void* " + var[1]
716 out_c = out_c + ") {\n"
718 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
719 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
720 out_c = out_c + "\t//TODO: Assign calls->o from o\n"
722 for (fn_name, java_meth_descr) in java_meths:
723 if fn_name != "free" and fn_name != "clone":
724 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
725 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
727 for var in field_var_conversions:
728 if isinstance(var, ConvInfo) and var.arg_conv is not None:
729 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
730 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
731 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
732 for fn_line in field_function_lines:
733 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
734 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_jcall,\n"
735 elif fn_line.fn_name == "free":
736 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
738 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
739 for var in field_var_conversions:
740 if isinstance(var, ConvInfo):
741 if var.arg_conv_name is not None:
742 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
743 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
745 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
746 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
748 out_c = out_c + "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1] + "),\n"
749 out_c = out_c + "\t};\n"
750 for var in field_var_conversions:
751 if not isinstance(var, ConvInfo):
752 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
753 out_c = out_c + "\treturn ret;\n"
754 out_c = out_c + "}\n"
756 out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "/*TODO: JS Object Reference */void* o"
757 for var in field_var_conversions:
758 if isinstance(var, ConvInfo):
759 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
761 out_c = out_c + ", /*TODO: JS Object Reference */ void* " + var[1]
762 out_c = out_c + ") {\n"
763 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
764 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
765 for var in field_var_conversions:
766 if isinstance(var, ConvInfo):
767 out_c = out_c + ", " + var.arg_name
769 out_c = out_c + ", " + var[1]
770 out_c = out_c + ");\n"
771 out_c = out_c + "\treturn (long)res_ptr;\n"
772 out_c = out_c + "}\n"
774 return (out_typescript_bindings, out_typescript_human, out_c)
776 def trait_struct_inc_refcnt(self, ty_info):
779 def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
780 java_hu_type = struct_name.replace("LDK", "")
786 out_java_enum += (self.hu_struct_file_prefix)
787 out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
788 out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
789 out_java_enum += ("\tprotected finalize() {\n")
790 out_java_enum += ("\t\tsuper.finalize();\n")
791 out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
792 out_java_enum += ("\t}\n")
793 out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
794 out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
795 java_hu_subclasses = ""
797 out_java += ("\tpublic static class " + struct_name + " {\n")
798 out_java += ("\t\tprivate " + struct_name + "() {}\n")
799 for var in variant_list:
800 out_java += ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
801 java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
802 out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
803 out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
804 init_meth_params = ""
807 for idx, field_ty in enumerate(var.fields):
808 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
809 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
810 if field_ty.to_hu_conv is not None:
811 hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
812 hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
813 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
815 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
817 init_meth_params = init_meth_params + ", "
818 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
819 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
820 out_java += ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
821 out_java += (init_meth_body)
823 out_java += ("\t\t}\n")
824 out_java_enum += ("\t\t}\n")
825 java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
826 java_hu_subclasses = java_hu_subclasses + hu_conv_body
827 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
828 out_java += ("\t\tstatic native void init();\n")
829 out_java += ("\t}\n")
830 out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
831 out_java += ("\tstatic { " + struct_name + ".init(); }\n")
832 out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
834 out_c += (self.c_fn_ty_pfx + self.c_complex_enum_pass_ty(struct_name) + self.c_fn_name_define_pfx(struct_name + "_ref_from_ptr", True) + self.ptr_c_ty + " ptr) {\n")
835 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
836 out_c += ("\tswitch(obj->tag) {\n")
837 for var in variant_list:
838 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
840 for idx, field_map in enumerate(var.fields):
841 if field_map.ret_conv is not None:
842 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
843 out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
844 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
845 c_params.append(field_map.ret_conv_name)
847 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
848 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
850 out_c += ("\t\tdefault: abort();\n")
851 out_c += ("\t}\n}\n")
852 out_java_enum += ("}\n")
853 out_java_enum += (java_hu_subclasses)
854 return (out_java, out_java_enum, out_c)
856 def map_opaque_struct(self, struct_name):
859 if struct_name.startswith("LDKLocked"):
860 implementations += "implements AutoCloseable "
866 protected finalize() {
870 out_opaque_struct_human = f"""
871 {self.hu_struct_file_prefix}
873 export default class {struct_name.replace("LDK","")} extends CommonBase {implementations}{{
874 constructor(_dummy: object, ptr: number) {{
879 if (this.ptr != 0) {{
880 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
884 return out_opaque_struct_human
886 def map_function(self, argument_types, c_call_string, is_free, method_name, return_type_info, struct_meth, default_constructor_args, takes_self, args_known, has_out_java_struct: bool, type_mapping_generator):
889 out_java_struct = None
891 out_java += ("\tpublic static native ")
892 out_c += (self.c_fn_ty_pfx)
893 out_c += (return_type_info.c_ty)
894 out_java += (return_type_info.java_ty)
895 if return_type_info.ret_conv is not None:
896 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
897 out_java += (" " + method_name + "(")
898 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
900 method_argument_string = ""
901 native_call_argument_string = ""
902 for idx, arg_conv_info in enumerate(argument_types):
904 method_argument_string += (", ")
905 native_call_argument_string += ', '
907 if arg_conv_info.c_ty != "void":
908 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
909 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
910 native_argument = arg_conv_info.arg_name
912 converter = self.wasm_encoding_map[arg_conv_info.c_ty]
913 native_argument = f"{converter}({arg_conv_info.arg_name})"
914 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
915 native_call_argument_string += native_argument
917 has_return_value = return_type_info.c_ty != 'void'
918 needs_decoding = return_type_info.c_ty in self.wasm_decoding_map
919 return_statement = 'return nativeResponseValue;'
920 if not has_return_value:
921 return_statement = '// debug statements here'
923 converter = self.wasm_decoding_map[return_type_info.c_ty]
924 return_statement = f"return {converter}(nativeResponseValue);"
926 out_java = f"""\texport function {method_name}({method_argument_string}): {return_type_info.java_ty} {{
927 if(!isWasmInitialized) {{
928 throw new Error("initializeWasm() must be awaited first!");
930 const nativeResponseValue = wasm.{method_name}({native_call_argument_string});
935 if has_out_java_struct:
938 out_java_struct += ("\t// Skipped " + method_name + "\n")
939 has_out_java_struct = False
941 meth_n = method_name[len(struct_meth) + 1:]
944 "\tpublic static " + return_type_info.java_hu_ty + " constructor_" + meth_n + "(")
946 out_java_struct += ("\tpublic " + return_type_info.java_hu_ty + " " + meth_n + "(")
947 for idx, arg in enumerate(argument_types):
949 if not takes_self or idx > 1:
950 out_java_struct += (", ")
953 if arg.java_ty != "void":
954 if arg.arg_name in default_constructor_args:
955 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
957 out_java_struct += (", ")
959 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
961 out_java_struct += (arg.java_hu_ty + " " + arg.arg_name)
964 if out_java_struct is not None:
965 out_java_struct += (") {\n")
966 for info in argument_types:
967 if info.arg_conv is not None:
968 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
969 if return_type_info.ret_conv is not None:
970 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
971 elif return_type_info.c_ty != "void":
972 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
975 if c_call_string is None:
976 out_c += (method_name + "(")
978 out_c += (c_call_string)
979 for idx, info in enumerate(argument_types):
980 if info.arg_conv_name is not None:
983 elif c_call_string is not None:
985 out_c += (info.arg_conv_name)
987 if return_type_info.ret_conv is not None:
988 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
991 for info in argument_types:
992 if info.arg_conv_cleanup is not None:
993 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
994 if return_type_info.ret_conv is not None:
995 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
996 elif return_type_info.c_ty != "void":
997 out_c += ("\n\treturn ret_val;")
1000 if has_out_java_struct:
1001 out_java_struct += ("\t\t")
1002 if return_type_info.java_ty != "void":
1003 out_java_struct += (return_type_info.java_ty + " ret = ")
1004 out_java_struct += ("bindings." + method_name + "(")
1005 for idx, info in enumerate(argument_types):
1007 out_java_struct += (", ")
1008 if idx == 0 and takes_self:
1009 out_java_struct += ("this.ptr")
1010 elif info.arg_name in default_constructor_args:
1011 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1012 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1013 if explode_idx != 0:
1014 out_java_struct += (", ")
1015 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1016 if explode_arg.from_hu_conv is not None:
1017 out_java_struct += (
1018 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1020 out_java_struct += (expl_arg_name)
1021 out_java_struct += (")")
1022 elif info.from_hu_conv is not None:
1023 out_java_struct += (info.from_hu_conv[0])
1025 out_java_struct += (info.arg_name)
1026 out_java_struct += (");\n")
1027 if return_type_info.to_hu_conv is not None:
1029 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1030 return_type_info.to_hu_conv_name) + "\n")
1032 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1034 for idx, info in enumerate(argument_types):
1035 if idx == 0 and takes_self:
1037 elif info.arg_name in default_constructor_args:
1038 for explode_arg in default_constructor_args[info.arg_name]:
1039 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1040 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1041 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1042 expl_arg_name).replace(
1043 "this", return_type_info.to_hu_conv_name) + ";\n")
1044 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1045 if not takes_self and return_type_info.to_hu_conv_name is not None:
1046 out_java_struct += (
1047 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name) + ";\n")
1049 out_java_struct += ("\t\t" + info.from_hu_conv[1] + ";\n")
1051 if return_type_info.to_hu_conv_name is not None:
1052 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1053 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1054 out_java_struct += ("\t\treturn ret;\n")
1055 out_java_struct += ("\t}\n\n")
1057 return (out_java, out_c, out_java_struct)