Make variable declaration statements language-specific
[ldk-java] / typescript_strings.py
1 from bindingstypes import ConvInfo
2 from enum import Enum
3
4 def first_to_lower(string: str) -> str:
5     first = string[0]
6     return first.lower() + string[1:]
7
8
9 class Target(Enum):
10     NODEJS = 1,
11     BROWSER = 2
12
13 class Consts:
14     def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
15         self.outdir = outdir
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'],
22         )
23
24         self.wasm_decoding_map = dict(
25             int8_tArray = 'decodeUint8Array'
26         )
27
28         self.wasm_encoding_map = dict(
29             int8_tArray = 'encodeUint8Array',
30         )
31
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});',
35         )
36
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;
45         this.stride = stride;
46     }
47 }
48
49 /*
50 TODO: load WASM file
51 static {
52     System.loadLibrary(\"lightningjni\");
53     init(java.lang.Enum.class, VecOrSliceDef.class);
54     init_class_cache();
55 }
56
57 static native void init(java.lang.Class c, java.lang.Class slicedef);
58 static native void init_class_cache();
59
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();
71 */
72
73 """
74
75         self.bindings_version_file = ""
76
77         self.bindings_footer = ""
78
79         self.util_fn_pfx = ""
80         self.util_fn_sfx = ""
81
82         self.common_base = """
83             export default class CommonBase {
84                 protected ptr: number;
85                 protected ptrs_to: object[] = [];
86                 protected constructor(ptr: number) { this.ptr = ptr; }
87                 public _test_only_get_ptr(): number { return this.ptr; }
88                 protected finalize() {
89                     // TODO: finalize myself
90                 }
91             }
92 """
93
94         self.c_file_pfx = """#include "js-wasm.h"
95 #include <stdatomic.h>
96 #include <lightning.h>
97
98 // These should be provided...somehow...
99 void *memset(void *s, int c, size_t n);
100 void *memcpy(void *dest, const void *src, size_t n);
101 int memcmp(const void *s1, const void *s2, size_t n);
102
103 void __attribute__((noreturn)) abort(void);
104 static inline void assert(bool expression) {
105         if (!expression) { abort(); }
106 }
107 """
108
109         if not DEBUG:
110             self.c_file_pfx = self.c_file_pfx + """
111 void *malloc(size_t size);
112 void free(void *ptr);
113
114 #define MALLOC(a, _) malloc(a)
115 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
116 #define DO_ASSERT(a) (void)(a)
117 #define CHECK(a)
118 #define CHECK_ACCESS(p)
119 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
120 """
121         else:
122             self.c_file_pfx = self.c_file_pfx + """
123 // Always run a, then assert it is true:
124 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
125 // Assert a is true or do nothing
126 #define CHECK(a) DO_ASSERT(a)
127
128 // Running a leak check across all the allocations and frees of the JDK is a mess,
129 // so instead we implement our own naive leak checker here, relying on the -wrap
130 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
131 // and free'd in Rust or C across the generated bindings shared library.
132
133 #define BT_MAX 128
134 typedef struct allocation {
135         struct allocation* next;
136         void* ptr;
137         const char* struct_name;
138 } allocation;
139 static allocation* allocation_ll = NULL;
140
141 void* __real_malloc(size_t len);
142 void* __real_calloc(size_t nmemb, size_t len);
143 static void new_allocation(void* res, const char* struct_name) {
144         allocation* new_alloc = __real_malloc(sizeof(allocation));
145         new_alloc->ptr = res;
146         new_alloc->struct_name = struct_name;
147         new_alloc->next = allocation_ll;
148         allocation_ll = new_alloc;
149 }
150 static void* MALLOC(size_t len, const char* struct_name) {
151         void* res = __real_malloc(len);
152         new_allocation(res, struct_name);
153         return res;
154 }
155 void __real_free(void* ptr);
156 static void alloc_freed(void* ptr) {
157         allocation* p = NULL;
158         allocation* it = allocation_ll;
159         while (it->ptr != ptr) {
160                 p = it; it = it->next;
161                 if (it == NULL) {
162                         //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
163                         return; // addrsan should catch malloc-unknown and print more info than we have
164                 }
165         }
166         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
167         DO_ASSERT(it->ptr == ptr);
168         __real_free(it);
169 }
170 static void FREE(void* ptr) {
171         if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
172         alloc_freed(ptr);
173         __real_free(ptr);
174 }
175
176 static void CHECK_ACCESS(const void* ptr) {
177         allocation* it = allocation_ll;
178         while (it->ptr != ptr) {
179                 it = it->next;
180                 if (it == NULL) {
181                         return; // addrsan should catch malloc-unknown and print more info than we have
182                 }
183         }
184 }
185 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
186         if (v.is_owned && v.inner != NULL) { \\
187                 const void *p = __unmangle_inner_ptr(v.inner); \\
188                 if (p != NULL) { \\
189                         CHECK_ACCESS(p); \\
190                 } \\
191         }
192
193 void* __wrap_malloc(size_t len) {
194         void* res = __real_malloc(len);
195         new_allocation(res, "malloc call");
196         return res;
197 }
198 void* __wrap_calloc(size_t nmemb, size_t len) {
199         void* res = __real_calloc(nmemb, len);
200         new_allocation(res, "calloc call");
201         return res;
202 }
203 void __wrap_free(void* ptr) {
204         if (ptr == NULL) return;
205         alloc_freed(ptr);
206         __real_free(ptr);
207 }
208
209 void* __real_realloc(void* ptr, size_t newlen);
210 void* __wrap_realloc(void* ptr, size_t len) {
211         if (ptr != NULL) alloc_freed(ptr);
212         void* res = __real_realloc(ptr, len);
213         new_allocation(res, "realloc call");
214         return res;
215 }
216 void __wrap_reallocarray(void* ptr, size_t new_sz) {
217         // Rust doesn't seem to use reallocarray currently
218         DO_ASSERT(false);
219 }
220
221 void __attribute__((destructor)) check_leaks() {
222         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
223                 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
224         }
225         DO_ASSERT(allocation_ll == NULL);
226 }
227 """
228         self.c_file_pfx = self.c_file_pfx + """
229 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
230 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
231 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
232 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
233
234 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
235
236 #define DECL_ARR_TYPE(ty, name) \\
237         struct name##array { \\
238                 uint32_t arr_len; \\
239                 ty elems[]; \\
240         }; \\
241         typedef struct name##array * name##Array; \\
242         static inline name##Array init_##name##Array(size_t arr_len) { \\
243                 name##Array arr = (name##Array)MALLOC(arr_len * sizeof(ty) + sizeof(uint32_t), "##name array init"); \\
244                 arr->arr_len = arr_len; \\
245                 return arr; \\
246         }
247
248 DECL_ARR_TYPE(int64_t, int64_t);
249 DECL_ARR_TYPE(int8_t, int8_t);
250 DECL_ARR_TYPE(uint32_t, uint32_t);
251 DECL_ARR_TYPE(void*, ptr);
252 DECL_ARR_TYPE(char, char);
253 typedef charArray jstring;
254
255 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
256         charArray arr = init_charArray(len);
257         memcpy(arr->elems, chars, len);
258         return arr;
259 }
260 static inline LDKStr str_ref_to_owned_c(const jstring str) {
261         char* newchars = MALLOC(str->arr_len + 1, "String chars");
262         memcpy(newchars, str->elems, str->arr_len);
263         newchars[str->arr_len] = 0;
264         LDKStr res = {
265                 .chars = newchars,
266                 .len = str->arr_len,
267                 .chars_is_owned = true
268         };
269         return res;
270 }
271
272 typedef bool jboolean;
273
274 uint32_t __attribute__((visibility("default"))) TS_malloc(uint32_t size) {
275         return (uint32_t)MALLOC(size, "JS-Called malloc");
276 }
277 void __attribute__((visibility("default"))) TS_free(uint32_t ptr) {
278         FREE((void*)ptr);
279 }
280 """
281
282         self.c_version_file = ""
283
284         self.hu_struct_file_prefix = f"""
285 import CommonBase from './CommonBase';
286 import * as bindings from '../bindings.mjs'
287
288 """
289         self.c_fn_ty_pfx = ""
290         self.file_ext = ".mts"
291         self.ptr_c_ty = "uint32_t"
292         self.ptr_native_ty = "number"
293         self.result_c_ty = "uint32_t"
294         self.ptr_arr = "ptrArray"
295         self.is_arr_some_check = ("", " != 0")
296         self.get_native_arr_len_call = ("", "->arr_len")
297
298     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
299         return None
300     def create_native_arr_call(self, arr_len, ty_info):
301         if ty_info.c_ty == "ptrArray":
302             assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
303         return "init_" + ty_info.c_ty + "(" + arr_len + ")"
304     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
305         if ty_info.c_ty == "int8_tArray":
306             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
307         else:
308             assert False
309     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
310         if ty_info.c_ty == "int8_tArray":
311             if copy:
312                 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + ")"
313         if ty_info.c_ty == "ptrArray":
314             return "(void*) " + arr_name + "->elems"
315         else:
316             assert not copy
317             return arr_name + "->elems"
318     def get_native_arr_elem(self, arr_name, idxc, ty_info):
319         assert False # Only called if above is None
320     def get_native_arr_ptr_call(self, ty_info):
321         if ty_info.subty is not None:
322             return "(" + ty_info.subty.c_ty + "*)(", " + 4)"
323         return "(" + ty_info.c_ty + "*)(", " + 4)"
324     def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
325         return None
326     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
327         if ty_info.c_ty == "int8_tArray":
328             return None
329         else:
330             return None
331
332     def str_ref_to_native_call(self, var_name, str_len):
333         return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
334     def str_ref_to_c_call(self, var_name):
335         return "str_ref_to_owned_c(" + var_name + ")"
336
337     def c_fn_name_define_pfx(self, fn_name, have_args):
338         return " __attribute__((visibility(\"default\"))) TS_" + fn_name + "("
339
340     def wasm_import_header(self, target):
341         res = """
342 function freer(f: () => void) { f() }
343 const finalizer = new FinalizationRegistry(freer);
344 const memory = new WebAssembly.Memory({initial: 256});
345
346 const imports: any = {};
347 imports.env = {};
348
349 imports.env.memoryBase = 0;
350 imports.env.memory = memory;
351 imports.env.tableBase = 0;
352 imports.env.table = new WebAssembly.Table({initial: 4, element: 'anyfunc'});
353
354 imports.env["abort"] = function () {
355         console.error("ABORT");
356 };
357 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) {
358         console.log('function called from wasm:', fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
359 };
360 imports.env["js_free_function_ptr"] = function(fn: number) {
361         console.log("function ptr free'd from wasm:", fn);
362 };
363
364 imports.wasi_snapshot_preview1 = {
365         "fd_write" : () => {
366                 console.log("ABORT");
367         },
368         "random_get" : () => {
369                 console.log("RAND GET");
370         },
371         "environ_sizes_get" : () => {
372                 console.log("wasi_snapshot_preview1:environ_sizes_get");
373         },
374         "proc_exit" : () => {
375                 console.log("wasi_snapshot_preview1:proc_exit");
376         },
377         "environ_get" : () => {
378                 console.log("wasi_snapshot_preview1:environ_get");
379         },
380 };
381
382 var wasm = null;
383 let isWasmInitialized: boolean = false;
384 """
385
386         if target == Target.NODEJS:
387             res += """import * as fs from 'fs';
388 export async function initializeWasm(path) {
389         const source = fs.readFileSync(path);
390         const { instance: wasmInstance } = await WebAssembly.instantiate(source, imports);
391         wasm = wasmInstance.exports;
392         isWasmInitialized = true;
393 };
394 """
395         else:
396             res += """
397 export async function initializeWasm(uri) {
398         const stream = fetch(uri);
399         const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);
400         wasm = wasmInstance.exports;
401         isWasmInitialized = true;
402 };
403
404 """
405
406         return res + """
407
408
409 // WASM CODEC
410
411 const nextMultipleOfFour = (value: number) => {
412         return Math.ceil(value / 4) * 4;
413 }
414
415 const encodeUint8Array = (inputArray) => {
416         const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
417         const arrayLengthView = new Uint32Array(memory.buffer, cArrayPointer, 1);
418         arrayLengthView[0] = inputArray.length;
419         const arrayMemoryView = new Uint8Array(memory.buffer, cArrayPointer + 4, inputArray.length);
420         arrayMemoryView.set(inputArray);
421         return cArrayPointer;
422 }
423
424 const encodeUint32Array = (inputArray) => {
425         const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
426         const arrayMemoryView = new Uint32Array(memory.buffer, cArrayPointer, inputArray.length);
427         arrayMemoryView.set(inputArray, 1);
428         arrayMemoryView[0] = inputArray.length;
429         return cArrayPointer;
430 }
431
432 const getArrayLength = (arrayPointer) => {
433         const arraySizeViewer = new Uint32Array(
434                 memory.buffer, // value
435                 arrayPointer, // offset
436                 1 // one int
437         );
438         return arraySizeViewer[0];
439 }
440 const decodeUint8Array = (arrayPointer, free = true) => {
441         const arraySize = getArrayLength(arrayPointer);
442         const actualArrayViewer = new Uint8Array(
443                 memory.buffer, // value
444                 arrayPointer + 4, // offset (ignoring length bytes)
445                 arraySize // uint8 count
446         );
447         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
448         // will free the underlying memory when it becomes unreachable instead of copying here.
449         const actualArray = actualArrayViewer.slice(0, arraySize);
450         if (free) {
451                 wasm.TS_free(arrayPointer);
452         }
453         return actualArray;
454 }
455 const decodeUint32Array = (arrayPointer, free = true) => {
456         const arraySize = getArrayLength(arrayPointer);
457         const actualArrayViewer = new Uint32Array(
458                 memory.buffer, // value
459                 arrayPointer + 4, // offset (ignoring length bytes)
460                 arraySize // uint32 count
461         );
462         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
463         // will free the underlying memory when it becomes unreachable instead of copying here.
464         const actualArray = actualArrayViewer.slice(0, arraySize);
465         if (free) {
466                 wasm.TS_free(arrayPointer);
467         }
468         return actualArray;
469 }
470
471 const encodeString = (string) => {
472         // make malloc count divisible by 4
473         const memoryNeed = nextMultipleOfFour(string.length + 1);
474         const stringPointer = wasm.TS_malloc(memoryNeed);
475         const stringMemoryView = new Uint8Array(
476                 memory.buffer, // value
477                 stringPointer, // offset
478                 string.length + 1 // length
479         );
480         for (let i = 0; i < string.length; i++) {
481                 stringMemoryView[i] = string.charCodeAt(i);
482         }
483         stringMemoryView[string.length] = 0;
484         return stringPointer;
485 }
486
487 const decodeString = (stringPointer, free = true) => {
488         const memoryView = new Uint8Array(memory.buffer, stringPointer);
489         let cursor = 0;
490         let result = '';
491
492         while (memoryView[cursor] !== 0) {
493                 result += String.fromCharCode(memoryView[cursor]);
494                 cursor++;
495         }
496
497         if (free) {
498                 wasm.wasm_free(stringPointer);
499         }
500
501         return result;
502 };
503 """
504
505     def init_str(self):
506         return ""
507
508     def var_decl_statement(self, ty_string, var_name, statement):
509         return "const " + var_name + ": " + ty_string + " = " + statement
510
511     def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
512         out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
513         out_c = out_c + "\tswitch (ord) {\n"
514         ord_v = 0
515
516         out_typescript_enum_fields = ""
517
518         for var, var_docs in variants:
519             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
520             ord_v = ord_v + 1
521             if var_docs is not None:
522                 out_typescript_enum_fields += f"/**\n * {var_docs}\n */\n"
523             out_typescript_enum_fields += f"{var},\n\t\t\t\t"
524         out_c = out_c + "\t}\n"
525         out_c = out_c + "\tabort();\n"
526         out_c = out_c + "}\n"
527
528         out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
529         out_c = out_c + "\tswitch (val) {\n"
530         ord_v = 0
531         for var, _ in variants:
532             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
533             ord_v = ord_v + 1
534         out_c = out_c + "\t\tdefault: abort();\n"
535         out_c = out_c + "\t}\n"
536         out_c = out_c + "}\n"
537
538         out_typescript = f"""
539             export enum {struct_name} {{
540                 {out_typescript_enum_fields}
541             }}
542 """
543         out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
544         return (out_c, out_typescript_enum, out_typescript)
545
546     def c_unitary_enum_to_native_call(self, ty_info):
547         return (ty_info.rust_obj + "_to_js(", ")")
548     def native_unitary_enum_to_c_call(self, ty_info):
549         return (ty_info.rust_obj + "_from_js(", ")")
550
551     def c_complex_enum_pass_ty(self, struct_name):
552         return "uint32_t"
553
554     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
555         ret = "0 /* " + struct_name + " - " + variant + " */"
556         for param in c_params:
557             ret = ret + "; (void) " + param
558         return ret
559
560     def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
561         out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
562
563         constructor_arguments = ""
564         super_instantiator = ""
565         pointer_to_adder = ""
566         impl_constructor_arguments = ""
567         for var in flattened_field_var_conversions:
568             if isinstance(var, ConvInfo):
569                 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
570                 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
571                 if var.from_hu_conv is not None:
572                     super_instantiator += ", " + var.from_hu_conv[0]
573                     if var.from_hu_conv[1] != "":
574                         pointer_to_adder += var.from_hu_conv[1] + ";\n"
575                 else:
576                     super_instantiator += ", " + first_to_lower(var.arg_name)
577             else:
578                 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
579                 super_instantiator += ", " + first_to_lower(var[1])
580                 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
581                 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
582
583         # BUILD INTERFACE METHODS
584         out_java_interface = ""
585         out_interface_implementation_overrides = ""
586         java_methods = []
587         for fn_line in field_function_lines:
588             java_method_descriptor = ""
589             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
590                 out_java_interface += fn_line.fn_name + "("
591                 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
592
593                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
594                     if idx >= 1:
595                         out_java_interface += ", "
596                         out_interface_implementation_overrides += ", "
597                     out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
598                     out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
599                     java_method_descriptor += arg_conv_info.java_fn_ty_arg
600                 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
601                 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
602                 java_methods.append((fn_line.fn_name, java_method_descriptor))
603
604                 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
605
606                 interface_method_override_inset = "\t\t\t\t\t\t"
607                 interface_implementation_inset = "\t\t\t\t\t\t\t"
608                 for arg_info in fn_line.args_ty:
609                     if arg_info.to_hu_conv is not None:
610                         out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
611
612                 if fn_line.ret_ty_info.java_ty != "void":
613                     out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
614                 else:
615                     out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
616
617                 for idx, arg_info in enumerate(fn_line.args_ty):
618                     if idx != 0:
619                         out_interface_implementation_overrides += ", "
620                     if arg_info.to_hu_conv_name is not None:
621                         out_interface_implementation_overrides += arg_info.to_hu_conv_name
622                     else:
623                         out_interface_implementation_overrides += arg_info.arg_name
624
625                 out_interface_implementation_overrides += ");\n"
626                 if fn_line.ret_ty_info.java_ty != "void":
627                     if fn_line.ret_ty_info.from_hu_conv is not None:
628                         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"
629                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
630                             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"
631                         #if fn_line.ret_ty_info.rust_obj in result_types:
632                         # XXX: We need to handle this in conversion logic so that its cross-language!
633                         # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
634                         #    out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
635                         out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
636                     else:
637                         out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
638                 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
639
640         trait_constructor_arguments = ""
641         for var in field_var_conversions:
642             if isinstance(var, ConvInfo):
643                 trait_constructor_arguments += ", " + var.arg_name
644             else:
645                 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl"
646                 for suparg in var[2]:
647                     if isinstance(suparg, ConvInfo):
648                         trait_constructor_arguments += ", " + suparg.arg_name
649                     else:
650                         trait_constructor_arguments += ", " + suparg[1]
651                 trait_constructor_arguments += ").bindings_instance"
652                 for suparg in var[2]:
653                     if isinstance(suparg, ConvInfo):
654                         trait_constructor_arguments += ", " + suparg.arg_name
655                     else:
656                         trait_constructor_arguments += ", " + suparg[1]
657
658         out_typescript_human = f"""
659             {self.hu_struct_file_prefix}
660
661             export class {struct_name.replace("LDK","")} extends CommonBase {{
662
663                 bindings_instance?: bindings.{struct_name};
664
665                 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
666                     if (Number.isFinite(ptr)) {{
667                                         super(ptr);
668                                         this.bindings_instance = null;
669                                     }} else {{
670                                         // TODO: private constructor instantiation
671                                         super(bindings.{struct_name}_new(arg{super_instantiator}));
672                                         this.ptrs_to.push(arg);
673                                         {pointer_to_adder}
674                                     }}
675                 }}
676
677                 protected finalize() {{
678                     if (this.ptr != 0) {{
679                         bindings.{struct_name.replace("LDK","")}_free(this.ptr);
680                     }}
681                     super.finalize();
682                 }}
683
684                 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
685                     const impl_holder: {struct_name}Holder = new {struct_name}Holder();
686                     let structImplementation = <bindings.{struct_name}>{{
687                         // todo: in-line interface filling
688                         {out_interface_implementation_overrides}
689                     }};
690                     impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
691                 }}
692             }}
693
694             export interface {struct_name.replace("LDK", "")}Interface {{
695                 {out_java_interface}
696             }}
697
698             class {struct_name}Holder {{
699                 held: {struct_name.replace("LDK", "")};
700             }}
701 """
702
703         out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
704         java_meths = []
705         for fn_line in field_function_lines:
706             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
707                 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
708
709                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
710                     if idx >= 1:
711                         out_typescript_bindings = out_typescript_bindings + ", "
712                     out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
713
714                 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
715
716         out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
717
718         out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
719         for var in flattened_field_var_conversions:
720             if isinstance(var, ConvInfo):
721                 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
722             else:
723                 out_typescript_bindings += f", {var[1]}: {var[0]}"
724
725         out_typescript_bindings += f"""): number {{
726             throw new Error('unimplemented'); // TODO: bind to WASM
727         }}
728 """
729
730         out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
731
732         # Now that we've written out our java code (and created java_meths), generate C
733         out_c = "typedef struct " + struct_name + "_JCalls {\n"
734         out_c = out_c + "\tatomic_size_t refcnt;\n"
735         for var in flattened_field_var_conversions:
736             if isinstance(var, ConvInfo):
737                 # We're a regular ol' field
738                 pass
739             else:
740                 # We're a supertrait
741                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
742         for fn in field_function_lines:
743             if fn.fn_name != "free" and fn.fn_name != "cloned":
744                 out_c = out_c + "\tuint32_t " + fn.fn_name + "_meth;\n"
745         out_c = out_c + "} " + struct_name + "_JCalls;\n"
746
747         for fn_line in field_function_lines:
748             if fn_line.fn_name == "free":
749                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
750                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
751                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
752                 for fn in field_function_lines:
753                     if fn.fn_name != "free" and fn.fn_name != "cloned":
754                         out_c = out_c + "\t\tjs_free_function_ptr(j_calls->" + fn.fn_name + "_meth);\n"
755                 out_c = out_c + "\t\tFREE(j_calls);\n"
756                 out_c = out_c + "\t}\n}\n"
757
758         for idx, fn_line in enumerate(field_function_lines):
759             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
760                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
761                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
762                 if fn_line.self_is_const:
763                     out_c = out_c + "const void* this_arg"
764                 else:
765                     out_c = out_c + "void* this_arg"
766
767                 for idx, arg in enumerate(fn_line.args_ty):
768                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
769
770                 out_c = out_c + ") {\n"
771                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
772
773                 for arg_info in fn_line.args_ty:
774                     if arg_info.ret_conv is not None:
775                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
776                         out_c = out_c + arg_info.arg_name
777                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
778
779                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
780                     out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
781                     out_c += "js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
782                 elif fn_line.ret_ty_info.java_ty == "void":
783                     out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
784                 elif fn_line.ret_ty_info.java_ty == "String":
785                     out_c = out_c + "\tjstring ret = (jstring)js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
786                 elif not fn_line.ret_ty_info.passed_as_ptr:
787                     out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
788                 else:
789                     out_c = out_c + "\tuint32_t ret = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->" + fn_line.fn_name + "_meth"
790
791                 for idx, arg_info in enumerate(fn_line.args_ty):
792                     if arg_info.ret_conv is not None:
793                         out_c = out_c + ", (uint32_t)" + arg_info.ret_conv_name
794                     else:
795                         out_c = out_c + ", (uint32_t)" + arg_info.arg_name
796                 out_c = out_c + ");\n"
797                 if fn_line.ret_ty_info.arg_conv is not None:
798                     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"
799
800                 out_c = out_c + "}\n"
801
802         # Write out a clone function whether we need one or not, as we use them in moving to rust
803         out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
804         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
805         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
806         for var in field_var_conversions:
807             if not isinstance(var, ConvInfo):
808                 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
809         out_c = out_c + "}\n"
810
811         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (/*TODO: JS Object Reference */void* o"
812         for var in flattened_field_var_conversions:
813             if isinstance(var, ConvInfo):
814                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
815             else:
816                 out_c = out_c + ", /*TODO: JS Object Reference */void* " + var[1]
817         out_c = out_c + ") {\n"
818
819         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
820         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
821         out_c = out_c + "\t//TODO: Assign calls->o from o\n"
822
823         for (fn_name, java_meth_descr) in java_meths:
824             if fn_name != "free" and fn_name != "cloned":
825                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
826                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
827
828         for var in flattened_field_var_conversions:
829             if isinstance(var, ConvInfo) and var.arg_conv is not None:
830                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
831         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
832         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
833         for fn_line in field_function_lines:
834             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
835                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
836             elif fn_line.fn_name == "free":
837                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
838             else:
839                 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
840         for var in field_var_conversions:
841             if isinstance(var, ConvInfo):
842                 if var.arg_conv_name is not None:
843                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
844                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
845                 else:
846                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
847                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
848             else:
849                 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
850                 for suparg in var[2]:
851                     if isinstance(suparg, ConvInfo):
852                         out_c += ", " + suparg.arg_name
853                     else:
854                         out_c += ", " + suparg[1]
855                 out_c += "),\n"
856         out_c = out_c + "\t};\n"
857         for var in flattened_field_var_conversions:
858             if not isinstance(var, ConvInfo):
859                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
860         out_c = out_c + "\treturn ret;\n"
861         out_c = out_c + "}\n"
862
863         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"
864         for var in flattened_field_var_conversions:
865             if isinstance(var, ConvInfo):
866                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
867             else:
868                 out_c = out_c + ", /*TODO: JS Object Reference */ void* " + var[1]
869         out_c = out_c + ") {\n"
870         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
871         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
872         for var in flattened_field_var_conversions:
873             if isinstance(var, ConvInfo):
874                 out_c = out_c + ", " + var.arg_name
875             else:
876                 out_c = out_c + ", " + var[1]
877         out_c = out_c + ");\n"
878         out_c = out_c + "\treturn (long)res_ptr;\n"
879         out_c = out_c + "}\n"
880
881         return (out_typescript_bindings, out_typescript_human, out_c)
882
883     def trait_struct_inc_refcnt(self, ty_info):
884         return ""
885
886     def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
887         bindings_type = struct_name.replace("LDK", "")
888         java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
889
890         out_java_enum = ""
891         out_java = ""
892         out_c = ""
893
894         out_java_enum += (self.hu_struct_file_prefix)
895
896         java_hu_class = ""
897         java_hu_class += "export default class " + java_hu_type + " extends CommonBase {\n"
898         java_hu_class += "\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n"
899         java_hu_class += "\tprotected finalize() {\n"
900         java_hu_class += "\t\tsuper.finalize();\n"
901         java_hu_class += "\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n"
902         java_hu_class += "\t}\n"
903         java_hu_class += "\t/* @internal */\n"
904         java_hu_class += f"\tpublic static constr_from_ptr(ptr: number): {java_hu_type} {{\n"
905         java_hu_class += f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n"
906         java_hu_subclasses = ""
907
908         out_java += "\texport class " + struct_name + " {\n"
909         out_java += "\t\tprotected constructor() {}\n"
910         java_subclasses = ""
911         for var in variant_list:
912             java_subclasses += "\texport class " + struct_name + "_" + var.var_name + " extends " + struct_name + " {\n"
913             java_hu_subclasses = java_hu_subclasses + "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
914             java_hu_class += "\t\tif (raw_val instanceof bindings." + struct_name + "_" + var.var_name + ") {\n"
915             java_hu_class += "\t\t\treturn new " + java_hu_type + "_" + var.var_name + "(ptr, raw_val);\n"
916             init_meth_params = ""
917             hu_conv_body = ""
918             for idx, (field_ty, field_docs) in enumerate(var.fields):
919                 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
920                 if field_ty.to_hu_conv is not None:
921                     hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
922                     hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
923                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
924                 else:
925                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
926                 if idx > 0:
927                     init_meth_params += ", "
928                 init_meth_params += "public " + field_ty.arg_name + ": " + field_ty.java_ty
929             java_subclasses += "\t\tconstructor(" + init_meth_params + ") { super(); }\n"
930             java_subclasses += "\t}\n"
931             java_hu_class += "\t\t}\n"
932             java_hu_subclasses += "\t/* @internal */\n"
933             java_hu_subclasses += "\tpublic constructor(ptr: number, obj: bindings." + struct_name + "_" + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
934             java_hu_subclasses = java_hu_subclasses + hu_conv_body
935             java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
936         out_java += ("\t}\n")
937         out_java += java_subclasses
938         java_hu_class += "\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n"
939         out_java += self.fn_call_body(struct_name + "_ref_from_ptr", "uint32_t", "number", "ptr: number", "ptr")
940
941         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")
942         out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n")
943         out_c += ("\tswitch(obj->tag) {\n")
944         for var in variant_list:
945             out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
946             c_params = []
947             for idx, (field_map, _) in enumerate(var.fields):
948                 if field_map.ret_conv is not None:
949                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
950                     if var.tuple_variant:
951                         out_c += "obj->" + camel_to_snake(var.var_name)
952                     else:
953                         out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
954                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
955                     c_params.append(field_map.ret_conv_name)
956                 else:
957                     if var.tuple_variant:
958                         c_params.append("obj->" + camel_to_snake(var.var_name))
959                     else:
960                         c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
961             out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
962             out_c += ("\t\t}\n")
963         out_c += ("\t\tdefault: abort();\n")
964         out_c += ("\t}\n}\n")
965         out_java_enum += java_hu_class
966         self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
967         return (out_java, out_java_enum, out_c)
968
969     def map_opaque_struct(self, struct_name, struct_doc_comment):
970         implementations = ""
971         method_header = ""
972         if struct_name.startswith("LDKLocked"):
973             implementations += "implements AutoCloseable "
974             method_header = """
975                 public close() {
976 """
977         else:
978             method_header = """
979                 protected finalize() {
980                     super.finalize();
981 """
982
983         out_opaque_struct_human = f"""
984             {self.hu_struct_file_prefix}
985
986             export default class {struct_name.replace("LDK","")} extends CommonBase {implementations}{{
987                 /* @internal */
988                 public constructor(_dummy: object, ptr: number) {{
989                     super(ptr);
990                 }}
991
992                 {method_header}
993                     if (this.ptr != 0) {{
994                         bindings.{struct_name.replace("LDK","")}_free(this.ptr);
995                     }}
996                 }}
997 """
998         return out_opaque_struct_human
999
1000     def map_tuple(self, struct_name):
1001         return self.map_opaque_struct(struct_name, "A Tuple")
1002
1003     def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1004         has_return_value = return_c_ty != 'void'
1005         needs_decoding = return_c_ty in self.wasm_decoding_map
1006         return_statement = 'return nativeResponseValue;'
1007         if not has_return_value:
1008             return_statement = '// debug statements here'
1009         elif needs_decoding:
1010             converter = self.wasm_decoding_map[return_c_ty]
1011             return_statement = f"return {converter}(nativeResponseValue);"
1012
1013         return f"""\texport function {method_name}({method_argument_string}): {return_java_ty} {{
1014                 if(!isWasmInitialized) {{
1015                         throw new Error("initializeWasm() must be awaited first!");
1016                 }}
1017                 const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1018                 {return_statement}
1019         }}
1020 """
1021     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):
1022         out_java = ""
1023         out_c = ""
1024         out_java_struct = None
1025
1026         out_java += ("\t")
1027         out_c += (self.c_fn_ty_pfx)
1028         out_c += (return_type_info.c_ty)
1029         out_java += (return_type_info.java_ty)
1030         if return_type_info.ret_conv is not None:
1031             ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1032         out_java += (" " + method_name + "(")
1033         out_c += (" "  + self.c_fn_name_define_pfx(method_name, True))
1034
1035         method_argument_string = ""
1036         native_call_argument_string = ""
1037         for idx, arg_conv_info in enumerate(argument_types):
1038             if idx != 0:
1039                 method_argument_string += (", ")
1040                 native_call_argument_string += ', '
1041                 out_c += (", ")
1042             if arg_conv_info.c_ty != "void":
1043                 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1044                 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
1045                 native_argument = arg_conv_info.arg_name
1046                 if needs_encoding:
1047                     converter = self.wasm_encoding_map[arg_conv_info.c_ty]
1048                     native_argument = f"{converter}({arg_conv_info.arg_name})"
1049                 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1050                 native_call_argument_string += native_argument
1051         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)
1052
1053         out_java_struct = ""
1054         if not args_known:
1055             out_java_struct += ("\t// Skipped " + method_name + "\n")
1056         else:
1057             if not takes_self:
1058                 out_java_struct += (
1059                         "\tpublic static constructor_" + meth_n + "(")
1060             else:
1061                 out_java_struct += ("\tpublic " + meth_n + "(")
1062             for idx, arg in enumerate(argument_types):
1063                 if idx != 0:
1064                     if not takes_self or idx > 1:
1065                         out_java_struct += (", ")
1066                 elif takes_self:
1067                     continue
1068                 if arg.java_ty != "void":
1069                     if arg.arg_name in default_constructor_args:
1070                         for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1071                             if explode_idx != 0:
1072                                 out_java_struct += (", ")
1073                             out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1074                     else:
1075                         out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1076
1077         out_c += (") {\n")
1078         if out_java_struct is not None:
1079             out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1080         for info in argument_types:
1081             if info.arg_conv is not None:
1082                 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1083         if return_type_info.ret_conv is not None:
1084             out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1085         elif return_type_info.c_ty != "void":
1086             out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1087         else:
1088             out_c += ("\t")
1089         if c_call_string is None:
1090             out_c += (method_name + "(")
1091         else:
1092             out_c += (c_call_string)
1093         for idx, info in enumerate(argument_types):
1094             if info.arg_conv_name is not None:
1095                 if idx != 0:
1096                     out_c += (", ")
1097                 elif c_call_string is not None:
1098                     continue
1099                 out_c += (info.arg_conv_name)
1100         out_c += (")")
1101         if return_type_info.ret_conv is not None:
1102             out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1103         else:
1104             out_c += (";")
1105         for info in argument_types:
1106             if info.arg_conv_cleanup is not None:
1107                 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1108         if return_type_info.ret_conv is not None:
1109             out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1110         elif return_type_info.c_ty != "void":
1111             out_c += ("\n\treturn ret_val;")
1112         out_c += ("\n}\n\n")
1113
1114         if args_known:
1115             out_java_struct += ("\t\t")
1116             if return_type_info.java_ty != "void":
1117                 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1118             out_java_struct += ("bindings." + method_name + "(")
1119             for idx, info in enumerate(argument_types):
1120                 if idx != 0:
1121                     out_java_struct += (", ")
1122                 if idx == 0 and takes_self:
1123                     out_java_struct += ("this.ptr")
1124                 elif info.arg_name in default_constructor_args:
1125                     out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1126                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1127                         if explode_idx != 0:
1128                             out_java_struct += (", ")
1129                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1130                         if explode_arg.from_hu_conv is not None:
1131                             out_java_struct += (
1132                                 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1133                         else:
1134                             out_java_struct += (expl_arg_name)
1135                     out_java_struct += (")")
1136                 elif info.from_hu_conv is not None:
1137                     out_java_struct += (info.from_hu_conv[0])
1138                 else:
1139                     out_java_struct += (info.arg_name)
1140             out_java_struct += (");\n")
1141             if return_type_info.to_hu_conv is not None:
1142                 if not takes_self:
1143                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1144                                                                                                              return_type_info.to_hu_conv_name) + "\n")
1145                 else:
1146                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1147
1148             for idx, info in enumerate(argument_types):
1149                 if idx == 0 and takes_self:
1150                     pass
1151                 elif info.arg_name in default_constructor_args:
1152                     for explode_arg in default_constructor_args[info.arg_name]:
1153                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1154                         if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1155                             out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1156                                                                                              expl_arg_name).replace(
1157                                 "this", return_type_info.to_hu_conv_name) + ";\n")
1158                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1159                     if not takes_self and return_type_info.to_hu_conv_name is not None:
1160                         out_java_struct += (
1161                                 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1162                     else:
1163                         out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1164
1165             if return_type_info.to_hu_conv_name is not None:
1166                 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1167             elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1168                 out_java_struct += ("\t\treturn ret;\n")
1169             out_java_struct += ("\t}\n\n")
1170
1171         return (out_java, out_c, out_java_struct)
1172
1173     def cleanup(self):
1174         for struct in self.struct_file_suffixes:
1175             with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1176                 src.write(self.struct_file_suffixes[struct])