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;
88 self.common_base = """
89 export default class CommonBase {
91 ptrs_to: object[] = []; // new LinkedList(); TODO: build linked list implementation
92 protected constructor(ptr: number) { this.ptr = ptr; }
93 public _test_only_get_ptr(): number { return this.ptr; }
94 protected finalize() {
95 // TODO: finalize myself
100 self.c_file_pfx = """#include "js-wasm.h"
101 #include <stdatomic.h>
102 #include <lightning.h>
104 // These should be provided...somehow...
105 void *memset(void *s, int c, size_t n);
106 void *memcpy(void *dest, const void *src, size_t n);
107 int memcmp(const void *s1, const void *s2, size_t n);
109 void __attribute__((noreturn)) abort(void);
110 static inline void assert(bool expression) {
111 if (!expression) { abort(); }
116 self.c_file_pfx = self.c_file_pfx + """
117 void *malloc(size_t size);
118 void free(void *ptr);
120 #define MALLOC(a, _) malloc(a)
121 #define FREE(p) if ((long)(p) > 1024) { free(p); }
122 #define DO_ASSERT(a) (void)(a)
126 self.c_file_pfx = self.c_file_pfx + """
127 // Always run a, then assert it is true:
128 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
129 // Assert a is true or do nothing
130 #define CHECK(a) DO_ASSERT(a)
132 // Running a leak check across all the allocations and frees of the JDK is a mess,
133 // so instead we implement our own naive leak checker here, relying on the -wrap
134 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
135 // and free'd in Rust or C across the generated bindings shared library.
138 typedef struct allocation {
139 struct allocation* next;
141 const char* struct_name;
143 static allocation* allocation_ll = NULL;
145 void* __real_malloc(size_t len);
146 void* __real_calloc(size_t nmemb, size_t len);
147 static void new_allocation(void* res, const char* struct_name) {
148 allocation* new_alloc = __real_malloc(sizeof(allocation));
149 new_alloc->ptr = res;
150 new_alloc->struct_name = struct_name;
151 new_alloc->next = allocation_ll;
152 allocation_ll = new_alloc;
154 static void* MALLOC(size_t len, const char* struct_name) {
155 void* res = __real_malloc(len);
156 new_allocation(res, struct_name);
159 void __real_free(void* ptr);
160 static void alloc_freed(void* ptr) {
161 allocation* p = NULL;
162 allocation* it = allocation_ll;
163 while (it->ptr != ptr) {
164 p = it; it = it->next;
166 //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
167 return; // addrsan should catch malloc-unknown and print more info than we have
170 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
171 DO_ASSERT(it->ptr == ptr);
174 static void FREE(void* ptr) {
175 if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
180 void* __wrap_malloc(size_t len) {
181 void* res = __real_malloc(len);
182 new_allocation(res, "malloc call");
185 void* __wrap_calloc(size_t nmemb, size_t len) {
186 void* res = __real_calloc(nmemb, len);
187 new_allocation(res, "calloc call");
190 void __wrap_free(void* ptr) {
191 if (ptr == NULL) return;
196 void* __real_realloc(void* ptr, size_t newlen);
197 void* __wrap_realloc(void* ptr, size_t len) {
198 if (ptr != NULL) alloc_freed(ptr);
199 void* res = __real_realloc(ptr, len);
200 new_allocation(res, "realloc call");
203 void __wrap_reallocarray(void* ptr, size_t new_sz) {
204 // Rust doesn't seem to use reallocarray currently
208 void __attribute__((destructor)) check_leaks() {
209 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
210 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
212 DO_ASSERT(allocation_ll == NULL);
215 self.c_file_pfx = self.c_file_pfx + """
216 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
217 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
218 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
219 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
221 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
223 typedef uint32_t int64_tArray;
224 typedef uint32_t int8_tArray;
225 typedef uint32_t uint32_tArray;
226 typedef uint32_t ptrArray;
227 typedef uint32_t jstring;
229 static inline uint32_t init_arr(size_t arr_len, size_t elem_size, const char *type_desc) {
230 uint32_t *elems = (uint32_t*)MALLOC(arr_len * elem_size + 4, type_desc);
232 return (uint32_t)elems;
235 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
236 char* err_buf = MALLOC(len + 4, "str conv buf");
237 *((uint32_t*)err_buf) = len;
238 memcpy(err_buf + 4, chars, len);
239 return (uint32_t) err_buf;
241 static inline LDKStr str_ref_to_owned_c(jstring str) {
242 uint32_t *str_len = (uint32_t*)str;
243 char* newchars = MALLOC(*str_len + 1, "String chars");
244 memcpy(newchars, (const char*)(str + 4), *str_len);
245 newchars[*str_len] = 0;
249 .chars_is_owned = true
254 typedef bool jboolean;
256 uint32_t __attribute__((visibility("default"))) TS_malloc(uint32_t size) {
257 return (uint32_t)MALLOC(size, "JS-Called malloc");
259 void __attribute__((visibility("default"))) TS_free(uint32_t ptr) {
264 self.hu_struct_file_prefix = f"""
265 import CommonBase from './CommonBase';
266 import * as bindings from '../bindings' // TODO: figure out location
269 self.c_fn_ty_pfx = ""
270 self.file_ext = ".ts"
271 self.ptr_c_ty = "uint32_t"
272 self.ptr_native_ty = "number"
273 self.result_c_ty = "uint32_t"
274 self.ptr_arr = "ptrArray"
275 self.get_native_arr_len_call = ("*((uint32_t*)", ")")
277 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
279 def create_native_arr_call(self, arr_len, ty_info):
280 if ty_info.c_ty == "int8_tArray":
281 return "init_arr(" + arr_len + ", sizeof(uint8_t), \"Native int8_tArray Bytes\")"
282 elif ty_info.c_ty == "int64_tArray":
283 return "init_arr(" + arr_len + ", sizeof(uint64_t), \"Native int64_tArray Bytes\")"
284 elif ty_info.c_ty == "uint32_tArray":
285 return "init_arr(" + arr_len + ", sizeof(uint32_t), \"Native uint32_tArray Bytes\")"
286 elif ty_info.c_ty == "ptrArray":
287 assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
288 return "init_arr(" + arr_len + ", sizeof(uint32_t), \"Native ptrArray Bytes\")"
290 print("Need to create arr!", ty_info.c_ty)
292 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
293 if ty_info.c_ty == "int8_tArray":
294 return ("memcpy((uint8_t*)(" + arr_name + " + 4), ", ", " + arr_len + ")")
297 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
298 if ty_info.c_ty == "int8_tArray":
300 return "memcpy(" + dest_name + ", (uint8_t*)(" + arr_name + " + 4), " + arr_len + ")"
302 return "(int8_t*)(" + arr_name + " + 4)"
304 return "(" + ty_info.subty.c_ty + "*)(" + arr_name + " + 4)"
305 def get_native_arr_elem(self, arr_name, idxc, ty_info):
306 assert False # Only called if above is None
307 def get_native_arr_ptr_call(self, ty_info):
308 if ty_info.subty is not None:
309 return "(" + ty_info.subty.c_ty + "*)(", " + 4)"
310 return "(" + ty_info.c_ty + "*)(", " + 4)"
311 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
313 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
314 if ty_info.c_ty == "int8_tArray":
319 def str_ref_to_native_call(self, var_name, str_len):
320 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
321 def str_ref_to_c_call(self, var_name):
322 return "str_ref_to_owned_c(" + var_name + ")"
324 def c_fn_name_define_pfx(self, fn_name, have_args):
325 return " __attribute__((visibility(\"default\"))) TS_" + fn_name + "("
327 def wasm_import_header(self, target):
328 if target == Target.NODEJS:
330 import * as fs from 'fs';
331 const source = fs.readFileSync('./ldk.wasm');
333 const memory = new WebAssembly.Memory({initial: 256});
334 const wasmModule = new WebAssembly.Module(source);
336 const imports: any = {};
339 imports.env.memoryBase = 0;
340 imports.env.memory = memory;
341 imports.env.tableBase = 0;
342 imports.env.table = new WebAssembly.Table({initial: 4, element: 'anyfunc'});
344 imports.env["abort"] = function () {
345 console.error("ABORT");
349 let isWasmInitialized: boolean = false;
354 const nextMultipleOfFour = (value: number) => {
355 return Math.ceil(value / 4) * 4;
358 const encodeUint8Array = (inputArray) => {
359 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
360 const arrayLengthView = new Uint32Array(memory.buffer, cArrayPointer, 1);
361 arrayLengthView[0] = inputArray.length;
362 const arrayMemoryView = new Uint8Array(memory.buffer, cArrayPointer + 4, inputArray.length);
363 arrayMemoryView.set(inputArray);
364 return cArrayPointer;
367 const encodeUint32Array = (inputArray) => {
368 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
369 const arrayMemoryView = new Uint32Array(memory.buffer, cArrayPointer, inputArray.length);
370 arrayMemoryView.set(inputArray, 1);
371 arrayMemoryView[0] = inputArray.length;
372 return cArrayPointer;
375 const getArrayLength = (arrayPointer) => {
376 const arraySizeViewer = new Uint32Array(
377 memory.buffer, // value
378 arrayPointer, // offset
381 return arraySizeViewer[0];
383 const decodeUint8Array = (arrayPointer, free = true) => {
384 const arraySize = getArrayLength(arrayPointer);
385 const actualArrayViewer = new Uint8Array(
386 memory.buffer, // value
387 arrayPointer + 4, // offset (ignoring length bytes)
388 arraySize // uint8 count
390 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
391 // will free the underlying memory when it becomes unreachable instead of copying here.
392 const actualArray = actualArrayViewer.slice(0, arraySize);
394 wasm.TS_free(arrayPointer);
398 const decodeUint32Array = (arrayPointer, free = true) => {
399 const arraySize = getArrayLength(arrayPointer);
400 const actualArrayViewer = new Uint32Array(
401 memory.buffer, // value
402 arrayPointer + 4, // offset (ignoring length bytes)
403 arraySize // uint32 count
405 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
406 // will free the underlying memory when it becomes unreachable instead of copying here.
407 const actualArray = actualArrayViewer.slice(0, arraySize);
409 wasm.TS_free(arrayPointer);
414 const encodeString = (string) => {
415 // make malloc count divisible by 4
416 const memoryNeed = nextMultipleOfFour(string.length + 1);
417 const stringPointer = wasm.TS_malloc(memoryNeed);
418 const stringMemoryView = new Uint8Array(
419 memory.buffer, // value
420 stringPointer, // offset
421 string.length + 1 // length
423 for (let i = 0; i < string.length; i++) {
424 stringMemoryView[i] = string.charCodeAt(i);
426 stringMemoryView[string.length] = 0;
427 return stringPointer;
430 const decodeString = (stringPointer, free = true) => {
431 const memoryView = new Uint8Array(memory.buffer, stringPointer);
435 while (memoryView[cursor] !== 0) {
436 result += String.fromCharCode(memoryView[cursor]);
441 wasm.wasm_free(stringPointer);
452 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
453 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
454 out_c = out_c + "\tswitch (ord) {\n"
457 out_typescript_enum_fields = ""
460 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
462 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
463 out_c = out_c + "\t}\n"
464 out_c = out_c + "\tabort();\n"
465 out_c = out_c + "}\n"
467 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
468 out_c = out_c + "\tswitch (val) {\n"
471 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
473 out_c = out_c + "\t\tdefault: abort();\n"
474 out_c = out_c + "\t}\n"
475 out_c = out_c + "}\n"
477 out_typescript_enum = f"""
478 export enum {struct_name} {{
479 {out_typescript_enum_fields}
483 return (out_c, out_typescript_enum, "")
485 def c_unitary_enum_to_native_call(self, ty_info):
486 return (ty_info.rust_obj + "_to_js(", ")")
487 def native_unitary_enum_to_c_call(self, ty_info):
488 return (ty_info.rust_obj + "_from_js(", ")")
490 def c_complex_enum_pass_ty(self, struct_name):
493 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
494 ret = "0 /* " + struct_name + " - " + variant + " */"
495 for param in c_params:
496 ret = ret + "; (void) " + param
499 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
500 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
502 constructor_arguments = ""
503 super_instantiator = ""
504 pointer_to_adder = ""
505 impl_constructor_arguments = ""
506 for var in flattened_field_var_conversions:
507 if isinstance(var, ConvInfo):
508 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
509 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
510 if var.from_hu_conv is not None:
511 super_instantiator += ", " + var.from_hu_conv[0]
512 if var.from_hu_conv[1] != "":
513 pointer_to_adder += var.from_hu_conv[1] + ";\n"
515 super_instantiator += ", " + first_to_lower(var.arg_name)
517 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
518 super_instantiator += ", " + first_to_lower(var[1])
519 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
520 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
522 # BUILD INTERFACE METHODS
523 out_java_interface = ""
524 out_interface_implementation_overrides = ""
526 for fn_line in field_function_lines:
527 java_method_descriptor = ""
528 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
529 out_java_interface += fn_line.fn_name + "("
530 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
532 for idx, arg_conv_info in enumerate(fn_line.args_ty):
534 out_java_interface += ", "
535 out_interface_implementation_overrides += ", "
536 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
537 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
538 java_method_descriptor += arg_conv_info.java_fn_ty_arg
539 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
540 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
541 java_methods.append((fn_line.fn_name, java_method_descriptor))
543 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
545 interface_method_override_inset = "\t\t\t\t\t\t"
546 interface_implementation_inset = "\t\t\t\t\t\t\t"
547 for arg_info in fn_line.args_ty:
548 if arg_info.to_hu_conv is not None:
549 out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
551 if fn_line.ret_ty_info.java_ty != "void":
552 out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
554 out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
556 for idx, arg_info in enumerate(fn_line.args_ty):
558 out_interface_implementation_overrides += ", "
559 if arg_info.to_hu_conv_name is not None:
560 out_interface_implementation_overrides += arg_info.to_hu_conv_name
562 out_interface_implementation_overrides += arg_info.arg_name
564 out_interface_implementation_overrides += ");\n"
565 if fn_line.ret_ty_info.java_ty != "void":
566 if fn_line.ret_ty_info.from_hu_conv is not None:
567 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"
568 if fn_line.ret_ty_info.from_hu_conv[1] != "":
569 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"
570 #if fn_line.ret_ty_info.rust_obj in result_types:
571 # XXX: We need to handle this in conversion logic so that its cross-language!
572 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
573 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
574 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
576 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
577 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
579 trait_constructor_arguments = ""
580 for var in field_var_conversions:
581 if isinstance(var, ConvInfo):
582 trait_constructor_arguments += ", " + var.arg_name
584 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl"
585 for suparg in var[2]:
586 if isinstance(suparg, ConvInfo):
587 trait_constructor_arguments += ", " + suparg.arg_name
589 trait_constructor_arguments += ", " + suparg[1]
590 trait_constructor_arguments += ").bindings_instance"
591 for suparg in var[2]:
592 if isinstance(suparg, ConvInfo):
593 trait_constructor_arguments += ", " + suparg.arg_name
595 trait_constructor_arguments += ", " + suparg[1]
597 out_typescript_human = f"""
598 {self.hu_struct_file_prefix}
600 export class {struct_name.replace("LDK","")} extends CommonBase {{
602 bindings_instance?: bindings.{struct_name};
604 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
605 if (Number.isFinite(ptr)) {{
607 this.bindings_instance = null;
609 // TODO: private constructor instantiation
610 super(bindings.{struct_name}_new(arg{super_instantiator}));
611 this.ptrs_to.push(arg);
616 protected finalize() {{
617 if (this.ptr != 0) {{
618 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
623 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
624 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
625 let structImplementation = <bindings.{struct_name}>{{
626 // todo: in-line interface filling
627 {out_interface_implementation_overrides}
629 impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
633 export interface {struct_name.replace("LDK", "")}Interface {{
637 class {struct_name}Holder {{
638 held: {struct_name.replace("LDK", "")};
642 out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
644 for fn_line in field_function_lines:
645 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
646 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
648 for idx, arg_conv_info in enumerate(fn_line.args_ty):
650 out_typescript_bindings = out_typescript_bindings + ", "
651 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
653 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
655 out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
657 out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
658 for var in flattened_field_var_conversions:
659 if isinstance(var, ConvInfo):
660 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
662 out_typescript_bindings += f", {var[1]}: {var[0]}"
664 out_typescript_bindings += f"""): number {{
665 throw new Error('unimplemented'); // TODO: bind to WASM
669 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
671 # Now that we've written out our java code (and created java_meths), generate C
672 out_c = "typedef struct " + struct_name + "_JCalls {\n"
673 out_c = out_c + "\tatomic_size_t refcnt;\n"
674 for var in flattened_field_var_conversions:
675 if isinstance(var, ConvInfo):
676 # We're a regular ol' field
680 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
681 for fn in field_function_lines:
682 if fn.fn_name != "free" and fn.fn_name != "clone":
683 out_c = out_c + "\tuint32_t " + fn.fn_name + "_meth;\n"
684 out_c = out_c + "} " + struct_name + "_JCalls;\n"
686 for fn_line in field_function_lines:
687 if fn_line.fn_name == "free":
688 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
689 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
690 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
691 for fn in field_function_lines:
692 if fn.fn_name != "free" and fn.fn_name != "clone":
693 out_c = out_c + "\t\tjs_free(j_calls->" + fn.fn_name + "_meth);\n"
694 out_c = out_c + "\t\tFREE(j_calls);\n"
695 out_c = out_c + "\t}\n}\n"
697 for idx, fn_line in enumerate(field_function_lines):
698 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
699 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
700 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
701 if fn_line.self_is_const:
702 out_c = out_c + "const void* this_arg"
704 out_c = out_c + "void* this_arg"
706 for idx, arg in enumerate(fn_line.args_ty):
707 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
709 out_c = out_c + ") {\n"
710 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
712 for arg_info in fn_line.args_ty:
713 if arg_info.ret_conv is not None:
714 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
715 out_c = out_c + arg_info.arg_name
716 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
718 if fn_line.ret_ty_info.c_ty.endswith("Array"):
719 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"
720 elif fn_line.ret_ty_info.java_ty == "void":
721 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
722 elif not fn_line.ret_ty_info.passed_as_ptr:
723 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
725 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"
727 for idx, arg_info in enumerate(fn_line.args_ty):
728 if arg_info.ret_conv is not None:
729 out_c = out_c + ", " + arg_info.ret_conv_name
731 out_c = out_c + ", " + arg_info.arg_name
732 out_c = out_c + ");\n"
733 if fn_line.ret_ty_info.arg_conv is not None:
734 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"
736 out_c = out_c + "}\n"
738 # Write out a clone function whether we need one or not, as we use them in moving to rust
739 out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
740 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
741 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
742 for var in field_var_conversions:
743 if not isinstance(var, ConvInfo):
744 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
745 out_c = out_c + "\treturn (void*) this_arg;\n"
746 out_c = out_c + "}\n"
748 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (/*TODO: JS Object Reference */void* o"
749 for var in flattened_field_var_conversions:
750 if isinstance(var, ConvInfo):
751 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
753 out_c = out_c + ", /*TODO: JS Object Reference */void* " + var[1]
754 out_c = out_c + ") {\n"
756 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
757 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
758 out_c = out_c + "\t//TODO: Assign calls->o from o\n"
760 for (fn_name, java_meth_descr) in java_meths:
761 if fn_name != "free" and fn_name != "clone":
762 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
763 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
765 for var in flattened_field_var_conversions:
766 if isinstance(var, ConvInfo) and var.arg_conv is not None:
767 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
768 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
769 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
770 for fn_line in field_function_lines:
771 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
772 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
773 elif fn_line.fn_name == "free":
774 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
776 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
777 for var in field_var_conversions:
778 if isinstance(var, ConvInfo):
779 if var.arg_conv_name is not None:
780 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
781 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
783 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
784 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
786 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
787 for suparg in var[2]:
788 if isinstance(suparg, ConvInfo):
789 out_c += ", " + suparg.arg_name
791 out_c += ", " + suparg[1]
793 out_c = out_c + "\t};\n"
794 for var in flattened_field_var_conversions:
795 if not isinstance(var, ConvInfo):
796 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
797 out_c = out_c + "\treturn ret;\n"
798 out_c = out_c + "}\n"
800 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"
801 for var in flattened_field_var_conversions:
802 if isinstance(var, ConvInfo):
803 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
805 out_c = out_c + ", /*TODO: JS Object Reference */ void* " + var[1]
806 out_c = out_c + ") {\n"
807 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
808 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
809 for var in flattened_field_var_conversions:
810 if isinstance(var, ConvInfo):
811 out_c = out_c + ", " + var.arg_name
813 out_c = out_c + ", " + var[1]
814 out_c = out_c + ");\n"
815 out_c = out_c + "\treturn (long)res_ptr;\n"
816 out_c = out_c + "}\n"
818 return (out_typescript_bindings, out_typescript_human, out_c)
820 def trait_struct_inc_refcnt(self, ty_info):
823 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
824 java_hu_type = struct_name.replace("LDK", "")
830 out_java_enum += (self.hu_struct_file_prefix)
831 out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
832 out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
833 out_java_enum += ("\tprotected finalize() {\n")
834 out_java_enum += ("\t\tsuper.finalize();\n")
835 out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
836 out_java_enum += ("\t}\n")
837 out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
838 out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
839 java_hu_subclasses = ""
841 out_java += ("\tpublic static class " + struct_name + " {\n")
842 out_java += ("\t\tprivate " + struct_name + "() {}\n")
843 for var in variant_list:
844 out_java += ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
845 java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
846 out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
847 out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
848 init_meth_params = ""
851 for idx, field_ty in enumerate(var.fields):
852 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
853 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
854 if field_ty.to_hu_conv is not None:
855 hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
856 hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
857 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
859 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
861 init_meth_params = init_meth_params + ", "
862 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
863 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
864 out_java += ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
865 out_java += (init_meth_body)
867 out_java += ("\t\t}\n")
868 out_java_enum += ("\t\t}\n")
869 java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
870 java_hu_subclasses = java_hu_subclasses + hu_conv_body
871 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
872 out_java += ("\t\tstatic native void init();\n")
873 out_java += ("\t}\n")
874 out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
875 out_java += ("\tstatic { " + struct_name + ".init(); }\n")
876 out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
878 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")
879 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n")
880 out_c += ("\tswitch(obj->tag) {\n")
881 for var in variant_list:
882 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
884 for idx, field_map in enumerate(var.fields):
885 if field_map.ret_conv is not None:
886 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
887 if var.tuple_variant:
888 out_c += "obj->" + camel_to_snake(var.var_name)
890 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
891 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
892 c_params.append(field_map.ret_conv_name)
894 if var.tuple_variant:
895 c_params.append("obj->" + camel_to_snake(var.var_name))
897 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
898 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
900 out_c += ("\t\tdefault: abort();\n")
901 out_c += ("\t}\n}\n")
902 out_java_enum += ("}\n")
903 out_java_enum += (java_hu_subclasses)
904 return (out_java, out_java_enum, out_c)
906 def map_opaque_struct(self, struct_name, struct_doc_comment):
909 if struct_name.startswith("LDKLocked"):
910 implementations += "implements AutoCloseable "
916 protected finalize() {
920 out_opaque_struct_human = f"""
921 {self.hu_struct_file_prefix}
923 export default class {struct_name.replace("LDK","")} extends CommonBase {implementations}{{
924 constructor(_dummy: object, ptr: number) {{
929 if (this.ptr != 0) {{
930 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
934 return out_opaque_struct_human
936 def map_function(self, argument_types, c_call_string, method_name, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
939 out_java_struct = None
941 out_java += ("\tpublic static native ")
942 out_c += (self.c_fn_ty_pfx)
943 out_c += (return_type_info.c_ty)
944 out_java += (return_type_info.java_ty)
945 if return_type_info.ret_conv is not None:
946 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
947 out_java += (" " + method_name + "(")
948 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
950 method_argument_string = ""
951 native_call_argument_string = ""
952 for idx, arg_conv_info in enumerate(argument_types):
954 method_argument_string += (", ")
955 native_call_argument_string += ', '
957 if arg_conv_info.c_ty != "void":
958 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
959 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
960 native_argument = arg_conv_info.arg_name
962 converter = self.wasm_encoding_map[arg_conv_info.c_ty]
963 native_argument = f"{converter}({arg_conv_info.arg_name})"
964 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
965 native_call_argument_string += native_argument
967 has_return_value = return_type_info.c_ty != 'void'
968 needs_decoding = return_type_info.c_ty in self.wasm_decoding_map
969 return_statement = 'return nativeResponseValue;'
970 if not has_return_value:
971 return_statement = '// debug statements here'
973 converter = self.wasm_decoding_map[return_type_info.c_ty]
974 return_statement = f"return {converter}(nativeResponseValue);"
976 out_java = f"""\texport function {method_name}({method_argument_string}): {return_type_info.java_ty} {{
977 if(!isWasmInitialized) {{
978 throw new Error("initializeWasm() must be awaited first!");
980 const nativeResponseValue = wasm.{method_name}({native_call_argument_string});
987 out_java_struct += ("\t// Skipped " + method_name + "\n")
989 meth_n = method_name[len(struct_meth) + 1:]
992 "\tpublic static " + return_type_info.java_hu_ty + " constructor_" + meth_n + "(")
994 out_java_struct += ("\tpublic " + return_type_info.java_hu_ty + " " + meth_n + "(")
995 for idx, arg in enumerate(argument_types):
997 if not takes_self or idx > 1:
998 out_java_struct += (", ")
1001 if arg.java_ty != "void":
1002 if arg.arg_name in default_constructor_args:
1003 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1004 if explode_idx != 0:
1005 out_java_struct += (", ")
1006 out_java_struct += (
1007 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1009 out_java_struct += (arg.java_hu_ty + " " + arg.arg_name)
1012 if out_java_struct is not None:
1013 out_java_struct += (") {\n")
1014 for info in argument_types:
1015 if info.arg_conv is not None:
1016 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1017 if return_type_info.ret_conv is not None:
1018 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1019 elif return_type_info.c_ty != "void":
1020 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1023 if c_call_string is None:
1024 out_c += (method_name + "(")
1026 out_c += (c_call_string)
1027 for idx, info in enumerate(argument_types):
1028 if info.arg_conv_name is not None:
1031 elif c_call_string is not None:
1033 out_c += (info.arg_conv_name)
1035 if return_type_info.ret_conv is not None:
1036 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1039 for info in argument_types:
1040 if info.arg_conv_cleanup is not None:
1041 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1042 if return_type_info.ret_conv is not None:
1043 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1044 elif return_type_info.c_ty != "void":
1045 out_c += ("\n\treturn ret_val;")
1046 out_c += ("\n}\n\n")
1049 out_java_struct += ("\t\t")
1050 if return_type_info.java_ty != "void":
1051 out_java_struct += (return_type_info.java_ty + " ret = ")
1052 out_java_struct += ("bindings." + method_name + "(")
1053 for idx, info in enumerate(argument_types):
1055 out_java_struct += (", ")
1056 if idx == 0 and takes_self:
1057 out_java_struct += ("this.ptr")
1058 elif info.arg_name in default_constructor_args:
1059 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1060 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1061 if explode_idx != 0:
1062 out_java_struct += (", ")
1063 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1064 if explode_arg.from_hu_conv is not None:
1065 out_java_struct += (
1066 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1068 out_java_struct += (expl_arg_name)
1069 out_java_struct += (")")
1070 elif info.from_hu_conv is not None:
1071 out_java_struct += (info.from_hu_conv[0])
1073 out_java_struct += (info.arg_name)
1074 out_java_struct += (");\n")
1075 if return_type_info.to_hu_conv is not None:
1077 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1078 return_type_info.to_hu_conv_name) + "\n")
1080 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1082 for idx, info in enumerate(argument_types):
1083 if idx == 0 and takes_self:
1085 elif info.arg_name in default_constructor_args:
1086 for explode_arg in default_constructor_args[info.arg_name]:
1087 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1088 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1089 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1090 expl_arg_name).replace(
1091 "this", return_type_info.to_hu_conv_name) + ";\n")
1092 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1093 if not takes_self and return_type_info.to_hu_conv_name is not None:
1094 out_java_struct += (
1095 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1097 out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1099 if return_type_info.to_hu_conv_name is not None:
1100 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1101 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1102 out_java_struct += ("\t\treturn ret;\n")
1103 out_java_struct += ("\t}\n\n")
1105 return (out_java, out_c, out_java_struct)