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