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'],
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>
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 void __attribute__((noreturn)) abort(void);
107 void assert(scalar expression);
111 self.c_file_pfx = self.c_file_pfx + """
112 void *malloc(size_t size);
113 void free(void *ptr);
115 #define MALLOC(a, _) malloc(a)
116 #define FREE(p) if ((long)(p) > 1024) { free(p); }
117 #define DO_ASSERT(a) (void)(a)
121 self.c_file_pfx = self.c_file_pfx + """
122 // Always run a, then assert it is true:
123 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
124 // Assert a is true or do nothing
125 #define CHECK(a) DO_ASSERT(a)
127 // Running a leak check across all the allocations and frees of the JDK is a mess,
128 // so instead we implement our own naive leak checker here, relying on the -wrap
129 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
130 // and free'd in Rust or C across the generated bindings shared library.
133 typedef struct allocation {
134 struct allocation* next;
136 const char* struct_name;
138 static allocation* allocation_ll = NULL;
140 void* __real_malloc(size_t len);
141 void* __real_calloc(size_t nmemb, size_t len);
142 static void new_allocation(void* res, const char* struct_name) {
143 allocation* new_alloc = __real_malloc(sizeof(allocation));
144 new_alloc->ptr = res;
145 new_alloc->struct_name = struct_name;
146 new_alloc->next = allocation_ll;
147 allocation_ll = new_alloc;
149 static void* MALLOC(size_t len, const char* struct_name) {
150 void* res = __real_malloc(len);
151 new_allocation(res, struct_name);
154 void __real_free(void* ptr);
155 static void alloc_freed(void* ptr) {
156 allocation* p = NULL;
157 allocation* it = allocation_ll;
158 while (it->ptr != ptr) {
159 p = it; it = it->next;
161 //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
162 return; // addrsan should catch malloc-unknown and print more info than we have
165 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
166 DO_ASSERT(it->ptr == ptr);
169 static void FREE(void* ptr) {
170 if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
175 void* __wrap_malloc(size_t len) {
176 void* res = __real_malloc(len);
177 new_allocation(res, "malloc call");
180 void* __wrap_calloc(size_t nmemb, size_t len) {
181 void* res = __real_calloc(nmemb, len);
182 new_allocation(res, "calloc call");
185 void __wrap_free(void* ptr) {
186 if (ptr == NULL) return;
191 void* __real_realloc(void* ptr, size_t newlen);
192 void* __wrap_realloc(void* ptr, size_t len) {
193 if (ptr != NULL) alloc_freed(ptr);
194 void* res = __real_realloc(ptr, len);
195 new_allocation(res, "realloc call");
198 void __wrap_reallocarray(void* ptr, size_t new_sz) {
199 // Rust doesn't seem to use reallocarray currently
203 void __attribute__((destructor)) check_leaks() {
204 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
205 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
207 DO_ASSERT(allocation_ll == NULL);
210 self.c_file_pfx = self.c_file_pfx + """
211 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
212 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
213 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
214 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
216 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
218 typedef struct int64_tArray {uint32_t len;int64_t *ptr;} int64_tArray;
219 typedef struct uint32_tArray {uint32_t len;int32_t *ptr;} uint32_tArray;
220 typedef struct int8_tArray {uint32_t len;int8_t *ptr;} int8_tArray;
222 typedef bool jboolean;
226 self.hu_struct_file_prefix = f"""
227 import CommonBase from './CommonBase';
228 import * as bindings from '../bindings' // TODO: figure out location
231 self.c_fn_ty_pfx = ""
232 self.c_fn_name_pfx = ""
233 self.c_fn_args_pfx = "void* ctx_TODO"
234 self.file_ext = ".ts"
235 self.ptr_c_ty = "uint32_t"
236 self.ptr_native_ty = "number" # "uint32_t"
237 self.result_c_ty = "uint32_t"
238 self.ptr_arr = "uint32_tArray"
239 self.get_native_arr_len_call = ("", ".len")
240 self.get_native_arr_ptr_call = ("", ".ptr")
242 def release_native_arr_ptr_call(self, arr_var, arr_ptr_var):
244 def create_native_arr_call(self, arr_len, ty_info):
245 if ty_info.c_ty == "int8_tArray":
246 return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + ", \"Native " + ty_info.c_ty + " Bytes\") }"
247 elif ty_info.c_ty == "int64_tArray":
248 return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int64_t), \"Native " + ty_info.c_ty + " Bytes\") }"
249 elif ty_info.c_ty == "uint32_tArray":
250 return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int32_t), \"Native " + ty_info.c_ty + " Bytes\") }"
252 print("Need to create arr!", ty_info.c_ty)
254 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
255 if ty_info.c_ty == "int8_tArray":
256 return ("memcpy(" + arr_name + ".ptr, ", ", " + arr_len + ")")
259 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
260 if ty_info.c_ty == "int8_tArray":
262 return "memcpy(" + dest_name + ", " + arr_name + ".ptr, " + arr_len + ")"
264 return arr_name + ".ptr"
266 return "(" + ty_info.subty.c_ty + "*) " + arr_name + ".ptr"
267 def get_native_arr_elem(self, arr_name, idxc, ty_info):
268 assert False # Only called if above is None
269 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
270 if ty_info.c_ty == "int8_tArray":
276 def wasm_import_header(self, target):
277 if target == Target.NODEJS:
280 import * as fs from 'fs';
281 const source = fs.readFileSync('./ldk.wasm');
283 const memory = new WebAssembly.Memory({initial: 256});
284 const wasmModule = new WebAssembly.Module(source);
286 const imports: any = {};
289 imports.env.memoryBase = 0;
290 imports.env.memory = memory;
291 imports.env.tableBase = 0;
292 imports.env.table = new WebAssembly.Table({initial: 4, element: 'anyfunc'});
294 imports.env["abort"] = function () {
295 console.error("ABORT");
299 let isWasmInitialized: boolean = false;
304 const nextMultipleOfFour = (value: number) => {
305 return Math.ceil(value / 4) * 4;
308 const encodeArray = (inputArray) => {
309 // TODO: (matt) is this correct, or should it go back to length * 4?
310 // const cArrayPointer = wasm.wasm_malloc(inputArray.length * 4);
311 const cArrayPointer = wasm.wasm_malloc(nextMultipleOfFour(inputArray.length));
313 const arrayMemoryView = new Uint32Array(memory.buffer, cArrayPointer, inputArray.length);
314 arrayMemoryView.set(inputArray);
315 return cArrayPointer;
318 const decodeArray = (arrayPointer, free = true) => {
319 const arraySizeViewer = new Uint32Array(
320 memory.buffer, // value
321 arrayPointer, // offset
324 const arraySize = arraySizeViewer[0];
325 const actualArrayViewer = new Uint32Array(
326 memory.buffer, // value
327 arrayPointer, // offset
330 const actualArray = actualArrayViewer.slice(1, arraySize + 1);
332 // wasm.free_array(arrayPointer);
333 wasm.wasm_free(arrayPointer); // TODO: check if passing *void still captures remaining values
338 const encodeString = (string) => {
339 // make malloc count divisible by 4
340 const memoryNeed = nextMultipleOfFour(string.length + 1);
341 const stringPointer = wasm.wasm_malloc(memoryNeed);
342 const stringMemoryView = new Uint8Array(
343 memory.buffer, // value
344 stringPointer, // offset
345 string.length + 1 // length
347 for (let i = 0; i < string.length; i++) {
348 stringMemoryView[i] = string.charCodeAt(i);
350 stringMemoryView[string.length] = 0;
351 return stringPointer;
354 const decodeString = (stringPointer, free = true) => {
355 const memoryView = new Uint8Array(memory.buffer, stringPointer);
359 while (memoryView[cursor] !== 0) {
360 result += String.fromCharCode(memoryView[cursor]);
365 wasm.wasm_free(stringPointer);
375 def init_str(self, c_array_class_caches):
378 def native_c_unitary_enum_map(self, struct_name, variants):
379 out_c = "static inline " + struct_name + " " + struct_name + "_from_js(int32_t ord) {\n"
380 out_c = out_c + "\tswitch (ord) {\n"
383 out_typescript_enum_fields = ""
386 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
388 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
389 out_c = out_c + "\t}\n"
390 out_c = out_c + "\tabort();\n"
391 out_c = out_c + "}\n"
393 out_c = out_c + "static inline int32_t " + struct_name + "_to_js(" + struct_name + " val) {\n"
394 out_c = out_c + "\tswitch (val) {\n"
397 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
399 out_c = out_c + "\t\tdefault: abort();\n"
400 out_c = out_c + "\t}\n"
401 out_c = out_c + "}\n"
403 out_typescript_enum = f"""
404 export enum {struct_name} {{
405 {out_typescript_enum_fields}
409 return (out_c, out_typescript_enum, "")
411 def c_unitary_enum_to_native_call(self, ty_info):
412 return (ty_info.rust_obj + "_to_js(", ")")
413 def native_unitary_enum_to_c_call(self, ty_info):
414 return (ty_info.rust_obj + "_from_js(", ")")
416 def c_complex_enum_pass_ty(self, struct_name):
419 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
420 ret = "0 /* " + struct_name + " - " + variant + " */"
421 for param in c_params:
422 ret = ret + "; (void) " + param
425 def native_c_map_trait(self, struct_name, field_var_conversions, field_function_lines):
426 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
428 constructor_arguments = ""
429 super_instantiator = ""
430 pointer_to_adder = ""
431 impl_constructor_arguments = ""
432 for var in field_var_conversions:
433 if isinstance(var, ConvInfo):
434 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
435 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
436 if var.from_hu_conv is not None:
437 super_instantiator += ", " + var.from_hu_conv[0]
438 if var.from_hu_conv[1] != "":
439 pointer_to_adder += var.from_hu_conv[1] + ";\n"
441 super_instantiator += ", " + first_to_lower(var.arg_name)
443 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
444 super_instantiator += ", " + first_to_lower(var[1])
445 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
446 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
448 # BUILD INTERFACE METHODS
449 out_java_interface = ""
450 out_interface_implementation_overrides = ""
452 for fn_line in field_function_lines:
453 java_method_descriptor = ""
454 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
455 out_java_interface += fn_line.fn_name + "("
456 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
458 for idx, arg_conv_info in enumerate(fn_line.args_ty):
460 out_java_interface += ", "
461 out_interface_implementation_overrides += ", "
462 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
463 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
464 java_method_descriptor += arg_conv_info.java_fn_ty_arg
465 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
466 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
467 java_methods.append((fn_line.fn_name, java_method_descriptor))
469 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
471 interface_method_override_inset = "\t\t\t\t\t\t"
472 interface_implementation_inset = "\t\t\t\t\t\t\t"
473 for arg_info in fn_line.args_ty:
474 if arg_info.to_hu_conv is not None:
475 out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
477 if fn_line.ret_ty_info.java_ty != "void":
478 out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
480 out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
482 for idx, arg_info in enumerate(fn_line.args_ty):
484 out_interface_implementation_overrides += ", "
485 if arg_info.to_hu_conv_name is not None:
486 out_interface_implementation_overrides += arg_info.to_hu_conv_name
488 out_interface_implementation_overrides += arg_info.arg_name
490 out_interface_implementation_overrides += ");\n"
491 if fn_line.ret_ty_info.java_ty != "void":
492 if fn_line.ret_ty_info.from_hu_conv is not None:
493 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"
494 if fn_line.ret_ty_info.from_hu_conv[1] != "":
495 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"
496 #if fn_line.ret_ty_info.rust_obj in result_types:
497 # XXX: We need to handle this in conversion logic so that its cross-language!
498 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
499 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
500 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
502 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
503 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
505 trait_constructor_arguments = ""
506 for var in field_var_conversions:
507 if isinstance(var, ConvInfo):
508 trait_constructor_arguments += ", " + var.arg_name
510 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl).bindings_instance"
514 out_typescript_human = f"""
515 {self.hu_struct_file_prefix}
517 export class {struct_name.replace("LDK","")} extends CommonBase {{
519 bindings_instance?: bindings.{struct_name};
521 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
522 if (Number.isFinite(ptr)) {{
524 this.bindings_instance = null;
526 // TODO: private constructor instantiation
527 super(bindings.{struct_name}_new(arg{super_instantiator}));
528 this.ptrs_to.push(arg);
533 protected finalize() {{
534 if (this.ptr != 0) {{
535 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
540 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
541 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
542 let structImplementation = <bindings.{struct_name}>{{
544 // todo: in-line interface filling
546 {out_interface_implementation_overrides}
548 impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
553 export interface {struct_name.replace("LDK", "")}Interface {{
557 class {struct_name}Holder {{
558 held: {struct_name.replace("LDK", "")};
565 out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
567 for fn_line in field_function_lines:
568 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
569 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
571 for idx, arg_conv_info in enumerate(fn_line.args_ty):
573 out_typescript_bindings = out_typescript_bindings + ", "
574 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
576 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
578 out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
580 out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
581 for var in field_var_conversions:
582 if isinstance(var, ConvInfo):
583 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
585 out_typescript_bindings += f", {var[1]}: {var[0]}"
587 out_typescript_bindings += f"""): number {{
588 throw new Error('unimplemented'); // TODO: bind to WASM
591 export function {struct_name}_get_obj_from_jcalls(val: number): {struct_name} {{
592 throw new Error('unimplemented'); // TODO: bind to WASM
596 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
598 # Now that we've written out our java code (and created java_meths), generate C
599 out_c = "typedef struct " + struct_name + "_JCalls {\n"
600 out_c = out_c + "\tatomic_size_t refcnt;\n"
601 out_c = out_c + "\tJavaVM *vm;\n"
602 out_c = out_c + "\tjweak o;\n"
603 for var in field_var_conversions:
604 if isinstance(var, ConvInfo):
605 # We're a regular ol' field
609 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
610 for fn in field_function_lines:
611 if fn.fn_name != "free" and fn.fn_name != "clone":
612 out_c = out_c + "\tjmethodID " + fn.fn_name + "_meth;\n"
613 out_c = out_c + "} " + struct_name + "_JCalls;\n"
615 for fn_line in field_function_lines:
616 if fn_line.fn_name == "free":
617 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
618 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
619 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
620 out_c = out_c + "\t\tJNIEnv *env;\n"
621 out_c = out_c + "\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
622 out_c = out_c + "\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n"
623 out_c = out_c + "\t\tFREE(j_calls);\n"
624 out_c = out_c + "\t}\n}\n"
626 for idx, fn_line in enumerate(field_function_lines):
627 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
628 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
629 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_jcall("
630 if fn_line.self_is_const:
631 out_c = out_c + "const void* this_arg"
633 out_c = out_c + "void* this_arg"
635 for idx, arg in enumerate(fn_line.args_ty):
636 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
638 out_c = out_c + ") {\n"
639 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
640 out_c = out_c + "\tJNIEnv *env;\n"
641 out_c = out_c + "\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
643 for arg_info in fn_line.args_ty:
644 if arg_info.ret_conv is not None:
645 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
646 out_c = out_c + arg_info.arg_name
647 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
649 out_c = out_c + "\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tCHECK(obj != NULL);\n"
650 if fn_line.ret_ty_info.c_ty.endswith("Array"):
651 out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " arg = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
652 elif not fn_line.ret_ty_info.passed_as_ptr:
653 out_c = out_c + "\treturn (*env)->Call" + fn_line.ret_ty_info.java_ty.title() + "Method(env, obj, j_calls->" + fn_line.fn_name + "_meth"
655 out_c = out_c + "\t" + fn_line.ret_ty_info.rust_obj + "* ret = (" + fn_line.ret_ty_info.rust_obj + "*)(*env)->CallLongMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
657 for idx, arg_info in enumerate(fn_line.args_ty):
658 if arg_info.ret_conv is not None:
659 out_c = out_c + ", " + arg_info.ret_conv_name
661 out_c = out_c + ", " + arg_info.arg_name
662 out_c = out_c + ");\n"
663 if fn_line.ret_ty_info.arg_conv is not None:
664 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"
666 out_c = out_c + "}\n"
668 # Write out a clone function whether we need one or not, as we use them in moving to rust
669 out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
670 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
671 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
672 for var in field_var_conversions:
673 if not isinstance(var, ConvInfo):
674 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
675 out_c = out_c + "\treturn (void*) this_arg;\n"
676 out_c = out_c + "}\n"
678 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (" + self.c_fn_args_pfx + ", jobject o"
679 for var in field_var_conversions:
680 if isinstance(var, ConvInfo):
681 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
683 out_c = out_c + ", jobject " + var[1]
684 out_c = out_c + ") {\n"
686 out_c = out_c + "\tjclass c = (*env)->GetObjectClass(env, o);\n"
687 out_c = out_c + "\tCHECK(c != NULL);\n"
688 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
689 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
690 out_c = out_c + "\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n"
691 out_c = out_c + "\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n"
693 for (fn_name, java_meth_descr) in java_meths:
694 if fn_name != "free" and fn_name != "clone":
695 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
696 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
698 for var in field_var_conversions:
699 if isinstance(var, ConvInfo) and var.arg_conv is not None:
700 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
701 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
702 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
703 for fn_line in field_function_lines:
704 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
705 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_jcall,\n"
706 elif fn_line.fn_name == "free":
707 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
709 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
710 for var in field_var_conversions:
711 if isinstance(var, ConvInfo):
712 if var.arg_conv_name is not None:
713 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
714 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
716 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
717 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
719 out_c = out_c + "\t\t." + var[1] + " = " + var[0] + "_init(env, clz, " + var[1] + "),\n"
720 out_c = out_c + "\t};\n"
721 for var in field_var_conversions:
722 if not isinstance(var, ConvInfo):
723 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
724 out_c = out_c + "\treturn ret;\n"
725 out_c = out_c + "}\n"
727 out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1new (" + self.c_fn_args_pfx + ", jobject o"
728 for var in field_var_conversions:
729 if isinstance(var, ConvInfo):
730 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
732 out_c = out_c + ", jobject " + var[1]
733 out_c = out_c + ") {\n"
734 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
735 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(env, clz, o"
736 for var in field_var_conversions:
737 if isinstance(var, ConvInfo):
738 out_c = out_c + ", " + var.arg_name
740 out_c = out_c + ", " + var[1]
741 out_c = out_c + ");\n"
742 out_c = out_c + "\treturn (long)res_ptr;\n"
743 out_c = out_c + "}\n"
745 out_c = out_c + self.c_fn_ty_pfx + "jobject " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1obj_1from_1jcalls (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " val) {\n"
746 out_c = out_c + "\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n"
747 out_c = out_c + "\tCHECK(ret != NULL);\n"
748 out_c = out_c + "\treturn ret;\n"
749 out_c = out_c + "}\n"
752 return (out_typescript_bindings, out_typescript_human, out_c)
754 def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
755 java_hu_type = struct_name.replace("LDK", "")
761 out_java_enum += (self.hu_struct_file_prefix)
762 out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
763 out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
764 out_java_enum += ("\tprotected finalize() {\n")
765 out_java_enum += ("\t\tsuper.finalize();\n")
766 out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
767 out_java_enum += ("\t}\n")
768 out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
769 out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
770 java_hu_subclasses = ""
772 out_java += ("\tpublic static class " + struct_name + " {\n")
773 out_java += ("\t\tprivate " + struct_name + "() {}\n")
774 for var in variant_list:
775 out_java += ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
776 java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
777 out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
778 out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
779 init_meth_params = ""
782 for idx, field_ty in enumerate(var.fields):
783 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
784 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
785 if field_ty.to_hu_conv is not None:
786 hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
787 hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
788 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
790 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
792 init_meth_params = init_meth_params + ", "
793 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
794 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
795 out_java += ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
796 out_java += (init_meth_body)
798 out_java += ("\t\t}\n")
799 out_java_enum += ("\t\t}\n")
800 java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
801 java_hu_subclasses = java_hu_subclasses + hu_conv_body
802 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
803 out_java += ("\t\tstatic native void init();\n")
804 out_java += ("\t}\n")
805 out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
806 out_java += ("\tstatic { " + struct_name + ".init(); }\n")
807 out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
809 out_c += (self.c_fn_ty_pfx + self.c_complex_enum_pass_ty(struct_name) + " " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " ptr) {\n")
810 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
811 out_c += ("\tswitch(obj->tag) {\n")
812 for var in variant_list:
813 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
815 for idx, field_map in enumerate(var.fields):
816 if field_map.ret_conv is not None:
817 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
818 out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
819 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
820 c_params.append(field_map.ret_conv_name)
822 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
823 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
825 out_c += ("\t\tdefault: abort();\n")
826 out_c += ("\t}\n}\n")
827 out_java_enum += ("}\n")
828 out_java_enum += (java_hu_subclasses)
829 return (out_java, out_java_enum, out_c)
831 def map_opaque_struct(self, struct_name):
835 if struct_name.startswith("LDKLocked"):
836 implementations += "implements AutoCloseable "
842 protected finalize() {
846 out_opaque_struct_human = f"""
847 {self.hu_struct_file_prefix}
849 export default class {struct_name.replace("LDK","")} extends CommonBase {implementations}{{
850 constructor(_dummy: object, ptr: number) {{
855 if (this.ptr != 0) {{
856 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
860 return out_opaque_struct_human
862 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):
865 out_java_struct = None
867 out_java += ("\tpublic static native ")
868 out_c += (self.c_fn_ty_pfx)
869 out_c += (return_type_info.c_ty)
870 out_java += (return_type_info.java_ty)
871 if return_type_info.ret_conv is not None:
872 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
873 out_java += (" " + method_name + "(")
874 out_c += (" " + self.c_fn_name_pfx + method_name.replace('_', '_1') + "(" + self.c_fn_args_pfx)
876 method_argument_string = ""
877 native_call_argument_string = ""
878 for idx, arg_conv_info in enumerate(argument_types):
880 method_argument_string += (", ")
881 native_call_argument_string += ', '
882 if arg_conv_info.c_ty != "void":
884 if arg_conv_info.c_ty != "void":
885 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
886 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
887 native_argument = arg_conv_info.arg_name
889 converter = self.wasm_encoding_map[arg_conv_info.c_ty]
890 native_argument = f"{converter}({arg_conv_info.arg_name})"
891 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
892 native_call_argument_string += native_argument
894 needs_decoding = return_type_info.c_ty in self.wasm_decoding_map
895 return_value = 'nativeResponseValue'
897 converter = self.wasm_decoding_map[return_type_info.c_ty]
898 return_value = f"{converter}(nativeResponseValue)"
900 out_java = f"""\texport function {method_name}({method_argument_string}): {return_type_info.java_ty} {{
901 if(!isWasmInitialized){{
902 throw new Error("initializeWasm() must be awaited first!");
904 const nativeResponseValue = wasm.{method_name}({native_call_argument_string});
905 return {return_value};
911 if has_out_java_struct:
914 out_java_struct += ("\t// Skipped " + method_name + "\n")
915 has_out_java_struct = False
917 meth_n = method_name[len(struct_meth) + 1:]
920 "\tpublic static " + return_type_info.java_hu_ty + " constructor_" + meth_n + "(")
922 out_java_struct += ("\tpublic " + return_type_info.java_hu_ty + " " + meth_n + "(")
923 for idx, arg in enumerate(argument_types):
925 if not takes_self or idx > 1:
926 out_java_struct += (", ")
929 if arg.java_ty != "void":
930 if arg.arg_name in default_constructor_args:
931 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
933 out_java_struct += (", ")
935 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
937 out_java_struct += (arg.java_hu_ty + " " + arg.arg_name)
940 if out_java_struct is not None:
941 out_java_struct += (") {\n")
942 for info in argument_types:
943 if info.arg_conv is not None:
944 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
945 if return_type_info.ret_conv is not None:
946 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
947 elif return_type_info.c_ty != "void":
948 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
951 if c_call_string is None:
952 out_c += (method_name + "(")
954 out_c += (c_call_string)
955 for idx, info in enumerate(argument_types):
956 if info.arg_conv_name is not None:
959 elif c_call_string is not None:
961 out_c += (info.arg_conv_name)
963 if return_type_info.ret_conv is not None:
964 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
967 for info in argument_types:
968 if info.arg_conv_cleanup is not None:
969 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
970 if return_type_info.ret_conv is not None:
971 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
972 elif return_type_info.c_ty != "void":
973 out_c += ("\n\treturn ret_val;")
976 if has_out_java_struct:
977 out_java_struct += ("\t\t")
978 if return_type_info.java_ty != "void":
979 out_java_struct += (return_type_info.java_ty + " ret = ")
980 out_java_struct += ("bindings." + method_name + "(")
981 for idx, info in enumerate(argument_types):
983 out_java_struct += (", ")
984 if idx == 0 and takes_self:
985 out_java_struct += ("this.ptr")
986 elif info.arg_name in default_constructor_args:
987 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
988 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
990 out_java_struct += (", ")
991 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
992 if explode_arg.from_hu_conv is not None:
994 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
996 out_java_struct += (expl_arg_name)
997 out_java_struct += (")")
998 elif info.from_hu_conv is not None:
999 out_java_struct += (info.from_hu_conv[0])
1001 out_java_struct += (info.arg_name)
1002 out_java_struct += (");\n")
1003 if return_type_info.to_hu_conv is not None:
1005 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1006 return_type_info.to_hu_conv_name) + "\n")
1008 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1010 for idx, info in enumerate(argument_types):
1011 if idx == 0 and takes_self:
1013 elif info.arg_name in default_constructor_args:
1014 for explode_arg in default_constructor_args[info.arg_name]:
1015 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1016 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1017 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1018 expl_arg_name).replace(
1019 "this", return_type_info.to_hu_conv_name) + ";\n")
1020 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1021 if not takes_self and return_type_info.to_hu_conv_name is not None:
1022 out_java_struct += (
1023 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name) + ";\n")
1025 out_java_struct += ("\t\t" + info.from_hu_conv[1] + ";\n")
1027 if return_type_info.to_hu_conv_name is not None:
1028 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1029 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1030 out_java_struct += ("\t\treturn ret;\n")
1031 out_java_struct += ("\t}\n\n")
1033 return (out_java, out_c, out_java_struct)