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 uint32_t int64_tArray;
222 typedef uint32_t int8_tArray;
223 typedef uint32_t uint32_tArray;
224 typedef uint32_t ptrArray;
225 typedef uint32_t jstring;
227 static inline uint32_t init_arr(size_t arr_len, size_t elem_size, const char *type_desc) {
228 uint32_t *elems = (uint32_t*)MALLOC(arr_len * elem_size + 4, type_desc);
230 return (uint32_t)elems;
233 jstring str_ref_to_ts(const char* chars, size_t len) {
234 char* err_buf = MALLOC(len + 4, "str conv buf");
235 *((uint32_t*)err_buf) = len;
236 memcpy(err_buf + 4, chars, len);
237 return (uint32_t) err_buf;
240 typedef bool jboolean;
242 uint32_t __attribute__((visibility("default"))) TS_malloc(uint32_t size) {
243 return (uint32_t)MALLOC(size, "JS-Called malloc");
245 void __attribute__((visibility("default"))) TS_free(uint32_t ptr) {
250 self.hu_struct_file_prefix = f"""
251 import CommonBase from './CommonBase';
252 import * as bindings from '../bindings' // TODO: figure out location
255 self.c_fn_ty_pfx = ""
256 self.file_ext = ".ts"
257 self.ptr_c_ty = "uint32_t"
258 self.ptr_native_ty = "number"
259 self.result_c_ty = "uint32_t"
260 self.ptr_arr = "ptrArray"
261 self.get_native_arr_len_call = ("*((uint32_t*)", ")")
263 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
265 def create_native_arr_call(self, arr_len, ty_info):
266 if ty_info.c_ty == "int8_tArray":
267 return "init_arr(" + arr_len + ", sizeof(uint8_t), \"Native int8_tArray Bytes\")"
268 elif ty_info.c_ty == "int64_tArray":
269 return "init_arr(" + arr_len + ", sizeof(uint64_t), \"Native int64_tArray Bytes\")"
270 elif ty_info.c_ty == "uint32_tArray":
271 return "init_arr(" + arr_len + ", sizeof(uint32_t), \"Native uint32_tArray Bytes\")"
272 elif ty_info.c_ty == "ptrArray":
273 assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
274 return "init_arr(" + arr_len + ", sizeof(uint32_t), \"Native ptrArray Bytes\")"
276 print("Need to create arr!", ty_info.c_ty)
278 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
279 if ty_info.c_ty == "int8_tArray":
280 return ("memcpy((uint8_t*)(" + arr_name + " + 4), ", ", " + arr_len + ")")
283 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
284 if ty_info.c_ty == "int8_tArray":
286 return "memcpy(" + dest_name + ", (uint8_t*)(" + arr_name + " + 4), " + arr_len + ")"
288 return "(int8_t*)(" + arr_name + " + 4)"
290 return "(" + ty_info.subty.c_ty + "*)(" + arr_name + " + 4)"
291 def get_native_arr_elem(self, arr_name, idxc, ty_info):
292 assert False # Only called if above is None
293 def get_native_arr_ptr_call(self, ty_info):
294 if ty_info.subty is not None:
295 return "(" + ty_info.subty.c_ty + "*)(", " + 4)"
296 return "(" + ty_info.c_ty + "*)(", " + 4)"
297 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
299 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
300 if ty_info.c_ty == "int8_tArray":
305 def str_ref_to_c_call(self, var_name, str_len):
306 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
308 def c_fn_name_define_pfx(self, fn_name, have_args):
309 return " __attribute__((visibility(\"default\"))) TS_" + fn_name + "("
311 def wasm_import_header(self, target):
312 if target == Target.NODEJS:
314 import * as fs from 'fs';
315 const source = fs.readFileSync('./ldk.wasm');
317 const memory = new WebAssembly.Memory({initial: 256});
318 const wasmModule = new WebAssembly.Module(source);
320 const imports: any = {};
323 imports.env.memoryBase = 0;
324 imports.env.memory = memory;
325 imports.env.tableBase = 0;
326 imports.env.table = new WebAssembly.Table({initial: 4, element: 'anyfunc'});
328 imports.env["abort"] = function () {
329 console.error("ABORT");
333 let isWasmInitialized: boolean = false;
338 const nextMultipleOfFour = (value: number) => {
339 return Math.ceil(value / 4) * 4;
342 const encodeUint8Array = (inputArray) => {
343 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
344 const arrayLengthView = new Uint32Array(memory.buffer, cArrayPointer, 1);
345 arrayLengthView[0] = inputArray.length;
346 const arrayMemoryView = new Uint8Array(memory.buffer, cArrayPointer + 4, inputArray.length);
347 arrayMemoryView.set(inputArray);
348 return cArrayPointer;
351 const encodeUint32Array = (inputArray) => {
352 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
353 const arrayMemoryView = new Uint32Array(memory.buffer, cArrayPointer, inputArray.length);
354 arrayMemoryView.set(inputArray, 1);
355 arrayMemoryView[0] = inputArray.length;
356 return cArrayPointer;
359 const getArrayLength = (arrayPointer) => {
360 const arraySizeViewer = new Uint32Array(
361 memory.buffer, // value
362 arrayPointer, // offset
365 return arraySizeViewer[0];
367 const decodeUint8Array = (arrayPointer, free = true) => {
368 const arraySize = getArrayLength(arrayPointer);
369 const actualArrayViewer = new Uint8Array(
370 memory.buffer, // value
371 arrayPointer + 4, // offset (ignoring length bytes)
372 arraySize // uint8 count
374 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
375 // will free the underlying memory when it becomes unreachable instead of copying here.
376 const actualArray = actualArrayViewer.slice(0, arraySize);
378 wasm.TS_free(arrayPointer);
382 const decodeUint32Array = (arrayPointer, free = true) => {
383 const arraySize = getArrayLength(arrayPointer);
384 const actualArrayViewer = new Uint32Array(
385 memory.buffer, // value
386 arrayPointer + 4, // offset (ignoring length bytes)
387 arraySize // uint32 count
389 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
390 // will free the underlying memory when it becomes unreachable instead of copying here.
391 const actualArray = actualArrayViewer.slice(0, arraySize);
393 wasm.TS_free(arrayPointer);
398 const encodeString = (string) => {
399 // make malloc count divisible by 4
400 const memoryNeed = nextMultipleOfFour(string.length + 1);
401 const stringPointer = wasm.TS_malloc(memoryNeed);
402 const stringMemoryView = new Uint8Array(
403 memory.buffer, // value
404 stringPointer, // offset
405 string.length + 1 // length
407 for (let i = 0; i < string.length; i++) {
408 stringMemoryView[i] = string.charCodeAt(i);
410 stringMemoryView[string.length] = 0;
411 return stringPointer;
414 const decodeString = (stringPointer, free = true) => {
415 const memoryView = new Uint8Array(memory.buffer, stringPointer);
419 while (memoryView[cursor] !== 0) {
420 result += String.fromCharCode(memoryView[cursor]);
425 wasm.wasm_free(stringPointer);
436 def native_c_unitary_enum_map(self, struct_name, variants):
437 out_c = "static inline " + struct_name + " " + struct_name + "_from_js(int32_t ord) {\n"
438 out_c = out_c + "\tswitch (ord) {\n"
441 out_typescript_enum_fields = ""
444 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
446 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
447 out_c = out_c + "\t}\n"
448 out_c = out_c + "\tabort();\n"
449 out_c = out_c + "}\n"
451 out_c = out_c + "static inline int32_t " + struct_name + "_to_js(" + struct_name + " val) {\n"
452 out_c = out_c + "\tswitch (val) {\n"
455 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
457 out_c = out_c + "\t\tdefault: abort();\n"
458 out_c = out_c + "\t}\n"
459 out_c = out_c + "}\n"
461 out_typescript_enum = f"""
462 export enum {struct_name} {{
463 {out_typescript_enum_fields}
467 return (out_c, out_typescript_enum, "")
469 def c_unitary_enum_to_native_call(self, ty_info):
470 return (ty_info.rust_obj + "_to_js(", ")")
471 def native_unitary_enum_to_c_call(self, ty_info):
472 return (ty_info.rust_obj + "_from_js(", ")")
474 def c_complex_enum_pass_ty(self, struct_name):
477 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
478 ret = "0 /* " + struct_name + " - " + variant + " */"
479 for param in c_params:
480 ret = ret + "; (void) " + param
483 def native_c_map_trait(self, struct_name, field_var_conversions, field_function_lines):
484 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
486 constructor_arguments = ""
487 super_instantiator = ""
488 pointer_to_adder = ""
489 impl_constructor_arguments = ""
490 for var in field_var_conversions:
491 if isinstance(var, ConvInfo):
492 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
493 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
494 if var.from_hu_conv is not None:
495 super_instantiator += ", " + var.from_hu_conv[0]
496 if var.from_hu_conv[1] != "":
497 pointer_to_adder += var.from_hu_conv[1] + ";\n"
499 super_instantiator += ", " + first_to_lower(var.arg_name)
501 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
502 super_instantiator += ", " + first_to_lower(var[1])
503 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
504 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
506 # BUILD INTERFACE METHODS
507 out_java_interface = ""
508 out_interface_implementation_overrides = ""
510 for fn_line in field_function_lines:
511 java_method_descriptor = ""
512 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
513 out_java_interface += fn_line.fn_name + "("
514 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
516 for idx, arg_conv_info in enumerate(fn_line.args_ty):
518 out_java_interface += ", "
519 out_interface_implementation_overrides += ", "
520 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
521 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
522 java_method_descriptor += arg_conv_info.java_fn_ty_arg
523 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
524 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
525 java_methods.append((fn_line.fn_name, java_method_descriptor))
527 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
529 interface_method_override_inset = "\t\t\t\t\t\t"
530 interface_implementation_inset = "\t\t\t\t\t\t\t"
531 for arg_info in fn_line.args_ty:
532 if arg_info.to_hu_conv is not None:
533 out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
535 if fn_line.ret_ty_info.java_ty != "void":
536 out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
538 out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
540 for idx, arg_info in enumerate(fn_line.args_ty):
542 out_interface_implementation_overrides += ", "
543 if arg_info.to_hu_conv_name is not None:
544 out_interface_implementation_overrides += arg_info.to_hu_conv_name
546 out_interface_implementation_overrides += arg_info.arg_name
548 out_interface_implementation_overrides += ");\n"
549 if fn_line.ret_ty_info.java_ty != "void":
550 if fn_line.ret_ty_info.from_hu_conv is not None:
551 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"
552 if fn_line.ret_ty_info.from_hu_conv[1] != "":
553 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"
554 #if fn_line.ret_ty_info.rust_obj in result_types:
555 # XXX: We need to handle this in conversion logic so that its cross-language!
556 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
557 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
558 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
560 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
561 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
563 trait_constructor_arguments = ""
564 for var in field_var_conversions:
565 if isinstance(var, ConvInfo):
566 trait_constructor_arguments += ", " + var.arg_name
568 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl).bindings_instance"
570 out_typescript_human = f"""
571 {self.hu_struct_file_prefix}
573 export class {struct_name.replace("LDK","")} extends CommonBase {{
575 bindings_instance?: bindings.{struct_name};
577 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
578 if (Number.isFinite(ptr)) {{
580 this.bindings_instance = null;
582 // TODO: private constructor instantiation
583 super(bindings.{struct_name}_new(arg{super_instantiator}));
584 this.ptrs_to.push(arg);
589 protected finalize() {{
590 if (this.ptr != 0) {{
591 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
596 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
597 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
598 let structImplementation = <bindings.{struct_name}>{{
599 // todo: in-line interface filling
600 {out_interface_implementation_overrides}
602 impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
606 export interface {struct_name.replace("LDK", "")}Interface {{
610 class {struct_name}Holder {{
611 held: {struct_name.replace("LDK", "")};
615 out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
617 for fn_line in field_function_lines:
618 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
619 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
621 for idx, arg_conv_info in enumerate(fn_line.args_ty):
623 out_typescript_bindings = out_typescript_bindings + ", "
624 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
626 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
628 out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
630 out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
631 for var in field_var_conversions:
632 if isinstance(var, ConvInfo):
633 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
635 out_typescript_bindings += f", {var[1]}: {var[0]}"
637 out_typescript_bindings += f"""): number {{
638 throw new Error('unimplemented'); // TODO: bind to WASM
642 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
644 # Now that we've written out our java code (and created java_meths), generate C
645 out_c = "typedef struct " + struct_name + "_JCalls {\n"
646 out_c = out_c + "\tatomic_size_t refcnt;\n"
647 for var in field_var_conversions:
648 if isinstance(var, ConvInfo):
649 # We're a regular ol' field
653 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
654 for fn in field_function_lines:
655 if fn.fn_name != "free" and fn.fn_name != "clone":
656 out_c = out_c + "\tuint32_t " + fn.fn_name + "_meth;\n"
657 out_c = out_c + "} " + struct_name + "_JCalls;\n"
659 for fn_line in field_function_lines:
660 if fn_line.fn_name == "free":
661 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
662 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
663 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
664 for fn in field_function_lines:
665 if fn.fn_name != "free" and fn.fn_name != "clone":
666 out_c = out_c + "\t\tjs_free(j_calls->" + fn.fn_name + "_meth);\n"
667 out_c = out_c + "\t\tFREE(j_calls);\n"
668 out_c = out_c + "\t}\n}\n"
670 for idx, fn_line in enumerate(field_function_lines):
671 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
672 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
673 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_jcall("
674 if fn_line.self_is_const:
675 out_c = out_c + "const void* this_arg"
677 out_c = out_c + "void* this_arg"
679 for idx, arg in enumerate(fn_line.args_ty):
680 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
682 out_c = out_c + ") {\n"
683 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
685 for arg_info in fn_line.args_ty:
686 if arg_info.ret_conv is not None:
687 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
688 out_c = out_c + arg_info.arg_name
689 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
691 if fn_line.ret_ty_info.c_ty.endswith("Array"):
692 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"
693 elif fn_line.ret_ty_info.java_ty == "void":
694 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
695 elif not fn_line.ret_ty_info.passed_as_ptr:
696 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
698 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"
700 for idx, arg_info in enumerate(fn_line.args_ty):
701 if arg_info.ret_conv is not None:
702 out_c = out_c + ", " + arg_info.ret_conv_name
704 out_c = out_c + ", " + arg_info.arg_name
705 out_c = out_c + ");\n"
706 if fn_line.ret_ty_info.arg_conv is not None:
707 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"
709 out_c = out_c + "}\n"
711 # Write out a clone function whether we need one or not, as we use them in moving to rust
712 out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
713 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
714 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
715 for var in field_var_conversions:
716 if not isinstance(var, ConvInfo):
717 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
718 out_c = out_c + "\treturn (void*) this_arg;\n"
719 out_c = out_c + "}\n"
721 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (/*TODO: JS Object Reference */void* o"
722 for var in field_var_conversions:
723 if isinstance(var, ConvInfo):
724 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
726 out_c = out_c + ", /*TODO: JS Object Reference */void* " + var[1]
727 out_c = out_c + ") {\n"
729 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
730 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
731 out_c = out_c + "\t//TODO: Assign calls->o from o\n"
733 for (fn_name, java_meth_descr) in java_meths:
734 if fn_name != "free" and fn_name != "clone":
735 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
736 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
738 for var in field_var_conversions:
739 if isinstance(var, ConvInfo) and var.arg_conv is not None:
740 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
741 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
742 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
743 for fn_line in field_function_lines:
744 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
745 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_jcall,\n"
746 elif fn_line.fn_name == "free":
747 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
749 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
750 for var in field_var_conversions:
751 if isinstance(var, ConvInfo):
752 if var.arg_conv_name is not None:
753 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
754 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
756 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
757 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
759 out_c = out_c + "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1] + "),\n"
760 out_c = out_c + "\t};\n"
761 for var in field_var_conversions:
762 if not isinstance(var, ConvInfo):
763 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
764 out_c = out_c + "\treturn ret;\n"
765 out_c = out_c + "}\n"
767 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"
768 for var in field_var_conversions:
769 if isinstance(var, ConvInfo):
770 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
772 out_c = out_c + ", /*TODO: JS Object Reference */ void* " + var[1]
773 out_c = out_c + ") {\n"
774 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
775 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
776 for var in field_var_conversions:
777 if isinstance(var, ConvInfo):
778 out_c = out_c + ", " + var.arg_name
780 out_c = out_c + ", " + var[1]
781 out_c = out_c + ");\n"
782 out_c = out_c + "\treturn (long)res_ptr;\n"
783 out_c = out_c + "}\n"
785 return (out_typescript_bindings, out_typescript_human, out_c)
787 def trait_struct_inc_refcnt(self, ty_info):
790 def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
791 java_hu_type = struct_name.replace("LDK", "")
797 out_java_enum += (self.hu_struct_file_prefix)
798 out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
799 out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
800 out_java_enum += ("\tprotected finalize() {\n")
801 out_java_enum += ("\t\tsuper.finalize();\n")
802 out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
803 out_java_enum += ("\t}\n")
804 out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
805 out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
806 java_hu_subclasses = ""
808 out_java += ("\tpublic static class " + struct_name + " {\n")
809 out_java += ("\t\tprivate " + struct_name + "() {}\n")
810 for var in variant_list:
811 out_java += ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
812 java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
813 out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
814 out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
815 init_meth_params = ""
818 for idx, field_ty in enumerate(var.fields):
819 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
820 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
821 if field_ty.to_hu_conv is not None:
822 hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
823 hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
824 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
826 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
828 init_meth_params = init_meth_params + ", "
829 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
830 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
831 out_java += ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
832 out_java += (init_meth_body)
834 out_java += ("\t\t}\n")
835 out_java_enum += ("\t\t}\n")
836 java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
837 java_hu_subclasses = java_hu_subclasses + hu_conv_body
838 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
839 out_java += ("\t\tstatic native void init();\n")
840 out_java += ("\t}\n")
841 out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
842 out_java += ("\tstatic { " + struct_name + ".init(); }\n")
843 out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
845 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")
846 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
847 out_c += ("\tswitch(obj->tag) {\n")
848 for var in variant_list:
849 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
851 for idx, field_map in enumerate(var.fields):
852 if field_map.ret_conv is not None:
853 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
854 out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
855 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
856 c_params.append(field_map.ret_conv_name)
858 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
859 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
861 out_c += ("\t\tdefault: abort();\n")
862 out_c += ("\t}\n}\n")
863 out_java_enum += ("}\n")
864 out_java_enum += (java_hu_subclasses)
865 return (out_java, out_java_enum, out_c)
867 def map_opaque_struct(self, struct_name):
870 if struct_name.startswith("LDKLocked"):
871 implementations += "implements AutoCloseable "
877 protected finalize() {
881 out_opaque_struct_human = f"""
882 {self.hu_struct_file_prefix}
884 export default class {struct_name.replace("LDK","")} extends CommonBase {implementations}{{
885 constructor(_dummy: object, ptr: number) {{
890 if (this.ptr != 0) {{
891 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
895 return out_opaque_struct_human
897 def map_function(self, argument_types, c_call_string, method_name, return_type_info, struct_meth, default_constructor_args, takes_self, args_known, type_mapping_generator):
900 out_java_struct = None
902 out_java += ("\tpublic static native ")
903 out_c += (self.c_fn_ty_pfx)
904 out_c += (return_type_info.c_ty)
905 out_java += (return_type_info.java_ty)
906 if return_type_info.ret_conv is not None:
907 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
908 out_java += (" " + method_name + "(")
909 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
911 method_argument_string = ""
912 native_call_argument_string = ""
913 for idx, arg_conv_info in enumerate(argument_types):
915 method_argument_string += (", ")
916 native_call_argument_string += ', '
918 if arg_conv_info.c_ty != "void":
919 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
920 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
921 native_argument = arg_conv_info.arg_name
923 converter = self.wasm_encoding_map[arg_conv_info.c_ty]
924 native_argument = f"{converter}({arg_conv_info.arg_name})"
925 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
926 native_call_argument_string += native_argument
928 has_return_value = return_type_info.c_ty != 'void'
929 needs_decoding = return_type_info.c_ty in self.wasm_decoding_map
930 return_statement = 'return nativeResponseValue;'
931 if not has_return_value:
932 return_statement = '// debug statements here'
934 converter = self.wasm_decoding_map[return_type_info.c_ty]
935 return_statement = f"return {converter}(nativeResponseValue);"
937 out_java = f"""\texport function {method_name}({method_argument_string}): {return_type_info.java_ty} {{
938 if(!isWasmInitialized) {{
939 throw new Error("initializeWasm() must be awaited first!");
941 const nativeResponseValue = wasm.{method_name}({native_call_argument_string});
948 out_java_struct += ("\t// Skipped " + method_name + "\n")
950 meth_n = method_name[len(struct_meth) + 1:]
953 "\tpublic static " + return_type_info.java_hu_ty + " constructor_" + meth_n + "(")
955 out_java_struct += ("\tpublic " + return_type_info.java_hu_ty + " " + meth_n + "(")
956 for idx, arg in enumerate(argument_types):
958 if not takes_self or idx > 1:
959 out_java_struct += (", ")
962 if arg.java_ty != "void":
963 if arg.arg_name in default_constructor_args:
964 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
966 out_java_struct += (", ")
968 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
970 out_java_struct += (arg.java_hu_ty + " " + arg.arg_name)
973 if out_java_struct is not None:
974 out_java_struct += (") {\n")
975 for info in argument_types:
976 if info.arg_conv is not None:
977 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
978 if return_type_info.ret_conv is not None:
979 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
980 elif return_type_info.c_ty != "void":
981 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
984 if c_call_string is None:
985 out_c += (method_name + "(")
987 out_c += (c_call_string)
988 for idx, info in enumerate(argument_types):
989 if info.arg_conv_name is not None:
992 elif c_call_string is not None:
994 out_c += (info.arg_conv_name)
996 if return_type_info.ret_conv is not None:
997 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1000 for info in argument_types:
1001 if info.arg_conv_cleanup is not None:
1002 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1003 if return_type_info.ret_conv is not None:
1004 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1005 elif return_type_info.c_ty != "void":
1006 out_c += ("\n\treturn ret_val;")
1007 out_c += ("\n}\n\n")
1010 out_java_struct += ("\t\t")
1011 if return_type_info.java_ty != "void":
1012 out_java_struct += (return_type_info.java_ty + " ret = ")
1013 out_java_struct += ("bindings." + method_name + "(")
1014 for idx, info in enumerate(argument_types):
1016 out_java_struct += (", ")
1017 if idx == 0 and takes_self:
1018 out_java_struct += ("this.ptr")
1019 elif info.arg_name in default_constructor_args:
1020 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1021 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1022 if explode_idx != 0:
1023 out_java_struct += (", ")
1024 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1025 if explode_arg.from_hu_conv is not None:
1026 out_java_struct += (
1027 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1029 out_java_struct += (expl_arg_name)
1030 out_java_struct += (")")
1031 elif info.from_hu_conv is not None:
1032 out_java_struct += (info.from_hu_conv[0])
1034 out_java_struct += (info.arg_name)
1035 out_java_struct += (");\n")
1036 if return_type_info.to_hu_conv is not None:
1038 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1039 return_type_info.to_hu_conv_name) + "\n")
1041 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1043 for idx, info in enumerate(argument_types):
1044 if idx == 0 and takes_self:
1046 elif info.arg_name in default_constructor_args:
1047 for explode_arg in default_constructor_args[info.arg_name]:
1048 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1049 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1050 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1051 expl_arg_name).replace(
1052 "this", return_type_info.to_hu_conv_name) + ";\n")
1053 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1054 if not takes_self and return_type_info.to_hu_conv_name is not None:
1055 out_java_struct += (
1056 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name) + ";\n")
1058 out_java_struct += ("\t\t" + info.from_hu_conv[1] + ";\n")
1060 if return_type_info.to_hu_conv_name is not None:
1061 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1062 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1063 out_java_struct += ("\t\treturn ret;\n")
1064 out_java_struct += ("\t}\n\n")
1066 return (out_java, out_c, out_java_struct)