merge Matt's array codec mechanism
[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, **kwargs):
15
16         self.c_type_map = dict(
17             uint8_t = ['number', 'Uint8Array'],
18             uint16_t = ['number', 'Uint16Array'],
19             uint32_t = ['number', 'Uint32Array'],
20             uint64_t = ['number'],
21         )
22
23         self.wasm_decoding_map = dict(
24             int8_tArray = 'decodeArray'
25         )
26
27         self.wasm_encoding_map = dict(
28             int8_tArray = 'encodeArray',
29         )
30
31         self.to_hu_conv_templates = dict(
32             ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
33             default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
34         )
35
36         self.bindings_header = self.wasm_import_header(target) + """
37 export class VecOrSliceDef {
38     public dataptr: number;
39     public datalen: number;
40     public stride: number;
41     public constructor(dataptr: number, datalen: number, stride: number) {
42         this.dataptr = dataptr;
43         this.datalen = datalen;
44         this.stride = stride;
45     }
46 }
47
48 /*
49 TODO: load WASM file
50 static {
51     System.loadLibrary(\"lightningjni\");
52     init(java.lang.Enum.class, VecOrSliceDef.class);
53     init_class_cache();
54 }
55
56 static native void init(java.lang.Class c, java.lang.Class slicedef);
57 static native void init_class_cache();
58
59 public static native boolean deref_bool(long ptr);
60 public static native long deref_long(long ptr);
61 public static native void free_heap_ptr(long ptr);
62 public static native byte[] read_bytes(long ptr, long len);
63 public static native byte[] get_u8_slice_bytes(long slice_ptr);
64 public static native long bytes_to_u8_vec(byte[] bytes);
65 public static native long new_txpointer_copy_data(byte[] txdata);
66 public static native void txpointer_free(long ptr);
67 public static native byte[] txpointer_get_buffer(long ptr);
68 public static native long vec_slice_len(long vec);
69 public static native long new_empty_slice_vec();
70 */
71
72 """
73
74         self.bindings_footer = """
75         export async function initializeWasm(allowDoubleInitialization: boolean = false): Promise<void> {
76             if(isWasmInitialized && !allowDoubleInitialization) {
77                 return;
78             }
79             const wasmInstance = await WebAssembly.instantiate(wasmModule, imports)
80             wasm = wasmInstance.exports;
81             isWasmInitialized = true;
82         }
83         """
84
85         self.common_base = """
86             export default class CommonBase {
87                 ptr: number;
88                 ptrs_to: object[] = []; // new LinkedList(); TODO: build linked list implementation
89                 protected constructor(ptr: number) { this.ptr = ptr; }
90                 public _test_only_get_ptr(): number { return this.ptr; }
91                 protected finalize() {
92                     // TODO: finalize myself
93                 }
94             }
95 """
96
97         self.c_file_pfx = """#include <rust_types.h>
98 #include "js-wasm.h"
99 #include <stdatomic.h>
100 #include <lightning.h>
101
102 // These should be provided...somehow...
103 void *memset(void *s, int c, size_t n);
104 void *memcpy(void *dest, const void *src, size_t n);
105 int memcmp(const void *s1, const void *s2, size_t n);
106
107 void __attribute__((noreturn)) abort(void);
108 void assert(bool expression);
109 """
110
111         if not DEBUG:
112             self.c_file_pfx = self.c_file_pfx + """
113 void *malloc(size_t size);
114 void free(void *ptr);
115
116 #define MALLOC(a, _) malloc(a)
117 #define FREE(p) if ((long)(p) > 1024) { free(p); }
118 #define DO_ASSERT(a) (void)(a)
119 #define CHECK(a)
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 ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
172         alloc_freed(ptr);
173         __real_free(ptr);
174 }
175
176 void* __wrap_malloc(size_t len) {
177         void* res = __real_malloc(len);
178         new_allocation(res, "malloc call");
179         return res;
180 }
181 void* __wrap_calloc(size_t nmemb, size_t len) {
182         void* res = __real_calloc(nmemb, len);
183         new_allocation(res, "calloc call");
184         return res;
185 }
186 void __wrap_free(void* ptr) {
187         if (ptr == NULL) return;
188         alloc_freed(ptr);
189         __real_free(ptr);
190 }
191
192 void* __real_realloc(void* ptr, size_t newlen);
193 void* __wrap_realloc(void* ptr, size_t len) {
194         if (ptr != NULL) alloc_freed(ptr);
195         void* res = __real_realloc(ptr, len);
196         new_allocation(res, "realloc call");
197         return res;
198 }
199 void __wrap_reallocarray(void* ptr, size_t new_sz) {
200         // Rust doesn't seem to use reallocarray currently
201         DO_ASSERT(false);
202 }
203
204 void __attribute__((destructor)) check_leaks() {
205         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
206                 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
207         }
208         DO_ASSERT(allocation_ll == NULL);
209 }
210 """
211         self.c_file_pfx = self.c_file_pfx + """
212 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
213 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
214 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
215 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
216
217 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
218
219 typedef struct int64_tArray { uint32_t *len; /* len + 1 is data */ } int64_tArray;
220 typedef struct uint32_tArray { uint32_t *len; /* len + 1 is data */ } uint32_tArray;
221 typedef struct ptrArray { uint32_t *len; /* len + 1 is data */ } ptrArray;
222 typedef struct int8_tArray { uint32_t *len; /* len + 1 is data */ } int8_tArray;
223 typedef struct jstring {} jstring;
224
225 jstring conv_owned_string(const char* _src) { jstring a; return a; }
226
227 typedef bool jboolean;
228
229 """
230
231         self.hu_struct_file_prefix = f"""
232 import CommonBase from './CommonBase';
233 import * as bindings from '../bindings' // TODO: figure out location
234
235 """
236         self.c_fn_ty_pfx = ""
237         self.c_fn_name_pfx = ""
238         self.c_fn_args_pfx = "void* ctx_TODO"
239         self.file_ext = ".ts"
240         self.ptr_c_ty = "uint32_t"
241         self.ptr_native_ty = "uint32_t"
242         self.result_c_ty = "uint32_t"
243         self.owned_str_to_c_call = ("conv_owned_string(", ")")
244         self.ptr_arr = "ptrArray"
245         self.get_native_arr_len_call = ("*", ".len")
246
247     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
248         return None
249     def create_native_arr_call(self, arr_len, ty_info):
250         if ty_info.c_ty == "int8_tArray":
251             return "{ .len = MALLOC(" + arr_len + " + sizeof(uint32_t), \"Native " + ty_info.c_ty + " Bytes\") }"
252         elif ty_info.c_ty == "int64_tArray":
253             return "{ .len = MALLOC(" + arr_len + " * sizeof(int64_t) + sizeof(uint32_t), \"Native " + ty_info.c_ty + " Bytes\") }"
254         elif ty_info.c_ty == "uint32_tArray":
255             return "{ .len = MALLOC(" + arr_len + " * sizeof(int32_t) + sizeof(uint32_t), \"Native " + ty_info.c_ty + " Bytes\") }"
256         elif ty_info.c_ty == "ptrArray":
257             assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
258             return "{ .len = MALLOC(" + arr_len + " * sizeof(int32_t) + sizeof(uint32_t), \"Native Object Bytes\") }"
259         else:
260             print("Need to create arr!", ty_info.c_ty)
261             return ty_info.c_ty
262     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
263         if ty_info.c_ty == "int8_tArray":
264             return ("memcpy(" + arr_name + ".len + 1, ", ", " + arr_len + ")")
265         else:
266             assert False
267     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
268         if ty_info.c_ty == "int8_tArray":
269             if copy:
270                 return "memcpy(" + dest_name + ", " + arr_name + ".len + 1, " + arr_len + ")"
271             else:
272                 return "(int8_t*)(" + arr_name + ".len + 1)"
273         else:
274             return "(" + ty_info.subty.c_ty + "*)(" + arr_name + ".len + 1)"
275     def get_native_arr_elem(self, arr_name, idxc, ty_info):
276         assert False # Only called if above is None
277     def get_native_arr_ptr_call(self, ty_info):
278         if ty_info.subty is not None:
279             return "(" + ty_info.subty.c_ty + "*)(", ".len + 1)"
280         return "(" + ty_info.c_ty + "*)(", ".len + 1)"
281     def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
282         return None
283     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
284         if ty_info.c_ty == "int8_tArray":
285             return None
286         else:
287             return None
288
289
290     def wasm_import_header(self, target):
291         if target == Target.NODEJS:
292             return """
293             
294 import * as fs from 'fs';
295 const source = fs.readFileSync('./ldk.wasm');
296
297 const memory = new WebAssembly.Memory({initial: 256});
298 const wasmModule = new WebAssembly.Module(source);
299
300 const imports: any = {};
301 imports.env = {};
302
303 imports.env.memoryBase = 0;
304 imports.env.memory = memory;
305 imports.env.tableBase = 0;
306 imports.env.table = new WebAssembly.Table({initial: 4, element: 'anyfunc'});
307
308 imports.env["abort"] = function () {
309     console.error("ABORT");
310 };
311
312 let wasm = null;
313 let isWasmInitialized: boolean = false;
314
315
316 // WASM CODEC
317
318 const nextMultipleOfFour = (value: number) => {
319     return Math.ceil(value / 4) * 4;
320 }
321
322 const encodeArray = (inputArray) => {
323         const cArrayPointer = wasm.wasm_malloc((inputArray.length + 1) * 4);
324         const arrayMemoryView = new Uint32Array(memory.buffer, cArrayPointer + 4, inputArray.length);
325         arrayMemoryView.set(inputArray, 1);
326     arrayMemoryView[0] = inputArray.length;
327         return cArrayPointer;
328 }
329
330 const getArrayLength = (arrayPointer) => {
331         const arraySizeViewer = new Uint32Array(
332                 memory.buffer, // value
333                 arrayPointer, // offset
334                 1 // one int
335         );
336         return arraySizeViewer[0];
337 }
338 const decodeUint8Array = (arrayPointer, free = true) => {
339         const arraySize = getArrayLength(arrayPointer);
340         const actualArrayViewer = new Uint8Array(
341                 memory.buffer, // value
342                 arrayPointer + 4, // offset (ignoring length bytes)
343                 arraySize // uint8 count
344         );
345         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
346         // will free the underlying memory when it becomes unreachable instead of copying here.
347         const actualArray = actualArrayViewer.slice(0, arraySize);
348         if (free) {
349                 wasm.free(arrayPointer);
350         }
351         return actualArray;
352 }
353 const decodeUint32Array = (arrayPointer, free = true) => {
354         const arraySize = getArrayLength(arrayPointer);
355         const actualArrayViewer = new Uint32Array(
356                 memory.buffer, // value
357                 arrayPointer + 4, // offset (ignoring length bytes)
358                 arraySize // uint32 count
359         );
360         // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
361         // will free the underlying memory when it becomes unreachable instead of copying here.
362         const actualArray = actualArrayViewer.slice(0, arraySize);
363         if (free) {
364                 wasm.free(arrayPointer);
365         }
366         return actualArray;
367 }
368
369 const encodeString = (string) => {
370     // make malloc count divisible by 4
371     const memoryNeed = nextMultipleOfFour(string.length + 1);
372     const stringPointer = wasm.wasm_malloc(memoryNeed);
373     const stringMemoryView = new Uint8Array(
374         memory.buffer, // value
375         stringPointer, // offset
376         string.length + 1 // length
377     );
378     for (let i = 0; i < string.length; i++) {
379         stringMemoryView[i] = string.charCodeAt(i);
380     }
381     stringMemoryView[string.length] = 0;
382     return stringPointer;
383 }
384
385 const decodeString = (stringPointer, free = true) => {
386     const memoryView = new Uint8Array(memory.buffer, stringPointer);
387     let cursor = 0;
388     let result = '';
389
390     while (memoryView[cursor] !== 0) {
391         result += String.fromCharCode(memoryView[cursor]);
392         cursor++;
393     }
394
395     if (free) {
396         wasm.wasm_free(stringPointer);
397     }
398
399     return result;
400 };
401
402
403             """
404         return ''
405
406     def init_str(self):
407         return ""
408
409     def native_c_unitary_enum_map(self, struct_name, variants):
410         out_c = "static inline " + struct_name + " " + struct_name + "_from_js(int32_t ord) {\n"
411         out_c = out_c + "\tswitch (ord) {\n"
412         ord_v = 0
413
414         out_typescript_enum_fields = ""
415
416         for var in variants:
417             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
418             ord_v = ord_v + 1
419             out_typescript_enum_fields += f"{var},\n\t\t\t\t"
420         out_c = out_c + "\t}\n"
421         out_c = out_c + "\tabort();\n"
422         out_c = out_c + "}\n"
423
424         out_c = out_c + "static inline int32_t " + struct_name + "_to_js(" + struct_name + " val) {\n"
425         out_c = out_c + "\tswitch (val) {\n"
426         ord_v = 0
427         for var in variants:
428             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
429             ord_v = ord_v + 1
430         out_c = out_c + "\t\tdefault: abort();\n"
431         out_c = out_c + "\t}\n"
432         out_c = out_c + "}\n"
433
434         out_typescript_enum = f"""
435             export enum {struct_name} {{
436                 {out_typescript_enum_fields}
437             }}
438 """
439
440         return (out_c, out_typescript_enum, "")
441
442     def c_unitary_enum_to_native_call(self, ty_info):
443         return (ty_info.rust_obj + "_to_js(", ")")
444     def native_unitary_enum_to_c_call(self, ty_info):
445         return (ty_info.rust_obj + "_from_js(", ")")
446
447     def c_complex_enum_pass_ty(self, struct_name):
448         return "uint32_t"
449
450     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
451         ret = "0 /* " + struct_name + " - " + variant + " */"
452         for param in c_params:
453             ret = ret + "; (void) " + param
454         return ret
455
456     def native_c_map_trait(self, struct_name, field_var_conversions, field_function_lines):
457         out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
458
459         constructor_arguments = ""
460         super_instantiator = ""
461         pointer_to_adder = ""
462         impl_constructor_arguments = ""
463         for var in field_var_conversions:
464             if isinstance(var, ConvInfo):
465                 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
466                 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
467                 if var.from_hu_conv is not None:
468                     super_instantiator += ", " + var.from_hu_conv[0]
469                     if var.from_hu_conv[1] != "":
470                         pointer_to_adder += var.from_hu_conv[1] + ";\n"
471                 else:
472                     super_instantiator += ", " + first_to_lower(var.arg_name)
473             else:
474                 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
475                 super_instantiator += ", " + first_to_lower(var[1])
476                 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
477                 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
478
479         # BUILD INTERFACE METHODS
480         out_java_interface = ""
481         out_interface_implementation_overrides = ""
482         java_methods = []
483         for fn_line in field_function_lines:
484             java_method_descriptor = ""
485             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
486                 out_java_interface += fn_line.fn_name + "("
487                 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
488
489                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
490                     if idx >= 1:
491                         out_java_interface += ", "
492                         out_interface_implementation_overrides += ", "
493                     out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
494                     out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
495                     java_method_descriptor += arg_conv_info.java_fn_ty_arg
496                 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
497                 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
498                 java_methods.append((fn_line.fn_name, java_method_descriptor))
499
500                 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
501
502                 interface_method_override_inset = "\t\t\t\t\t\t"
503                 interface_implementation_inset = "\t\t\t\t\t\t\t"
504                 for arg_info in fn_line.args_ty:
505                     if arg_info.to_hu_conv is not None:
506                         out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
507
508                 if fn_line.ret_ty_info.java_ty != "void":
509                     out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
510                 else:
511                     out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
512
513                 for idx, arg_info in enumerate(fn_line.args_ty):
514                     if idx != 0:
515                         out_interface_implementation_overrides += ", "
516                     if arg_info.to_hu_conv_name is not None:
517                         out_interface_implementation_overrides += arg_info.to_hu_conv_name
518                     else:
519                         out_interface_implementation_overrides += arg_info.arg_name
520
521                 out_interface_implementation_overrides += ");\n"
522                 if fn_line.ret_ty_info.java_ty != "void":
523                     if fn_line.ret_ty_info.from_hu_conv is not None:
524                         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"
525                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
526                             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"
527                         #if fn_line.ret_ty_info.rust_obj in result_types:
528                         # XXX: We need to handle this in conversion logic so that its cross-language!
529                         # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
530                         #    out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
531                         out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
532                     else:
533                         out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
534                 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
535
536         trait_constructor_arguments = ""
537         for var in field_var_conversions:
538             if isinstance(var, ConvInfo):
539                 trait_constructor_arguments += ", " + var.arg_name
540             else:
541                 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl).bindings_instance"
542
543         out_typescript_human = f"""
544             {self.hu_struct_file_prefix}
545
546             export class {struct_name.replace("LDK","")} extends CommonBase {{
547
548                 bindings_instance?: bindings.{struct_name};
549
550                 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
551                     if (Number.isFinite(ptr)) {{
552                                         super(ptr);
553                                         this.bindings_instance = null;
554                                     }} else {{
555                                         // TODO: private constructor instantiation
556                                         super(bindings.{struct_name}_new(arg{super_instantiator}));
557                                         this.ptrs_to.push(arg);
558                                         {pointer_to_adder}
559                                     }}
560                 }}
561
562                 protected finalize() {{
563                     if (this.ptr != 0) {{
564                         bindings.{struct_name.replace("LDK","")}_free(this.ptr);
565                     }}
566                     super.finalize();
567                 }}
568
569                 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
570                     const impl_holder: {struct_name}Holder = new {struct_name}Holder();
571                     let structImplementation = <bindings.{struct_name}>{{
572                         // todo: in-line interface filling
573                         {out_interface_implementation_overrides}
574                     }};
575                     impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
576                 }}
577             }}
578
579             export interface {struct_name.replace("LDK", "")}Interface {{
580                 {out_java_interface}
581             }}
582
583             class {struct_name}Holder {{
584                 held: {struct_name.replace("LDK", "")};
585             }}
586 """
587
588         out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
589         java_meths = []
590         for fn_line in field_function_lines:
591             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
592                 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
593
594                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
595                     if idx >= 1:
596                         out_typescript_bindings = out_typescript_bindings + ", "
597                     out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
598
599                 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
600
601         out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
602
603         out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
604         for var in field_var_conversions:
605             if isinstance(var, ConvInfo):
606                 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
607             else:
608                 out_typescript_bindings += f", {var[1]}: {var[0]}"
609
610         out_typescript_bindings += f"""): number {{
611             throw new Error('unimplemented'); // TODO: bind to WASM
612         }}
613 """
614
615         out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
616
617         # Now that we've written out our java code (and created java_meths), generate C
618         out_c = "typedef struct " + struct_name + "_JCalls {\n"
619         out_c = out_c + "\tatomic_size_t refcnt;\n"
620         out_c = out_c + "\t// TODO: Object pointer o;\n"
621         for var in field_var_conversions:
622             if isinstance(var, ConvInfo):
623                 # We're a regular ol' field
624                 pass
625             else:
626                 # We're a supertrait
627                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
628         for fn in field_function_lines:
629             if fn.fn_name != "free" and fn.fn_name != "clone":
630                 out_c = out_c + "\t// TODO: Some kind of method pointer " + fn.fn_name + "_meth;\n"
631         out_c = out_c + "} " + struct_name + "_JCalls;\n"
632
633         for fn_line in field_function_lines:
634             if fn_line.fn_name == "free":
635                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
636                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
637                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
638                 out_c = out_c + "\t\t// TODO: do any release required for j_calls->o (refcnt-- in java, but may be redundant)\n"
639                 out_c = out_c + "\t\tFREE(j_calls);\n"
640                 out_c = out_c + "\t}\n}\n"
641
642         for idx, fn_line in enumerate(field_function_lines):
643             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
644                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
645                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_jcall("
646                 if fn_line.self_is_const:
647                     out_c = out_c + "const void* this_arg"
648                 else:
649                     out_c = out_c + "void* this_arg"
650
651                 for idx, arg in enumerate(fn_line.args_ty):
652                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
653
654                 out_c = out_c + ") {\n"
655                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
656
657                 for arg_info in fn_line.args_ty:
658                     if arg_info.ret_conv is not None:
659                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
660                         out_c = out_c + arg_info.arg_name
661                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
662
663                 out_c = out_c + "\t//TODO: jobject obj = get object we can call against on j_calls->o\n"
664                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
665                     out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " arg; // TODO: Call " + fn_line.fn_name + " on j_calls with instance obj, returning an object"
666                 elif fn_line.ret_ty_info.java_ty == "void":
667                     out_c = out_c + "\treturn; //TODO: Call " + fn_line.fn_name + " on j_calls with instance obj"
668                 elif not fn_line.ret_ty_info.passed_as_ptr:
669                     out_c = out_c + "\treturn 0; //TODO: Call " + fn_line.fn_name + " on j_calls with instance obj, returning " + fn_line.ret_ty_info.java_ty
670                 else:
671                     out_c = out_c + "\t" + fn_line.ret_ty_info.rust_obj + "* ret; // TODO: Call " + fn_line.fn_name + " on j_calls with instance obj, returning a pointer"
672
673                 for idx, arg_info in enumerate(fn_line.args_ty):
674                     if arg_info.ret_conv is not None:
675                         out_c = out_c + ", " + arg_info.ret_conv_name
676                     else:
677                         out_c = out_c + ", " + arg_info.arg_name
678                 out_c = out_c + ");\n"
679                 if fn_line.ret_ty_info.arg_conv is not None:
680                     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"
681
682                 out_c = out_c + "}\n"
683
684         # Write out a clone function whether we need one or not, as we use them in moving to rust
685         out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
686         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
687         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
688         for var in field_var_conversions:
689             if not isinstance(var, ConvInfo):
690                 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
691         out_c = out_c + "\treturn (void*) this_arg;\n"
692         out_c = out_c + "}\n"
693
694         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (" + self.c_fn_args_pfx + ", /*TODO: JS Object Reference */void* o"
695         for var in field_var_conversions:
696             if isinstance(var, ConvInfo):
697                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
698             else:
699                 out_c = out_c + ", /*TODO: JS Object Reference */void* " + var[1]
700         out_c = out_c + ") {\n"
701
702         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
703         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
704         out_c = out_c + "\t//TODO: Assign calls->o from o\n"
705
706         for (fn_name, java_meth_descr) in java_meths:
707             if fn_name != "free" and fn_name != "clone":
708                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
709                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
710
711         for var in field_var_conversions:
712             if isinstance(var, ConvInfo) and var.arg_conv is not None:
713                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
714         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
715         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
716         for fn_line in field_function_lines:
717             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
718                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_jcall,\n"
719             elif fn_line.fn_name == "free":
720                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
721             else:
722                 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
723         for var in field_var_conversions:
724             if isinstance(var, ConvInfo):
725                 if var.arg_conv_name is not None:
726                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
727                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
728                 else:
729                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
730                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
731             else:
732                 out_c = out_c + "\t\t." + var[1] + " = " + var[0] + "_init(NULL, " + var[1] + "),\n"
733         out_c = out_c + "\t};\n"
734         for var in field_var_conversions:
735             if not isinstance(var, ConvInfo):
736                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
737         out_c = out_c + "\treturn ret;\n"
738         out_c = out_c + "}\n"
739
740         out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1new (" + self.c_fn_args_pfx + ", /*TODO: JS Object Reference */void* o"
741         for var in field_var_conversions:
742             if isinstance(var, ConvInfo):
743                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
744             else:
745                 out_c = out_c + ", /*TODO: JS Object Reference */ void* " + var[1]
746         out_c = out_c + ") {\n"
747         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
748         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(NULL, o"
749         for var in field_var_conversions:
750             if isinstance(var, ConvInfo):
751                 out_c = out_c + ", " + var.arg_name
752             else:
753                 out_c = out_c + ", " + var[1]
754         out_c = out_c + ");\n"
755         out_c = out_c + "\treturn (long)res_ptr;\n"
756         out_c = out_c + "}\n"
757
758         return (out_typescript_bindings, out_typescript_human, out_c)
759
760     def trait_struct_inc_refcnt(self, ty_info):
761         return ""
762
763     def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
764         java_hu_type = struct_name.replace("LDK", "")
765
766         out_java_enum = ""
767         out_java = ""
768         out_c = ""
769
770         out_java_enum += (self.hu_struct_file_prefix)
771         out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
772         out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
773         out_java_enum += ("\tprotected finalize() {\n")
774         out_java_enum += ("\t\tsuper.finalize();\n")
775         out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
776         out_java_enum += ("\t}\n")
777         out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
778         out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
779         java_hu_subclasses = ""
780
781         out_java +=  ("\tpublic static class " + struct_name + " {\n")
782         out_java +=  ("\t\tprivate " + struct_name + "() {}\n")
783         for var in variant_list:
784             out_java +=  ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
785             java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
786             out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
787             out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
788             init_meth_params = ""
789             init_meth_body = ""
790             hu_conv_body = ""
791             for idx, field_ty in enumerate(var.fields):
792                 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
793                 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
794                 if field_ty.to_hu_conv is not None:
795                     hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
796                     hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
797                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
798                 else:
799                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
800                 if idx > 0:
801                     init_meth_params = init_meth_params + ", "
802                 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
803                 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
804             out_java +=  ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
805             out_java +=  (init_meth_body)
806             out_java +=  ("}\n")
807             out_java += ("\t\t}\n")
808             out_java_enum += ("\t\t}\n")
809             java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
810             java_hu_subclasses = java_hu_subclasses + hu_conv_body
811             java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
812         out_java += ("\t\tstatic native void init();\n")
813         out_java += ("\t}\n")
814         out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
815         out_java += ("\tstatic { " + struct_name + ".init(); }\n")
816         out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
817
818         out_c += (self.c_fn_ty_pfx + self.c_complex_enum_pass_ty(struct_name) + " " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " ptr) {\n")
819         out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
820         out_c += ("\tswitch(obj->tag) {\n")
821         for var in variant_list:
822             out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
823             c_params = []
824             for idx, field_map in enumerate(var.fields):
825                 if field_map.ret_conv is not None:
826                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
827                     out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
828                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
829                     c_params.append(field_map.ret_conv_name)
830                 else:
831                     c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
832             out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
833             out_c += ("\t\t}\n")
834         out_c += ("\t\tdefault: abort();\n")
835         out_c += ("\t}\n}\n")
836         out_java_enum += ("}\n")
837         out_java_enum += (java_hu_subclasses)
838         return (out_java, out_java_enum, out_c)
839
840     def map_opaque_struct(self, struct_name):
841         implementations = ""
842         method_header = ""
843         if struct_name.startswith("LDKLocked"):
844             implementations += "implements AutoCloseable "
845             method_header = """
846                 public close() {
847 """
848         else:
849             method_header = """
850                 protected finalize() {
851                     super.finalize();
852 """
853
854         out_opaque_struct_human = f"""
855             {self.hu_struct_file_prefix}
856
857             export default class {struct_name.replace("LDK","")} extends CommonBase {implementations}{{
858                 constructor(_dummy: object, ptr: number) {{
859                     super(ptr);
860                 }}
861
862                 {method_header}
863                     if (this.ptr != 0) {{
864                         bindings.{struct_name.replace("LDK","")}_free(this.ptr);
865                     }}
866                 }}
867 """
868         return out_opaque_struct_human
869
870     def map_function(self, argument_types, c_call_string, is_free, method_name, return_type_info, struct_meth, default_constructor_args, takes_self, args_known, has_out_java_struct: bool, type_mapping_generator):
871         out_java = ""
872         out_c = ""
873         out_java_struct = None
874
875         out_java += ("\tpublic static native ")
876         out_c += (self.c_fn_ty_pfx)
877         out_c += (return_type_info.c_ty)
878         out_java += (return_type_info.java_ty)
879         if return_type_info.ret_conv is not None:
880             ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
881         out_java += (" " + method_name + "(")
882         out_c += (" " + self.c_fn_name_pfx + method_name.replace('_', '_1') + "(" + self.c_fn_args_pfx)
883
884         method_argument_string = ""
885         native_call_argument_string = ""
886         for idx, arg_conv_info in enumerate(argument_types):
887             if idx != 0:
888                 method_argument_string += (", ")
889                 native_call_argument_string += ', '
890             if arg_conv_info.c_ty != "void":
891                 out_c += (", ")
892             if arg_conv_info.c_ty != "void":
893                 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
894                 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
895                 native_argument = arg_conv_info.arg_name
896                 if needs_encoding:
897                     converter = self.wasm_encoding_map[arg_conv_info.c_ty]
898                     native_argument = f"{converter}({arg_conv_info.arg_name})"
899                 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
900                 native_call_argument_string += native_argument
901
902         has_return_value = return_type_info.c_ty != 'void'
903         needs_decoding = return_type_info.c_ty in self.wasm_decoding_map
904         return_statement = 'return nativeResponseValue;'
905         if not has_return_value:
906             return_statement = '// debug statements here'
907         elif needs_decoding:
908             converter = self.wasm_decoding_map[return_type_info.c_ty]
909             return_statement = f"return {converter}(nativeResponseValue);"
910
911         out_java = f"""\texport function {method_name}({method_argument_string}): {return_type_info.java_ty} {{
912             if(!isWasmInitialized){{
913                 throw new Error("initializeWasm() must be awaited first!");
914             }}
915             const nativeResponseValue = wasm.{method_name}({native_call_argument_string});
916             {return_statement}\n\t}}
917         \n"""
918
919
920
921         if has_out_java_struct:
922             out_java_struct = ""
923             if not args_known:
924                 out_java_struct += ("\t// Skipped " + method_name + "\n")
925                 has_out_java_struct = False
926             else:
927                 meth_n = method_name[len(struct_meth) + 1:]
928                 if not takes_self:
929                     out_java_struct += (
930                             "\tpublic static " + return_type_info.java_hu_ty + " constructor_" + meth_n + "(")
931                 else:
932                     out_java_struct += ("\tpublic " + return_type_info.java_hu_ty + " " + meth_n + "(")
933                 for idx, arg in enumerate(argument_types):
934                     if idx != 0:
935                         if not takes_self or idx > 1:
936                             out_java_struct += (", ")
937                     elif takes_self:
938                         continue
939                     if arg.java_ty != "void":
940                         if arg.arg_name in default_constructor_args:
941                             for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
942                                 if explode_idx != 0:
943                                     out_java_struct += (", ")
944                                 out_java_struct += (
945                                         explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
946                         else:
947                             out_java_struct += (arg.java_hu_ty + " " + arg.arg_name)
948
949         out_c += (") {\n")
950         if out_java_struct is not None:
951             out_java_struct += (") {\n")
952         for info in argument_types:
953             if info.arg_conv is not None:
954                 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
955         if return_type_info.ret_conv is not None:
956             out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
957         elif return_type_info.c_ty != "void":
958             out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
959         else:
960             out_c += ("\t")
961         if c_call_string is None:
962             out_c += (method_name + "(")
963         else:
964             out_c += (c_call_string)
965         for idx, info in enumerate(argument_types):
966             if info.arg_conv_name is not None:
967                 if idx != 0:
968                     out_c += (", ")
969                 elif c_call_string is not None:
970                     continue
971                 out_c += (info.arg_conv_name)
972         out_c += (")")
973         if return_type_info.ret_conv is not None:
974             out_c += (ret_conv_sfx.replace('\n', '\n\t'))
975         else:
976             out_c += (";")
977         for info in argument_types:
978             if info.arg_conv_cleanup is not None:
979                 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
980         if return_type_info.ret_conv is not None:
981             out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
982         elif return_type_info.c_ty != "void":
983             out_c += ("\n\treturn ret_val;")
984         out_c += ("\n}\n\n")
985
986         if has_out_java_struct:
987             out_java_struct += ("\t\t")
988             if return_type_info.java_ty != "void":
989                 out_java_struct += (return_type_info.java_ty + " ret = ")
990             out_java_struct += ("bindings." + method_name + "(")
991             for idx, info in enumerate(argument_types):
992                 if idx != 0:
993                     out_java_struct += (", ")
994                 if idx == 0 and takes_self:
995                     out_java_struct += ("this.ptr")
996                 elif info.arg_name in default_constructor_args:
997                     out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
998                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
999                         if explode_idx != 0:
1000                             out_java_struct += (", ")
1001                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1002                         if explode_arg.from_hu_conv is not None:
1003                             out_java_struct += (
1004                                 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1005                         else:
1006                             out_java_struct += (expl_arg_name)
1007                     out_java_struct += (")")
1008                 elif info.from_hu_conv is not None:
1009                     out_java_struct += (info.from_hu_conv[0])
1010                 else:
1011                     out_java_struct += (info.arg_name)
1012             out_java_struct += (");\n")
1013             if return_type_info.to_hu_conv is not None:
1014                 if not takes_self:
1015                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1016                                                                                                              return_type_info.to_hu_conv_name) + "\n")
1017                 else:
1018                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1019
1020             for idx, info in enumerate(argument_types):
1021                 if idx == 0 and takes_self:
1022                     pass
1023                 elif info.arg_name in default_constructor_args:
1024                     for explode_arg in default_constructor_args[info.arg_name]:
1025                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1026                         if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1027                             out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1028                                                                                              expl_arg_name).replace(
1029                                 "this", return_type_info.to_hu_conv_name) + ";\n")
1030                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1031                     if not takes_self and return_type_info.to_hu_conv_name is not None:
1032                         out_java_struct += (
1033                                 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name) + ";\n")
1034                     else:
1035                         out_java_struct += ("\t\t" + info.from_hu_conv[1] + ";\n")
1036
1037             if return_type_info.to_hu_conv_name is not None:
1038                 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1039             elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1040                 out_java_struct += ("\t\treturn ret;\n")
1041             out_java_struct += ("\t}\n\n")
1042
1043         return (out_java, out_c, out_java_struct)