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