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_version_file = ""
76 self.bindings_footer = """
77 export async function initializeWasm(allowDoubleInitialization: boolean = false): Promise<void> {
78 if(isWasmInitialized && !allowDoubleInitialization) {
81 const wasmInstance = await WebAssembly.instantiate(wasmModule, imports)
82 wasm = wasmInstance.exports;
83 isWasmInitialized = true;
90 self.common_base = """
91 export default class CommonBase {
93 ptrs_to: object[] = []; // new LinkedList(); TODO: build linked list implementation
94 protected constructor(ptr: number) { this.ptr = ptr; }
95 public _test_only_get_ptr(): number { return this.ptr; }
96 protected finalize() {
97 // TODO: finalize myself
102 self.c_file_pfx = """#include "js-wasm.h"
103 #include <stdatomic.h>
104 #include <lightning.h>
106 // These should be provided...somehow...
107 void *memset(void *s, int c, size_t n);
108 void *memcpy(void *dest, const void *src, size_t n);
109 int memcmp(const void *s1, const void *s2, size_t n);
111 void __attribute__((noreturn)) abort(void);
112 static inline void assert(bool expression) {
113 if (!expression) { abort(); }
118 self.c_file_pfx = self.c_file_pfx + """
119 void *malloc(size_t size);
120 void free(void *ptr);
122 #define MALLOC(a, _) malloc(a)
123 #define FREE(p) if ((unsigned long)(p) > 1024) { free(p); }
124 #define DO_ASSERT(a) (void)(a)
128 self.c_file_pfx = self.c_file_pfx + """
129 // Always run a, then assert it is true:
130 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
131 // Assert a is true or do nothing
132 #define CHECK(a) DO_ASSERT(a)
134 // Running a leak check across all the allocations and frees of the JDK is a mess,
135 // so instead we implement our own naive leak checker here, relying on the -wrap
136 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
137 // and free'd in Rust or C across the generated bindings shared library.
140 typedef struct allocation {
141 struct allocation* next;
143 const char* struct_name;
145 static allocation* allocation_ll = NULL;
147 void* __real_malloc(size_t len);
148 void* __real_calloc(size_t nmemb, size_t len);
149 static void new_allocation(void* res, const char* struct_name) {
150 allocation* new_alloc = __real_malloc(sizeof(allocation));
151 new_alloc->ptr = res;
152 new_alloc->struct_name = struct_name;
153 new_alloc->next = allocation_ll;
154 allocation_ll = new_alloc;
156 static void* MALLOC(size_t len, const char* struct_name) {
157 void* res = __real_malloc(len);
158 new_allocation(res, struct_name);
161 void __real_free(void* ptr);
162 static void alloc_freed(void* ptr) {
163 allocation* p = NULL;
164 allocation* it = allocation_ll;
165 while (it->ptr != ptr) {
166 p = it; it = it->next;
168 //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
169 return; // addrsan should catch malloc-unknown and print more info than we have
172 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
173 DO_ASSERT(it->ptr == ptr);
176 static void FREE(void* ptr) {
177 if ((unsigned long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
182 void* __wrap_malloc(size_t len) {
183 void* res = __real_malloc(len);
184 new_allocation(res, "malloc call");
187 void* __wrap_calloc(size_t nmemb, size_t len) {
188 void* res = __real_calloc(nmemb, len);
189 new_allocation(res, "calloc call");
192 void __wrap_free(void* ptr) {
193 if (ptr == NULL) return;
198 void* __real_realloc(void* ptr, size_t newlen);
199 void* __wrap_realloc(void* ptr, size_t len) {
200 if (ptr != NULL) alloc_freed(ptr);
201 void* res = __real_realloc(ptr, len);
202 new_allocation(res, "realloc call");
205 void __wrap_reallocarray(void* ptr, size_t new_sz) {
206 // Rust doesn't seem to use reallocarray currently
210 void __attribute__((destructor)) check_leaks() {
211 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
212 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
214 DO_ASSERT(allocation_ll == NULL);
217 self.c_file_pfx = self.c_file_pfx + """
218 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
219 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
220 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
221 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
223 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
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 static inline 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;
243 static inline LDKStr str_ref_to_owned_c(jstring str) {
244 uint32_t *str_len = (uint32_t*)str;
245 char* newchars = MALLOC(*str_len + 1, "String chars");
246 memcpy(newchars, (const char*)(str + 4), *str_len);
247 newchars[*str_len] = 0;
251 .chars_is_owned = true
256 typedef bool jboolean;
258 uint32_t __attribute__((visibility("default"))) TS_malloc(uint32_t size) {
259 return (uint32_t)MALLOC(size, "JS-Called malloc");
261 void __attribute__((visibility("default"))) TS_free(uint32_t ptr) {
266 self.c_version_file = ""
268 self.hu_struct_file_prefix = f"""
269 import CommonBase from './CommonBase';
270 import * as bindings from '../bindings' // TODO: figure out location
273 self.c_fn_ty_pfx = ""
274 self.file_ext = ".ts"
275 self.ptr_c_ty = "uint32_t"
276 self.ptr_native_ty = "number"
277 self.result_c_ty = "uint32_t"
278 self.ptr_arr = "ptrArray"
279 self.is_arr_some_check = ("", " != 0")
280 self.get_native_arr_len_call = ("*((uint32_t*)", ")")
282 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
284 def create_native_arr_call(self, arr_len, ty_info):
285 if ty_info.c_ty == "int8_tArray":
286 return "init_arr(" + arr_len + ", sizeof(uint8_t), \"Native int8_tArray Bytes\")"
287 elif ty_info.c_ty == "int64_tArray":
288 return "init_arr(" + arr_len + ", sizeof(uint64_t), \"Native int64_tArray Bytes\")"
289 elif ty_info.c_ty == "uint32_tArray":
290 return "init_arr(" + arr_len + ", sizeof(uint32_t), \"Native uint32_tArray Bytes\")"
291 elif ty_info.c_ty == "ptrArray":
292 assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
293 return "init_arr(" + arr_len + ", sizeof(uint32_t), \"Native ptrArray Bytes\")"
295 print("Need to create arr!", ty_info.c_ty)
297 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
298 if ty_info.c_ty == "int8_tArray":
299 return ("memcpy((uint8_t*)(" + arr_name + " + 4), ", ", " + arr_len + ")")
302 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
303 if ty_info.c_ty == "int8_tArray":
305 return "memcpy(" + dest_name + ", (uint8_t*)(" + arr_name + " + 4), " + arr_len + ")"
307 return "(int8_t*)(" + arr_name + " + 4)"
309 return "(" + ty_info.subty.c_ty + "*)(" + arr_name + " + 4)"
310 def get_native_arr_elem(self, arr_name, idxc, ty_info):
311 assert False # Only called if above is None
312 def get_native_arr_ptr_call(self, ty_info):
313 if ty_info.subty is not None:
314 return "(" + ty_info.subty.c_ty + "*)(", " + 4)"
315 return "(" + ty_info.c_ty + "*)(", " + 4)"
316 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
318 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
319 if ty_info.c_ty == "int8_tArray":
324 def str_ref_to_native_call(self, var_name, str_len):
325 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
326 def str_ref_to_c_call(self, var_name):
327 return "str_ref_to_owned_c(" + var_name + ")"
329 def c_fn_name_define_pfx(self, fn_name, have_args):
330 return " __attribute__((visibility(\"default\"))) TS_" + fn_name + "("
332 def wasm_import_header(self, target):
333 if target == Target.NODEJS:
335 import * as fs from 'fs';
336 const source = fs.readFileSync('./ldk.wasm');
338 const memory = new WebAssembly.Memory({initial: 256});
339 const wasmModule = new WebAssembly.Module(source);
341 const imports: any = {};
344 imports.env.memoryBase = 0;
345 imports.env.memory = memory;
346 imports.env.tableBase = 0;
347 imports.env.table = new WebAssembly.Table({initial: 4, element: 'anyfunc'});
349 imports.env["abort"] = function () {
350 console.error("ABORT");
354 let isWasmInitialized: boolean = false;
359 const nextMultipleOfFour = (value: number) => {
360 return Math.ceil(value / 4) * 4;
363 const encodeUint8Array = (inputArray) => {
364 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
365 const arrayLengthView = new Uint32Array(memory.buffer, cArrayPointer, 1);
366 arrayLengthView[0] = inputArray.length;
367 const arrayMemoryView = new Uint8Array(memory.buffer, cArrayPointer + 4, inputArray.length);
368 arrayMemoryView.set(inputArray);
369 return cArrayPointer;
372 const encodeUint32Array = (inputArray) => {
373 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
374 const arrayMemoryView = new Uint32Array(memory.buffer, cArrayPointer, inputArray.length);
375 arrayMemoryView.set(inputArray, 1);
376 arrayMemoryView[0] = inputArray.length;
377 return cArrayPointer;
380 const getArrayLength = (arrayPointer) => {
381 const arraySizeViewer = new Uint32Array(
382 memory.buffer, // value
383 arrayPointer, // offset
386 return arraySizeViewer[0];
388 const decodeUint8Array = (arrayPointer, free = true) => {
389 const arraySize = getArrayLength(arrayPointer);
390 const actualArrayViewer = new Uint8Array(
391 memory.buffer, // value
392 arrayPointer + 4, // offset (ignoring length bytes)
393 arraySize // uint8 count
395 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
396 // will free the underlying memory when it becomes unreachable instead of copying here.
397 const actualArray = actualArrayViewer.slice(0, arraySize);
399 wasm.TS_free(arrayPointer);
403 const decodeUint32Array = (arrayPointer, free = true) => {
404 const arraySize = getArrayLength(arrayPointer);
405 const actualArrayViewer = new Uint32Array(
406 memory.buffer, // value
407 arrayPointer + 4, // offset (ignoring length bytes)
408 arraySize // uint32 count
410 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
411 // will free the underlying memory when it becomes unreachable instead of copying here.
412 const actualArray = actualArrayViewer.slice(0, arraySize);
414 wasm.TS_free(arrayPointer);
419 const encodeString = (string) => {
420 // make malloc count divisible by 4
421 const memoryNeed = nextMultipleOfFour(string.length + 1);
422 const stringPointer = wasm.TS_malloc(memoryNeed);
423 const stringMemoryView = new Uint8Array(
424 memory.buffer, // value
425 stringPointer, // offset
426 string.length + 1 // length
428 for (let i = 0; i < string.length; i++) {
429 stringMemoryView[i] = string.charCodeAt(i);
431 stringMemoryView[string.length] = 0;
432 return stringPointer;
435 const decodeString = (stringPointer, free = true) => {
436 const memoryView = new Uint8Array(memory.buffer, stringPointer);
440 while (memoryView[cursor] !== 0) {
441 result += String.fromCharCode(memoryView[cursor]);
446 wasm.wasm_free(stringPointer);
457 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
458 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
459 out_c = out_c + "\tswitch (ord) {\n"
462 out_typescript_enum_fields = ""
465 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
467 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
468 out_c = out_c + "\t}\n"
469 out_c = out_c + "\tabort();\n"
470 out_c = out_c + "}\n"
472 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
473 out_c = out_c + "\tswitch (val) {\n"
476 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
478 out_c = out_c + "\t\tdefault: abort();\n"
479 out_c = out_c + "\t}\n"
480 out_c = out_c + "}\n"
482 out_typescript_enum = f"""
483 export enum {struct_name} {{
484 {out_typescript_enum_fields}
488 return (out_c, out_typescript_enum, "")
490 def c_unitary_enum_to_native_call(self, ty_info):
491 return (ty_info.rust_obj + "_to_js(", ")")
492 def native_unitary_enum_to_c_call(self, ty_info):
493 return (ty_info.rust_obj + "_from_js(", ")")
495 def c_complex_enum_pass_ty(self, struct_name):
498 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
499 ret = "0 /* " + struct_name + " - " + variant + " */"
500 for param in c_params:
501 ret = ret + "; (void) " + param
504 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
505 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
507 constructor_arguments = ""
508 super_instantiator = ""
509 pointer_to_adder = ""
510 impl_constructor_arguments = ""
511 for var in flattened_field_var_conversions:
512 if isinstance(var, ConvInfo):
513 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
514 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
515 if var.from_hu_conv is not None:
516 super_instantiator += ", " + var.from_hu_conv[0]
517 if var.from_hu_conv[1] != "":
518 pointer_to_adder += var.from_hu_conv[1] + ";\n"
520 super_instantiator += ", " + first_to_lower(var.arg_name)
522 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
523 super_instantiator += ", " + first_to_lower(var[1])
524 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
525 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
527 # BUILD INTERFACE METHODS
528 out_java_interface = ""
529 out_interface_implementation_overrides = ""
531 for fn_line in field_function_lines:
532 java_method_descriptor = ""
533 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
534 out_java_interface += fn_line.fn_name + "("
535 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
537 for idx, arg_conv_info in enumerate(fn_line.args_ty):
539 out_java_interface += ", "
540 out_interface_implementation_overrides += ", "
541 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
542 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
543 java_method_descriptor += arg_conv_info.java_fn_ty_arg
544 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
545 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
546 java_methods.append((fn_line.fn_name, java_method_descriptor))
548 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
550 interface_method_override_inset = "\t\t\t\t\t\t"
551 interface_implementation_inset = "\t\t\t\t\t\t\t"
552 for arg_info in fn_line.args_ty:
553 if arg_info.to_hu_conv is not None:
554 out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
556 if fn_line.ret_ty_info.java_ty != "void":
557 out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
559 out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
561 for idx, arg_info in enumerate(fn_line.args_ty):
563 out_interface_implementation_overrides += ", "
564 if arg_info.to_hu_conv_name is not None:
565 out_interface_implementation_overrides += arg_info.to_hu_conv_name
567 out_interface_implementation_overrides += arg_info.arg_name
569 out_interface_implementation_overrides += ");\n"
570 if fn_line.ret_ty_info.java_ty != "void":
571 if fn_line.ret_ty_info.from_hu_conv is not None:
572 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"
573 if fn_line.ret_ty_info.from_hu_conv[1] != "":
574 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"
575 #if fn_line.ret_ty_info.rust_obj in result_types:
576 # XXX: We need to handle this in conversion logic so that its cross-language!
577 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
578 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
579 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
581 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
582 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
584 trait_constructor_arguments = ""
585 for var in field_var_conversions:
586 if isinstance(var, ConvInfo):
587 trait_constructor_arguments += ", " + var.arg_name
589 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl"
590 for suparg in var[2]:
591 if isinstance(suparg, ConvInfo):
592 trait_constructor_arguments += ", " + suparg.arg_name
594 trait_constructor_arguments += ", " + suparg[1]
595 trait_constructor_arguments += ").bindings_instance"
596 for suparg in var[2]:
597 if isinstance(suparg, ConvInfo):
598 trait_constructor_arguments += ", " + suparg.arg_name
600 trait_constructor_arguments += ", " + suparg[1]
602 out_typescript_human = f"""
603 {self.hu_struct_file_prefix}
605 export class {struct_name.replace("LDK","")} extends CommonBase {{
607 bindings_instance?: bindings.{struct_name};
609 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
610 if (Number.isFinite(ptr)) {{
612 this.bindings_instance = null;
614 // TODO: private constructor instantiation
615 super(bindings.{struct_name}_new(arg{super_instantiator}));
616 this.ptrs_to.push(arg);
621 protected finalize() {{
622 if (this.ptr != 0) {{
623 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
628 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
629 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
630 let structImplementation = <bindings.{struct_name}>{{
631 // todo: in-line interface filling
632 {out_interface_implementation_overrides}
634 impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
638 export interface {struct_name.replace("LDK", "")}Interface {{
642 class {struct_name}Holder {{
643 held: {struct_name.replace("LDK", "")};
647 out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
649 for fn_line in field_function_lines:
650 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
651 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
653 for idx, arg_conv_info in enumerate(fn_line.args_ty):
655 out_typescript_bindings = out_typescript_bindings + ", "
656 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
658 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
660 out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
662 out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
663 for var in flattened_field_var_conversions:
664 if isinstance(var, ConvInfo):
665 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
667 out_typescript_bindings += f", {var[1]}: {var[0]}"
669 out_typescript_bindings += f"""): number {{
670 throw new Error('unimplemented'); // TODO: bind to WASM
674 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
676 # Now that we've written out our java code (and created java_meths), generate C
677 out_c = "typedef struct " + struct_name + "_JCalls {\n"
678 out_c = out_c + "\tatomic_size_t refcnt;\n"
679 for var in flattened_field_var_conversions:
680 if isinstance(var, ConvInfo):
681 # We're a regular ol' field
685 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
686 for fn in field_function_lines:
687 if fn.fn_name != "free" and fn.fn_name != "cloned":
688 out_c = out_c + "\tuint32_t " + fn.fn_name + "_meth;\n"
689 out_c = out_c + "} " + struct_name + "_JCalls;\n"
691 for fn_line in field_function_lines:
692 if fn_line.fn_name == "free":
693 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
694 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
695 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
696 for fn in field_function_lines:
697 if fn.fn_name != "free" and fn.fn_name != "cloned":
698 out_c = out_c + "\t\tjs_free(j_calls->" + fn.fn_name + "_meth);\n"
699 out_c = out_c + "\t\tFREE(j_calls);\n"
700 out_c = out_c + "\t}\n}\n"
702 for idx, fn_line in enumerate(field_function_lines):
703 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
704 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
705 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
706 if fn_line.self_is_const:
707 out_c = out_c + "const void* this_arg"
709 out_c = out_c + "void* this_arg"
711 for idx, arg in enumerate(fn_line.args_ty):
712 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
714 out_c = out_c + ") {\n"
715 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
717 for arg_info in fn_line.args_ty:
718 if arg_info.ret_conv is not None:
719 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
720 out_c = out_c + arg_info.arg_name
721 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
723 if fn_line.ret_ty_info.c_ty.endswith("Array"):
724 out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " ret = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
725 elif fn_line.ret_ty_info.java_ty == "void":
726 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
727 elif fn_line.ret_ty_info.java_ty == "String":
728 out_c = out_c + "\tuint32_t ret = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
729 elif not fn_line.ret_ty_info.passed_as_ptr:
730 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
732 out_c = out_c + "\tuint32_t ret = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
734 for idx, arg_info in enumerate(fn_line.args_ty):
735 if arg_info.ret_conv is not None:
736 out_c = out_c + ", " + arg_info.ret_conv_name
738 out_c = out_c + ", " + arg_info.arg_name
739 out_c = out_c + ");\n"
740 if fn_line.ret_ty_info.arg_conv is not None:
741 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"
743 out_c = out_c + "}\n"
745 # Write out a clone function whether we need one or not, as we use them in moving to rust
746 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
747 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
748 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
749 for var in field_var_conversions:
750 if not isinstance(var, ConvInfo):
751 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
752 out_c = out_c + "}\n"
754 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (/*TODO: JS Object Reference */void* o"
755 for var in flattened_field_var_conversions:
756 if isinstance(var, ConvInfo):
757 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
759 out_c = out_c + ", /*TODO: JS Object Reference */void* " + var[1]
760 out_c = out_c + ") {\n"
762 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
763 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
764 out_c = out_c + "\t//TODO: Assign calls->o from o\n"
766 for (fn_name, java_meth_descr) in java_meths:
767 if fn_name != "free" and fn_name != "cloned":
768 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
769 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
771 for var in flattened_field_var_conversions:
772 if isinstance(var, ConvInfo) and var.arg_conv is not None:
773 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
774 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
775 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
776 for fn_line in field_function_lines:
777 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
778 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
779 elif fn_line.fn_name == "free":
780 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
782 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
783 for var in field_var_conversions:
784 if isinstance(var, ConvInfo):
785 if var.arg_conv_name is not None:
786 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
787 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
789 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
790 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
792 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
793 for suparg in var[2]:
794 if isinstance(suparg, ConvInfo):
795 out_c += ", " + suparg.arg_name
797 out_c += ", " + suparg[1]
799 out_c = out_c + "\t};\n"
800 for var in flattened_field_var_conversions:
801 if not isinstance(var, ConvInfo):
802 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
803 out_c = out_c + "\treturn ret;\n"
804 out_c = out_c + "}\n"
806 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"
807 for var in flattened_field_var_conversions:
808 if isinstance(var, ConvInfo):
809 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
811 out_c = out_c + ", /*TODO: JS Object Reference */ void* " + var[1]
812 out_c = out_c + ") {\n"
813 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
814 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
815 for var in flattened_field_var_conversions:
816 if isinstance(var, ConvInfo):
817 out_c = out_c + ", " + var.arg_name
819 out_c = out_c + ", " + var[1]
820 out_c = out_c + ");\n"
821 out_c = out_c + "\treturn (long)res_ptr;\n"
822 out_c = out_c + "}\n"
824 return (out_typescript_bindings, out_typescript_human, out_c)
826 def trait_struct_inc_refcnt(self, ty_info):
829 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
830 java_hu_type = struct_name.replace("LDK", "")
836 out_java_enum += (self.hu_struct_file_prefix)
837 out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
838 out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
839 out_java_enum += ("\tprotected finalize() {\n")
840 out_java_enum += ("\t\tsuper.finalize();\n")
841 out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
842 out_java_enum += ("\t}\n")
843 out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
844 out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
845 java_hu_subclasses = ""
847 out_java += ("\tpublic static class " + struct_name + " {\n")
848 out_java += ("\t\tprivate " + struct_name + "() {}\n")
849 for var in variant_list:
850 out_java += ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
851 java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
852 out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
853 out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
854 init_meth_params = ""
857 for idx, (field_ty, field_docs) in enumerate(var.fields):
858 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
859 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
860 if field_ty.to_hu_conv is not None:
861 hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
862 hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
863 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
865 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
867 init_meth_params = init_meth_params + ", "
868 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
869 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
870 out_java += ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
871 out_java += (init_meth_body)
873 out_java += ("\t\t}\n")
874 out_java_enum += ("\t\t}\n")
875 java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
876 java_hu_subclasses = java_hu_subclasses + hu_conv_body
877 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
878 out_java += ("\t\tstatic native void init();\n")
879 out_java += ("\t}\n")
880 out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
881 out_java += ("\tstatic { " + struct_name + ".init(); }\n")
882 out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
884 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")
885 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n")
886 out_c += ("\tswitch(obj->tag) {\n")
887 for var in variant_list:
888 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
890 for idx, (field_map, _) in enumerate(var.fields):
891 if field_map.ret_conv is not None:
892 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
893 if var.tuple_variant:
894 out_c += "obj->" + camel_to_snake(var.var_name)
896 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
897 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
898 c_params.append(field_map.ret_conv_name)
900 if var.tuple_variant:
901 c_params.append("obj->" + camel_to_snake(var.var_name))
903 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
904 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
906 out_c += ("\t\tdefault: abort();\n")
907 out_c += ("\t}\n}\n")
908 out_java_enum += ("}\n")
909 out_java_enum += (java_hu_subclasses)
910 return (out_java, out_java_enum, out_c)
912 def map_opaque_struct(self, struct_name, struct_doc_comment):
915 if struct_name.startswith("LDKLocked"):
916 implementations += "implements AutoCloseable "
922 protected finalize() {
926 out_opaque_struct_human = f"""
927 {self.hu_struct_file_prefix}
929 export default class {struct_name.replace("LDK","")} extends CommonBase {implementations}{{
930 constructor(_dummy: object, ptr: number) {{
935 if (this.ptr != 0) {{
936 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
940 return out_opaque_struct_human
942 def map_tuple(self, struct_name):
943 return self.map_opaque_struct(struct_name, "A Tuple")
945 def map_function(self, argument_types, c_call_string, method_name, meth_n, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
948 out_java_struct = None
950 out_java += ("\tpublic static native ")
951 out_c += (self.c_fn_ty_pfx)
952 out_c += (return_type_info.c_ty)
953 out_java += (return_type_info.java_ty)
954 if return_type_info.ret_conv is not None:
955 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
956 out_java += (" " + method_name + "(")
957 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
959 method_argument_string = ""
960 native_call_argument_string = ""
961 for idx, arg_conv_info in enumerate(argument_types):
963 method_argument_string += (", ")
964 native_call_argument_string += ', '
966 if arg_conv_info.c_ty != "void":
967 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
968 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
969 native_argument = arg_conv_info.arg_name
971 converter = self.wasm_encoding_map[arg_conv_info.c_ty]
972 native_argument = f"{converter}({arg_conv_info.arg_name})"
973 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
974 native_call_argument_string += native_argument
976 has_return_value = return_type_info.c_ty != 'void'
977 needs_decoding = return_type_info.c_ty in self.wasm_decoding_map
978 return_statement = 'return nativeResponseValue;'
979 if not has_return_value:
980 return_statement = '// debug statements here'
982 converter = self.wasm_decoding_map[return_type_info.c_ty]
983 return_statement = f"return {converter}(nativeResponseValue);"
985 out_java = f"""\texport function {method_name}({method_argument_string}): {return_type_info.java_ty} {{
986 if(!isWasmInitialized) {{
987 throw new Error("initializeWasm() must be awaited first!");
989 const nativeResponseValue = wasm.{method_name}({native_call_argument_string});
996 out_java_struct += ("\t// Skipped " + method_name + "\n")
1000 "\tpublic static " + return_type_info.java_hu_ty + " constructor_" + meth_n + "(")
1002 out_java_struct += ("\tpublic " + return_type_info.java_hu_ty + " " + meth_n + "(")
1003 for idx, arg in enumerate(argument_types):
1005 if not takes_self or idx > 1:
1006 out_java_struct += (", ")
1009 if arg.java_ty != "void":
1010 if arg.arg_name in default_constructor_args:
1011 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1012 if explode_idx != 0:
1013 out_java_struct += (", ")
1014 out_java_struct += (
1015 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1017 out_java_struct += (arg.java_hu_ty + " " + arg.arg_name)
1020 if out_java_struct is not None:
1021 out_java_struct += (") {\n")
1022 for info in argument_types:
1023 if info.arg_conv is not None:
1024 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1025 if return_type_info.ret_conv is not None:
1026 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1027 elif return_type_info.c_ty != "void":
1028 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1031 if c_call_string is None:
1032 out_c += (method_name + "(")
1034 out_c += (c_call_string)
1035 for idx, info in enumerate(argument_types):
1036 if info.arg_conv_name is not None:
1039 elif c_call_string is not None:
1041 out_c += (info.arg_conv_name)
1043 if return_type_info.ret_conv is not None:
1044 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1047 for info in argument_types:
1048 if info.arg_conv_cleanup is not None:
1049 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1050 if return_type_info.ret_conv is not None:
1051 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1052 elif return_type_info.c_ty != "void":
1053 out_c += ("\n\treturn ret_val;")
1054 out_c += ("\n}\n\n")
1057 out_java_struct += ("\t\t")
1058 if return_type_info.java_ty != "void":
1059 out_java_struct += (return_type_info.java_ty + " ret = ")
1060 out_java_struct += ("bindings." + method_name + "(")
1061 for idx, info in enumerate(argument_types):
1063 out_java_struct += (", ")
1064 if idx == 0 and takes_self:
1065 out_java_struct += ("this.ptr")
1066 elif info.arg_name in default_constructor_args:
1067 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1068 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1069 if explode_idx != 0:
1070 out_java_struct += (", ")
1071 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1072 if explode_arg.from_hu_conv is not None:
1073 out_java_struct += (
1074 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1076 out_java_struct += (expl_arg_name)
1077 out_java_struct += (")")
1078 elif info.from_hu_conv is not None:
1079 out_java_struct += (info.from_hu_conv[0])
1081 out_java_struct += (info.arg_name)
1082 out_java_struct += (");\n")
1083 if return_type_info.to_hu_conv is not None:
1085 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1086 return_type_info.to_hu_conv_name) + "\n")
1088 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1090 for idx, info in enumerate(argument_types):
1091 if idx == 0 and takes_self:
1093 elif info.arg_name in default_constructor_args:
1094 for explode_arg in default_constructor_args[info.arg_name]:
1095 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1096 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1097 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1098 expl_arg_name).replace(
1099 "this", return_type_info.to_hu_conv_name) + ";\n")
1100 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1101 if not takes_self and return_type_info.to_hu_conv_name is not None:
1102 out_java_struct += (
1103 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1105 out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1107 if return_type_info.to_hu_conv_name is not None:
1108 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1109 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1110 out_java_struct += ("\t\treturn ret;\n")
1111 out_java_struct += ("\t}\n\n")
1113 return (out_java, out_c, out_java_struct)