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