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, outdir: str, **kwargs):
16 self.struct_file_suffixes = {}
17 self.c_type_map = dict(
18 uint8_t = ['number', 'Uint8Array'],
19 uint16_t = ['number', 'Uint16Array'],
20 uint32_t = ['number', 'Uint32Array'],
21 uint64_t = ['number'],
24 self.wasm_decoding_map = dict(
25 int8_tArray = 'decodeUint8Array'
28 self.wasm_encoding_map = dict(
29 int8_tArray = 'encodeUint8Array',
32 self.to_hu_conv_templates = dict(
33 ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
34 default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
37 self.bindings_header = self.wasm_import_header(target) + """
38 export class VecOrSliceDef {
39 public dataptr: number;
40 public datalen: number;
41 public stride: number;
42 public constructor(dataptr: number, datalen: number, stride: number) {
43 this.dataptr = dataptr;
44 this.datalen = datalen;
52 System.loadLibrary(\"lightningjni\");
53 init(java.lang.Enum.class, VecOrSliceDef.class);
57 static native void init(java.lang.Class c, java.lang.Class slicedef);
58 static native void init_class_cache();
60 public static native boolean deref_bool(long ptr);
61 public static native long deref_long(long ptr);
62 public static native void free_heap_ptr(long ptr);
63 public static native byte[] read_bytes(long ptr, long len);
64 public static native byte[] get_u8_slice_bytes(long slice_ptr);
65 public static native long bytes_to_u8_vec(byte[] bytes);
66 public static native long new_txpointer_copy_data(byte[] txdata);
67 public static native void txpointer_free(long ptr);
68 public static native byte[] txpointer_get_buffer(long ptr);
69 public static native long vec_slice_len(long vec);
70 public static native long new_empty_slice_vec();
75 self.bindings_version_file = ""
77 self.bindings_footer = ""
82 self.common_base = """
83 function freer(f: () => void) { f() }
84 const finalizer = new FinalizationRegistry(freer);
85 function get_freeer(ptr: number, free_fn: (number) => void) {
91 export default class CommonBase {
92 protected ptr: number;
93 protected ptrs_to: object[] = [];
94 protected constructor(ptr: number, free_fn: (ptr: number) => void) {
96 if (Number.isFinite(ptr) && ptr != 0){
97 finalizer.register(this, get_freeer(ptr, free_fn));
100 protected static add_ref_from(holder: CommonBase, referent: object) {
101 holder.ptrs_to.push(referent);
103 public _test_only_get_ptr(): number { return this.ptr; }
107 self.c_file_pfx = """#include "js-wasm.h"
108 #include <stdatomic.h>
109 #include <lightning.h>
111 // These should be provided...somehow...
112 void *memset(void *s, int c, size_t n);
113 void *memcpy(void *dest, const void *src, size_t n);
114 int memcmp(const void *s1, const void *s2, size_t n);
116 void __attribute__((noreturn)) abort(void);
117 static inline void assert(bool expression) {
118 if (!expression) { abort(); }
123 self.c_file_pfx = self.c_file_pfx + """
124 void *malloc(size_t size);
125 void free(void *ptr);
127 #define MALLOC(a, _) malloc(a)
128 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
129 #define DO_ASSERT(a) (void)(a)
131 #define CHECK_ACCESS(p)
132 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
135 self.c_file_pfx = self.c_file_pfx + """
136 // Always run a, then assert it is true:
137 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
138 // Assert a is true or do nothing
139 #define CHECK(a) DO_ASSERT(a)
141 // Running a leak check across all the allocations and frees of the JDK is a mess,
142 // so instead we implement our own naive leak checker here, relying on the -wrap
143 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
144 // and free'd in Rust or C across the generated bindings shared library.
147 typedef struct allocation {
148 struct allocation* next;
150 const char* struct_name;
152 static allocation* allocation_ll = NULL;
154 void* __real_malloc(size_t len);
155 void* __real_calloc(size_t nmemb, size_t len);
156 static void new_allocation(void* res, const char* struct_name) {
157 allocation* new_alloc = __real_malloc(sizeof(allocation));
158 new_alloc->ptr = res;
159 new_alloc->struct_name = struct_name;
160 new_alloc->next = allocation_ll;
161 allocation_ll = new_alloc;
163 static void* MALLOC(size_t len, const char* struct_name) {
164 void* res = __real_malloc(len);
165 new_allocation(res, struct_name);
168 void __real_free(void* ptr);
169 static void alloc_freed(void* ptr) {
170 allocation* p = NULL;
171 allocation* it = allocation_ll;
172 while (it->ptr != ptr) {
173 p = it; it = it->next;
175 //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
176 return; // addrsan should catch malloc-unknown and print more info than we have
179 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
180 DO_ASSERT(it->ptr == ptr);
183 static void FREE(void* ptr) {
184 if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
189 static void CHECK_ACCESS(const void* ptr) {
190 allocation* it = allocation_ll;
191 while (it->ptr != ptr) {
194 return; // addrsan should catch malloc-unknown and print more info than we have
198 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
199 if (v.is_owned && v.inner != NULL) { \\
200 const void *p = __unmangle_inner_ptr(v.inner); \\
206 void* __wrap_malloc(size_t len) {
207 void* res = __real_malloc(len);
208 new_allocation(res, "malloc call");
211 void* __wrap_calloc(size_t nmemb, size_t len) {
212 void* res = __real_calloc(nmemb, len);
213 new_allocation(res, "calloc call");
216 void __wrap_free(void* ptr) {
217 if (ptr == NULL) return;
222 void* __real_realloc(void* ptr, size_t newlen);
223 void* __wrap_realloc(void* ptr, size_t len) {
224 if (ptr != NULL) alloc_freed(ptr);
225 void* res = __real_realloc(ptr, len);
226 new_allocation(res, "realloc call");
229 void __wrap_reallocarray(void* ptr, size_t new_sz) {
230 // Rust doesn't seem to use reallocarray currently
234 void __attribute__((destructor)) check_leaks() {
235 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
236 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
238 DO_ASSERT(allocation_ll == NULL);
241 self.c_file_pfx = self.c_file_pfx + """
242 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
243 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
244 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
245 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
247 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
249 #define DECL_ARR_TYPE(ty, name) \\
250 struct name##array { \\
254 typedef struct name##array * name##Array; \\
255 static inline name##Array init_##name##Array(size_t arr_len) { \\
256 name##Array arr = (name##Array)MALLOC(arr_len * sizeof(ty) + sizeof(uint32_t), "##name array init"); \\
257 arr->arr_len = arr_len; \\
261 DECL_ARR_TYPE(int64_t, int64_t);
262 DECL_ARR_TYPE(int8_t, int8_t);
263 DECL_ARR_TYPE(uint32_t, uint32_t);
264 DECL_ARR_TYPE(void*, ptr);
265 DECL_ARR_TYPE(char, char);
266 typedef charArray jstring;
268 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
269 charArray arr = init_charArray(len);
270 memcpy(arr->elems, chars, len);
273 static inline LDKStr str_ref_to_owned_c(const jstring str) {
274 char* newchars = MALLOC(str->arr_len + 1, "String chars");
275 memcpy(newchars, str->elems, str->arr_len);
276 newchars[str->arr_len] = 0;
280 .chars_is_owned = true
285 typedef bool jboolean;
287 uint32_t __attribute__((visibility("default"))) TS_malloc(uint32_t size) {
288 return (uint32_t)MALLOC(size, "JS-Called malloc");
290 void __attribute__((visibility("default"))) TS_free(uint32_t ptr) {
295 self.c_version_file = ""
297 self.hu_struct_file_prefix = """
298 import CommonBase from './CommonBase.mjs';
299 import * as bindings from '../bindings.mjs'
300 import * as InternalUtils from '../InternalUtils.mjs'
303 self.c_fn_ty_pfx = ""
304 self.file_ext = ".mts"
305 self.ptr_c_ty = "uint32_t"
306 self.ptr_native_ty = "number"
307 self.result_c_ty = "uint32_t"
308 self.ptr_arr = "ptrArray"
309 self.is_arr_some_check = ("", " != 0")
310 self.get_native_arr_len_call = ("", "->arr_len")
312 with open(outdir + "/InternalUtils.mts", "w") as f:
313 f.write("export function check_arr_len(arr: Uint8Array, len: number): Uint8Array {\n")
314 f.write("\tif (arr.length != len) { throw new Error(\"Expected array of length \" + len + \"got \" + arr.length); }\n")
315 f.write("\treturn arr;\n")
318 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
320 def create_native_arr_call(self, arr_len, ty_info):
321 if ty_info.c_ty == "ptrArray":
322 assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
323 return "init_" + ty_info.c_ty + "(" + arr_len + ")"
324 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
325 if ty_info.c_ty == "int8_tArray":
326 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
329 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
330 if ty_info.c_ty == "int8_tArray":
332 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + ")"
333 if ty_info.c_ty == "ptrArray":
334 return "(void*) " + arr_name + "->elems"
337 return arr_name + "->elems"
338 def get_native_arr_elem(self, arr_name, idxc, ty_info):
339 assert False # Only called if above is None
340 def get_native_arr_ptr_call(self, ty_info):
341 if ty_info.subty is not None:
342 return "(" + ty_info.subty.c_ty + "*)(", " + 4)"
343 return "(" + ty_info.c_ty + "*)(", " + 4)"
344 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
346 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
347 if ty_info.c_ty == "int8_tArray":
352 def str_ref_to_native_call(self, var_name, str_len):
353 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
354 def str_ref_to_c_call(self, var_name):
355 return "str_ref_to_owned_c(" + var_name + ")"
357 def c_fn_name_define_pfx(self, fn_name, have_args):
358 return " __attribute__((visibility(\"default\"))) TS_" + fn_name + "("
360 def wasm_import_header(self, target):
362 const memory = new WebAssembly.Memory({initial: 256});
364 const imports: any = {};
367 imports.env.memoryBase = 0;
368 imports.env.memory = memory;
369 imports.env.tableBase = 0;
370 imports.env.table = new WebAssembly.Table({initial: 4, element: 'anyfunc'});
372 imports.env["abort"] = function () {
373 console.error("ABORT");
375 imports.env["js_invoke_function"] = function(fn: number, arg1: number, arg2: number, arg3: number, arg4: number, arg5: number, arg6: number, arg7: number, arg8: number, arg9: number, arg10: number) {
376 console.log('function called from wasm:', fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
378 imports.env["js_free_function_ptr"] = function(fn: number) {
379 console.log("function ptr free'd from wasm:", fn);
382 imports.wasi_snapshot_preview1 = {
384 console.log("ABORT");
386 "random_get" : () => {
387 console.log("RAND GET");
389 "environ_sizes_get" : () => {
390 console.log("wasi_snapshot_preview1:environ_sizes_get");
392 "proc_exit" : () => {
393 console.log("wasi_snapshot_preview1:proc_exit");
395 "environ_get" : () => {
396 console.log("wasi_snapshot_preview1:environ_get");
401 let isWasmInitialized: boolean = false;
404 if target == Target.NODEJS:
405 res += """import * as fs from 'fs';
406 export async function initializeWasm(path) {
407 const source = fs.readFileSync(path);
408 const { instance: wasmInstance } = await WebAssembly.instantiate(source, imports);
409 wasm = wasmInstance.exports;
410 isWasmInitialized = true;
415 export async function initializeWasm(uri) {
416 const stream = fetch(uri);
417 const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);
418 wasm = wasmInstance.exports;
419 isWasmInitialized = true;
429 const nextMultipleOfFour = (value: number) => {
430 return Math.ceil(value / 4) * 4;
433 const encodeUint8Array = (inputArray) => {
434 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
435 const arrayLengthView = new Uint32Array(memory.buffer, cArrayPointer, 1);
436 arrayLengthView[0] = inputArray.length;
437 const arrayMemoryView = new Uint8Array(memory.buffer, cArrayPointer + 4, inputArray.length);
438 arrayMemoryView.set(inputArray);
439 return cArrayPointer;
442 const encodeUint32Array = (inputArray) => {
443 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
444 const arrayMemoryView = new Uint32Array(memory.buffer, cArrayPointer, inputArray.length);
445 arrayMemoryView.set(inputArray, 1);
446 arrayMemoryView[0] = inputArray.length;
447 return cArrayPointer;
450 const getArrayLength = (arrayPointer) => {
451 const arraySizeViewer = new Uint32Array(
452 memory.buffer, // value
453 arrayPointer, // offset
456 return arraySizeViewer[0];
458 const decodeUint8Array = (arrayPointer, free = true) => {
459 const arraySize = getArrayLength(arrayPointer);
460 const actualArrayViewer = new Uint8Array(
461 memory.buffer, // value
462 arrayPointer + 4, // offset (ignoring length bytes)
463 arraySize // uint8 count
465 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
466 // will free the underlying memory when it becomes unreachable instead of copying here.
467 const actualArray = actualArrayViewer.slice(0, arraySize);
469 wasm.TS_free(arrayPointer);
473 const decodeUint32Array = (arrayPointer, free = true) => {
474 const arraySize = getArrayLength(arrayPointer);
475 const actualArrayViewer = new Uint32Array(
476 memory.buffer, // value
477 arrayPointer + 4, // offset (ignoring length bytes)
478 arraySize // uint32 count
480 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
481 // will free the underlying memory when it becomes unreachable instead of copying here.
482 const actualArray = actualArrayViewer.slice(0, arraySize);
484 wasm.TS_free(arrayPointer);
489 const encodeString = (string) => {
490 // make malloc count divisible by 4
491 const memoryNeed = nextMultipleOfFour(string.length + 1);
492 const stringPointer = wasm.TS_malloc(memoryNeed);
493 const stringMemoryView = new Uint8Array(
494 memory.buffer, // value
495 stringPointer, // offset
496 string.length + 1 // length
498 for (let i = 0; i < string.length; i++) {
499 stringMemoryView[i] = string.charCodeAt(i);
501 stringMemoryView[string.length] = 0;
502 return stringPointer;
505 const decodeString = (stringPointer, free = true) => {
506 const memoryView = new Uint8Array(memory.buffer, stringPointer);
510 while (memoryView[cursor] !== 0) {
511 result += String.fromCharCode(memoryView[cursor]);
516 wasm.wasm_free(stringPointer);
526 def var_decl_statement(self, ty_string, var_name, statement):
527 return "const " + var_name + ": " + ty_string + " = " + statement
529 def add_ref(self, holder, referent):
530 return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
532 def obj_defined(self, struct_names, folder):
533 with open(self.outdir + "/index.mts", 'a') as index:
534 index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
535 with open(self.outdir + "/imports.mts.part", 'a') as imports:
536 imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
538 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
539 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
540 out_c = out_c + "\tswitch (ord) {\n"
543 out_typescript_enum_fields = ""
545 for var, var_docs in variants:
546 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
548 if var_docs is not None:
549 out_typescript_enum_fields += f"/**\n * {var_docs}\n */\n"
550 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
551 out_c = out_c + "\t}\n"
552 out_c = out_c + "\tabort();\n"
553 out_c = out_c + "}\n"
555 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
556 out_c = out_c + "\tswitch (val) {\n"
558 for var, _ in variants:
559 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
561 out_c = out_c + "\t\tdefault: abort();\n"
562 out_c = out_c + "\t}\n"
563 out_c = out_c + "}\n"
565 out_typescript = f"""
566 export enum {struct_name} {{
567 {out_typescript_enum_fields}
570 out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
571 self.obj_defined([struct_name], "enums")
572 return (out_c, out_typescript_enum, out_typescript)
574 def c_unitary_enum_to_native_call(self, ty_info):
575 return (ty_info.rust_obj + "_to_js(", ")")
576 def native_unitary_enum_to_c_call(self, ty_info):
577 return (ty_info.rust_obj + "_from_js(", ")")
579 def c_complex_enum_pass_ty(self, struct_name):
582 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
583 ret = "0 /* " + struct_name + " - " + variant + " */"
584 for param in c_params:
585 ret = ret + "; (void) " + param
588 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
589 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
591 constructor_arguments = ""
592 super_instantiator = ""
593 pointer_to_adder = ""
594 impl_constructor_arguments = ""
595 for var in flattened_field_var_conversions:
596 if isinstance(var, ConvInfo):
597 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
598 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
599 if var.from_hu_conv is not None:
600 super_instantiator += ", " + var.from_hu_conv[0]
601 if var.from_hu_conv[1] != "":
602 pointer_to_adder += var.from_hu_conv[1] + ";\n"
604 super_instantiator += ", " + first_to_lower(var.arg_name)
606 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
607 super_instantiator += ", " + first_to_lower(var[1])
608 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
609 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
611 # BUILD INTERFACE METHODS
612 out_java_interface = ""
613 out_interface_implementation_overrides = ""
615 for fn_line in field_function_lines:
616 java_method_descriptor = ""
617 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
618 out_java_interface += fn_line.fn_name + "("
619 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
621 for idx, arg_conv_info in enumerate(fn_line.args_ty):
623 out_java_interface += ", "
624 out_interface_implementation_overrides += ", "
625 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
626 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
627 java_method_descriptor += arg_conv_info.java_fn_ty_arg
628 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
629 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
630 java_methods.append((fn_line.fn_name, java_method_descriptor))
632 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
634 interface_method_override_inset = "\t\t\t\t\t\t"
635 interface_implementation_inset = "\t\t\t\t\t\t\t"
636 for arg_info in fn_line.args_ty:
637 if arg_info.to_hu_conv is not None:
638 out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
640 if fn_line.ret_ty_info.java_ty != "void":
641 out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
643 out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
645 for idx, arg_info in enumerate(fn_line.args_ty):
647 out_interface_implementation_overrides += ", "
648 if arg_info.to_hu_conv_name is not None:
649 out_interface_implementation_overrides += arg_info.to_hu_conv_name
651 out_interface_implementation_overrides += arg_info.arg_name
653 out_interface_implementation_overrides += ");\n"
654 if fn_line.ret_ty_info.java_ty != "void":
655 if fn_line.ret_ty_info.from_hu_conv is not None:
656 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"
657 if fn_line.ret_ty_info.from_hu_conv[1] != "":
658 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"
659 #if fn_line.ret_ty_info.rust_obj in result_types:
660 # XXX: We need to handle this in conversion logic so that its cross-language!
661 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
662 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
663 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
665 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
666 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
668 trait_constructor_arguments = ""
669 for var in field_var_conversions:
670 if isinstance(var, ConvInfo):
671 trait_constructor_arguments += ", " + var.arg_name
673 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl"
674 for suparg in var[2]:
675 if isinstance(suparg, ConvInfo):
676 trait_constructor_arguments += ", " + suparg.arg_name
678 trait_constructor_arguments += ", " + suparg[1]
679 trait_constructor_arguments += ").bindings_instance"
680 for suparg in var[2]:
681 if isinstance(suparg, ConvInfo):
682 trait_constructor_arguments += ", " + suparg.arg_name
684 trait_constructor_arguments += ", " + suparg[1]
686 out_typescript_human = f"""
687 {self.hu_struct_file_prefix}
689 {struct_name.replace("LDK","")} extends CommonBase {{
691 bindings_instance?: bindings.{struct_name};
693 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
694 if (Number.isFinite(ptr)) {{
695 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
696 this.bindings_instance = null;
698 // TODO: private constructor instantiation
699 super(bindings.{struct_name}_new(arg{super_instantiator}));
700 this.ptrs_to.push(arg);
705 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
706 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
707 let structImplementation = <bindings.{struct_name}>{{
708 // todo: in-line interface filling
709 {out_interface_implementation_overrides}
711 impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
714 export interface {struct_name.replace("LDK", "")}Interface {{
718 class {struct_name}Holder {{
719 held: {struct_name.replace("LDK", "")};
723 out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
725 for fn_line in field_function_lines:
726 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
727 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
729 for idx, arg_conv_info in enumerate(fn_line.args_ty):
731 out_typescript_bindings = out_typescript_bindings + ", "
732 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
734 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
736 out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
738 out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
739 for var in flattened_field_var_conversions:
740 if isinstance(var, ConvInfo):
741 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
743 out_typescript_bindings += f", {var[1]}: {var[0]}"
745 out_typescript_bindings += f"""): number {{
746 throw new Error('unimplemented'); // TODO: bind to WASM
750 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
752 # Now that we've written out our java code (and created java_meths), generate C
753 out_c = "typedef struct " + struct_name + "_JCalls {\n"
754 out_c = out_c + "\tatomic_size_t refcnt;\n"
755 for var in flattened_field_var_conversions:
756 if isinstance(var, ConvInfo):
757 # We're a regular ol' field
761 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
762 for fn in field_function_lines:
763 if fn.fn_name != "free" and fn.fn_name != "cloned":
764 out_c = out_c + "\tuint32_t " + fn.fn_name + "_meth;\n"
765 out_c = out_c + "} " + struct_name + "_JCalls;\n"
767 for fn_line in field_function_lines:
768 if fn_line.fn_name == "free":
769 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
770 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
771 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
772 for fn in field_function_lines:
773 if fn.fn_name != "free" and fn.fn_name != "cloned":
774 out_c = out_c + "\t\tjs_free_function_ptr(j_calls->" + fn.fn_name + "_meth);\n"
775 out_c = out_c + "\t\tFREE(j_calls);\n"
776 out_c = out_c + "\t}\n}\n"
778 for idx, fn_line in enumerate(field_function_lines):
779 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
780 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
781 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
782 if fn_line.self_is_const:
783 out_c = out_c + "const void* this_arg"
785 out_c = out_c + "void* this_arg"
787 for idx, arg in enumerate(fn_line.args_ty):
788 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
790 out_c = out_c + ") {\n"
791 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
793 for arg_info in fn_line.args_ty:
794 if arg_info.ret_conv is not None:
795 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
796 out_c = out_c + arg_info.arg_name
797 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
799 if fn_line.ret_ty_info.c_ty.endswith("Array"):
800 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
801 out_c += "js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
802 elif fn_line.ret_ty_info.java_ty == "void":
803 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
804 elif fn_line.ret_ty_info.java_ty == "String":
805 out_c = out_c + "\tjstring ret = (jstring)js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
806 elif not fn_line.ret_ty_info.passed_as_ptr:
807 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
809 out_c = out_c + "\tuint32_t ret = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
811 for idx, arg_info in enumerate(fn_line.args_ty):
812 if arg_info.ret_conv is not None:
813 out_c = out_c + ", (uint32_t)" + arg_info.ret_conv_name
815 out_c = out_c + ", (uint32_t)" + arg_info.arg_name
816 out_c = out_c + ");\n"
817 if fn_line.ret_ty_info.arg_conv is not None:
818 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"
820 out_c = out_c + "}\n"
822 # Write out a clone function whether we need one or not, as we use them in moving to rust
823 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
824 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
825 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
826 for var in field_var_conversions:
827 if not isinstance(var, ConvInfo):
828 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
829 out_c = out_c + "}\n"
831 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (/*TODO: JS Object Reference */void* o"
832 for var in flattened_field_var_conversions:
833 if isinstance(var, ConvInfo):
834 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
836 out_c = out_c + ", /*TODO: JS Object Reference */void* " + var[1]
837 out_c = out_c + ") {\n"
839 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
840 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
841 out_c = out_c + "\t//TODO: Assign calls->o from o\n"
843 for (fn_name, java_meth_descr) in java_meths:
844 if fn_name != "free" and fn_name != "cloned":
845 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
846 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
848 for var in flattened_field_var_conversions:
849 if isinstance(var, ConvInfo) and var.arg_conv is not None:
850 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
851 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
852 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
853 for fn_line in field_function_lines:
854 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
855 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
856 elif fn_line.fn_name == "free":
857 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
859 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
860 for var in field_var_conversions:
861 if isinstance(var, ConvInfo):
862 if var.arg_conv_name is not None:
863 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
864 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
866 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
867 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
869 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
870 for suparg in var[2]:
871 if isinstance(suparg, ConvInfo):
872 out_c += ", " + suparg.arg_name
874 out_c += ", " + suparg[1]
876 out_c = out_c + "\t};\n"
877 for var in flattened_field_var_conversions:
878 if not isinstance(var, ConvInfo):
879 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
880 out_c = out_c + "\treturn ret;\n"
881 out_c = out_c + "}\n"
883 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"
884 for var in flattened_field_var_conversions:
885 if isinstance(var, ConvInfo):
886 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
888 out_c = out_c + ", /*TODO: JS Object Reference */ void* " + var[1]
889 out_c = out_c + ") {\n"
890 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
891 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
892 for var in flattened_field_var_conversions:
893 if isinstance(var, ConvInfo):
894 out_c = out_c + ", " + var.arg_name
896 out_c = out_c + ", " + var[1]
897 out_c = out_c + ");\n"
898 out_c = out_c + "\treturn (long)res_ptr;\n"
899 out_c = out_c + "}\n"
901 return (out_typescript_bindings, out_typescript_human, out_c)
903 def trait_struct_inc_refcnt(self, ty_info):
906 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
907 bindings_type = struct_name.replace("LDK", "")
908 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
914 out_java_enum += (self.hu_struct_file_prefix)
917 java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
918 java_hu_class += "\tprotected constructor(_dummy: object, ptr: number) { super(ptr, bindings." + bindings_type + "_free); }\n"
919 java_hu_class += "\t/* @internal */\n"
920 java_hu_class += f"\tpublic static constr_from_ptr(ptr: number): {java_hu_type} {{\n"
921 java_hu_class += f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n"
922 java_hu_subclasses = ""
924 out_java += "\texport class " + struct_name + " {\n"
925 out_java += "\t\tprotected constructor() {}\n"
927 for var in variant_list:
928 java_subclasses += "\texport class " + struct_name + "_" + var.var_name + " extends " + struct_name + " {\n"
929 java_hu_subclasses = java_hu_subclasses + "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
930 java_hu_class += "\t\tif (raw_val instanceof bindings." + struct_name + "_" + var.var_name + ") {\n"
931 java_hu_class += "\t\t\treturn new " + java_hu_type + "_" + var.var_name + "(ptr, raw_val);\n"
932 init_meth_params = ""
934 for idx, (field_ty, field_docs) in enumerate(var.fields):
935 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
936 if field_ty.to_hu_conv is not None:
937 hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
938 hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
939 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
941 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
943 init_meth_params += ", "
944 init_meth_params += "public " + field_ty.arg_name + ": " + field_ty.java_ty
945 java_subclasses += "\t\tconstructor(" + init_meth_params + ") { super(); }\n"
946 java_subclasses += "\t}\n"
947 java_hu_class += "\t\t}\n"
948 java_hu_subclasses += "\t/* @internal */\n"
949 java_hu_subclasses += "\tpublic constructor(ptr: number, obj: bindings." + struct_name + "_" + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
950 java_hu_subclasses = java_hu_subclasses + hu_conv_body
951 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
952 out_java += ("\t}\n")
953 out_java += java_subclasses
954 java_hu_class += "\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n"
955 out_java += self.fn_call_body(struct_name + "_ref_from_ptr", "uint32_t", "number", "ptr: number", "ptr")
957 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")
958 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n")
959 out_c += ("\tswitch(obj->tag) {\n")
960 for var in variant_list:
961 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
963 for idx, (field_map, _) in enumerate(var.fields):
964 if field_map.ret_conv is not None:
965 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
966 if var.tuple_variant:
967 out_c += "obj->" + camel_to_snake(var.var_name)
969 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
970 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
971 c_params.append(field_map.ret_conv_name)
973 if var.tuple_variant:
974 c_params.append("obj->" + camel_to_snake(var.var_name))
976 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
977 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
979 out_c += ("\t\tdefault: abort();\n")
980 out_c += ("\t}\n}\n")
981 out_java_enum += java_hu_class
982 self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
983 self.obj_defined([java_hu_type], "structs")
984 return (out_java, out_java_enum, out_c)
986 def map_opaque_struct(self, struct_name, struct_doc_comment):
989 if struct_name.startswith("LDKLocked"):
990 return "NOT IMPLEMENTED"
992 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
993 out_opaque_struct_human = f"""{self.hu_struct_file_prefix}
995 export class {hu_name} extends CommonBase {implementations}{{
997 public constructor(_dummy: object, ptr: number) {{
998 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1002 self.obj_defined([hu_name], "structs")
1003 return out_opaque_struct_human
1005 def map_tuple(self, struct_name):
1006 return self.map_opaque_struct(struct_name, "A Tuple")
1008 def map_result(self, struct_name, res_map, err_map):
1009 human_ty = struct_name.replace("LDKCResult", "Result")
1011 suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1012 if res_map.java_hu_ty != "void":
1013 suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1016 public constructor(_dummy: object, ptr: number) {{
1019 if res_map.java_hu_ty == "void":
1021 elif res_map.to_hu_conv is not None:
1022 suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1023 suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1024 suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1026 suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1027 suffixes += "\t}\n}\n"
1029 suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1030 if err_map.java_hu_ty != "void":
1031 suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1034 public constructor(_dummy: object, ptr: number) {{
1037 if err_map.java_hu_ty == "void":
1039 elif err_map.to_hu_conv is not None:
1040 suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1041 suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1042 suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1044 suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1045 suffixes += "\t}\n}"
1047 self.struct_file_suffixes[human_ty] = suffixes
1048 self.obj_defined([human_ty], "structs")
1050 return f"""{self.hu_struct_file_prefix}
1052 export class {human_ty} extends CommonBase {{
1053 protected constructor(_dummy: object, ptr: number) {{
1054 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1057 public static constr_from_ptr(ptr: number): {human_ty} {{
1058 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1059 return new {human_ty}_OK(null, ptr);
1061 return new {human_ty}_Err(null, ptr);
1066 def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1067 has_return_value = return_c_ty != 'void'
1068 needs_decoding = return_c_ty in self.wasm_decoding_map
1069 return_statement = 'return nativeResponseValue;'
1070 if not has_return_value:
1071 return_statement = '// debug statements here'
1072 elif needs_decoding:
1073 converter = self.wasm_decoding_map[return_c_ty]
1074 return_statement = f"return {converter}(nativeResponseValue);"
1076 return f"""\texport function {method_name}({method_argument_string}): {return_java_ty} {{
1077 if(!isWasmInitialized) {{
1078 throw new Error("initializeWasm() must be awaited first!");
1080 const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1084 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):
1087 out_java_struct = None
1090 out_c += (self.c_fn_ty_pfx)
1091 out_c += (return_type_info.c_ty)
1092 out_java += (return_type_info.java_ty)
1093 if return_type_info.ret_conv is not None:
1094 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1095 out_java += (" " + method_name + "(")
1096 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
1098 method_argument_string = ""
1099 native_call_argument_string = ""
1100 for idx, arg_conv_info in enumerate(argument_types):
1102 method_argument_string += (", ")
1103 native_call_argument_string += ', '
1105 if arg_conv_info.c_ty != "void":
1106 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1107 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
1108 native_argument = arg_conv_info.arg_name
1110 converter = self.wasm_encoding_map[arg_conv_info.c_ty]
1111 native_argument = f"{converter}({arg_conv_info.arg_name})"
1112 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1113 native_call_argument_string += native_argument
1114 out_java = self.fn_call_body(method_name, return_type_info.c_ty, return_type_info.java_ty, method_argument_string, native_call_argument_string)
1116 out_java_struct = ""
1118 out_java_struct += ("\t// Skipped " + method_name + "\n")
1121 out_java_struct += (
1122 "\tpublic static constructor_" + meth_n + "(")
1124 out_java_struct += ("\tpublic " + meth_n + "(")
1125 for idx, arg in enumerate(argument_types):
1127 if not takes_self or idx > 1:
1128 out_java_struct += (", ")
1131 if arg.java_ty != "void":
1132 if arg.arg_name in default_constructor_args:
1133 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1134 if explode_idx != 0:
1135 out_java_struct += (", ")
1136 out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1138 out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1141 if out_java_struct is not None:
1142 out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1143 for info in argument_types:
1144 if info.arg_conv is not None:
1145 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1146 if return_type_info.ret_conv is not None:
1147 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1148 elif return_type_info.c_ty != "void":
1149 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1152 if c_call_string is None:
1153 out_c += (method_name + "(")
1155 out_c += (c_call_string)
1156 for idx, info in enumerate(argument_types):
1157 if info.arg_conv_name is not None:
1160 elif c_call_string is not None:
1162 out_c += (info.arg_conv_name)
1164 if return_type_info.ret_conv is not None:
1165 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1168 for info in argument_types:
1169 if info.arg_conv_cleanup is not None:
1170 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1171 if return_type_info.ret_conv is not None:
1172 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1173 elif return_type_info.c_ty != "void":
1174 out_c += ("\n\treturn ret_val;")
1175 out_c += ("\n}\n\n")
1178 out_java_struct += ("\t\t")
1179 if return_type_info.java_ty != "void":
1180 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1181 out_java_struct += ("bindings." + method_name + "(")
1182 for idx, info in enumerate(argument_types):
1184 out_java_struct += (", ")
1185 if idx == 0 and takes_self:
1186 out_java_struct += ("this.ptr")
1187 elif info.arg_name in default_constructor_args:
1188 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1189 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1190 if explode_idx != 0:
1191 out_java_struct += (", ")
1192 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1193 if explode_arg.from_hu_conv is not None:
1194 out_java_struct += (
1195 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1197 out_java_struct += (expl_arg_name)
1198 out_java_struct += (")")
1199 elif info.from_hu_conv is not None:
1200 out_java_struct += (info.from_hu_conv[0])
1202 out_java_struct += (info.arg_name)
1203 out_java_struct += (");\n")
1204 if return_type_info.to_hu_conv is not None:
1206 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1207 return_type_info.to_hu_conv_name) + "\n")
1209 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1211 for idx, info in enumerate(argument_types):
1212 if idx == 0 and takes_self:
1214 elif info.arg_name in default_constructor_args:
1215 for explode_arg in default_constructor_args[info.arg_name]:
1216 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1217 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1218 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1219 expl_arg_name).replace(
1220 "this", return_type_info.to_hu_conv_name) + ";\n")
1221 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1222 if not takes_self and return_type_info.to_hu_conv_name is not None:
1223 out_java_struct += (
1224 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1226 out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1228 if return_type_info.to_hu_conv_name is not None:
1229 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1230 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1231 out_java_struct += ("\t\treturn ret;\n")
1232 out_java_struct += ("\t}\n\n")
1234 return (out_java, out_c, out_java_struct)
1237 for struct in self.struct_file_suffixes:
1238 with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1239 src.write(self.struct_file_suffixes[struct])