[C#] Drop java-specific crap and upgrade mono to something sane
[ldk-java] / csharp_strings.py
1 from bindingstypes import *
2 from enum import Enum
3 import sys
4
5 class Target(Enum):
6     CSHARP = 1,
7
8 class Consts:
9     def __init__(self, DEBUG: bool, target: Target, **kwargs):
10         self.target = target
11         self.c_array_class_caches = set()
12         self.c_type_map = dict(
13             bool = ['bool'],
14             uint8_t = ['byte'],
15             uint16_t = ['short'],
16             uint32_t = ['int'],
17             uint64_t = ['long'],
18             int64_t = ['long'],
19         )
20         self.java_type_map = dict(
21             String = "string"
22         )
23         self.java_hu_type_map = dict(
24             String = "string"
25         )
26
27         self.to_hu_conv_templates = dict(
28             ptr = '{human_type} {var_name}_hu_conv = null; if ({var_name} < 0 || {var_name} > 4096) { {var_name}_hu_conv = new {human_type}(null, {var_name}); }',
29             default = '{human_type} {var_name}_hu_conv = null; if ({var_name} < 0 || {var_name} > 4096) { {var_name}_hu_conv = new {human_type}(null, {var_name}); }'
30         )
31
32         self.bindings_header = """
33 using org.ldk.enums;
34 using org.ldk.impl;
35 using System;
36 using System.Runtime.InteropServices;
37
38 namespace org { namespace ldk { namespace impl {
39
40 internal class bindings {
41         internal class ArrayCoder : ICustomMarshaler {
42                 int size = 0;
43                 GCHandle pinnedArray;
44                 public static ICustomMarshaler GetInstance(string pstrCookie) {
45                         return new ArrayCoder();
46                 }
47
48                 public Object MarshalNativeToManaged(IntPtr pNativeData) { throw new NotImplementedException(); }
49                 public IntPtr MarshalManagedToNative(Object obj) {
50                         if (obj.GetType() == typeof(byte[])) {
51                                 byte[] inp = (byte[])obj;
52                                 IntPtr data = Marshal.AllocHGlobal(inp.Length + 8);
53                                 Marshal.WriteInt64(data, inp.Length);
54                                 Marshal.Copy(inp, 0, data + 8, inp.Length);
55                                 this.size = inp.Length + 8;
56                                 return data;
57                         } else {
58                                 throw new NotImplementedException();
59                         }
60                 }
61                 public void CleanUpNativeData(IntPtr pNativeData) {
62                         Marshal.FreeHGlobal(pNativeData);
63                 }
64                 public void CleanUpManagedData(Object ManagedObj) { }
65                 public int GetNativeDataSize() {
66                         // Blindly guess based on the last allocation, no idea how else to implement this.
67                         return this.size;
68                 }
69         }
70
71         /*static {
72                 init(java.lang.Enum.class, VecOrSliceDef.class);
73                 init_class_cache();
74                 if (!get_lib_version_string().equals(version.get_ldk_java_bindings_version()))
75                         throw new ArgumentException("Compiled LDK library and LDK class failes do not match");
76                 // Fetching the LDK versions from C also checks that the header and binaries match
77                 Console.Error.WriteLine("Loaded LDK-Java Bindings " + version.get_ldk_java_bindings_version() + " with LDK " + get_ldk_version() + " and LDK-C-Bindings " + get_ldk_c_bindings_version());
78         }*/
79         //static extern void init(java.lang.Class c);
80         //static native void init_class_cache();
81 """
82         self.bindings_header += self.native_meth_decl("get_lib_version_string", "string") + "();\n"
83         self.bindings_header += self.native_meth_decl("get_ldk_c_bindings_version", "string") + "();\n"
84         self.bindings_header += self.native_meth_decl("get_ldk_version", "string") + "();\n\n"
85
86         self.bindings_version_file = """
87
88 public class version {
89         public static string get_ldk_java_bindings_version() {
90                 return "<git_version_ldk_garbagecollected>";
91         }
92 }"""
93
94         self.util_fn_pfx = """using org.ldk.impl;
95 using org.ldk.enums;
96 using org.ldk.util;
97 using org.ldk.structs;
98 using System;
99
100 namespace org { namespace ldk { namespace util {
101 public class UtilMethods {
102 """
103         self.util_fn_sfx = "} } } }"
104         self.common_base = """using System.Collections.Generic;
105 using System.Diagnostics;
106
107 public class CommonBase {
108         protected internal long ptr;
109         protected internal LinkedList<object> ptrs_to = new LinkedList<object>();
110         protected CommonBase(long ptr) { Trace.Assert(ptr < 0 || ptr > 4096); this.ptr = ptr; }
111 }
112 """
113
114         self.txin_defn = """public class TxIn : CommonBase {
115         /** The witness in this input, in serialized form */
116         public readonly byte[] witness;
117         /** The script_sig in this input */
118         public readonly byte[] script_sig;
119         /** The transaction output's sequence number */
120         public readonly int sequence;
121         /** The txid this input is spending */
122         public readonly byte[] previous_txid;
123         /** The output index within the spent transaction of the output this input is spending */
124         public readonly int previous_vout;
125
126         internal TxIn(object _dummy, long ptr) : base(ptr) {
127                 this.witness = bindings.TxIn_get_witness(ptr);
128                 this.script_sig = bindings.TxIn_get_script_sig(ptr);
129                 this.sequence = bindings.TxIn_get_sequence(ptr);
130                 this.previous_txid = bindings.TxIn_get_previous_txid(ptr);
131                 this.previous_vout = bindings.TxIn_get_previous_vout(ptr);
132         }
133         public TxIn(byte[] witness, byte[] script_sig, int sequence, byte[] previous_txid, int previous_vout)
134         : this(null, bindings.TxIn_new(witness, script_sig, sequence, previous_txid, previous_vout)) {}
135
136         ~TxIn() {
137                 if (ptr != 0) { bindings.TxIn_free(ptr); }
138         }
139 }"""
140
141         self.txout_defn = """public class TxOut : CommonBase {
142         /** The script_pubkey in this output */
143         public readonly byte[] script_pubkey;
144         /** The value, in satoshis, of this output */
145         public readonly long value;
146
147     internal TxOut(object _dummy, long ptr) : base(ptr) {
148                 this.script_pubkey = bindings.TxOut_get_script_pubkey(ptr);
149                 this.value = bindings.TxOut_get_value(ptr);
150         }
151     public TxOut(long value, byte[] script_pubkey) : this(null, bindings.TxOut_new(script_pubkey, value)) {}
152
153         ~TxOut() {
154                 if (ptr != 0) { bindings.TxOut_free(ptr); }
155         }
156 }"""
157
158         self.scalar_defn = """public class BigEndianScalar : CommonBase {
159         /** The bytes of the scalar value, in big endian */
160         public readonly byte[] scalar_bytes;
161
162     internal BigEndianScalar(object _dummy, long ptr) : base(ptr) {
163                 this.scalar_bytes = bindings.BigEndianScalar_get_bytes(ptr);
164         }
165     public BigEndianScalar(byte[] scalar_bytes) : base(bindings.BigEndianScalar_new(scalar_bytes)) {
166                 this.scalar_bytes = bindings.BigEndianScalar_get_bytes(ptr);
167         }
168
169         ~BigEndianScalar() {
170                 if (ptr != 0) { bindings.BigEndianScalar_free(ptr); }
171         }
172 }"""
173
174
175         self.c_file_pfx = """
176 // On OSX jlong (ie long long) is not equivalent to int64_t, so we override here
177 #define int64_t jlong
178 #include <lightning.h>
179 #include <string.h>
180 #include <stdatomic.h>
181 #include <stdlib.h>
182
183 #define LIKELY(v) __builtin_expect(!!(v), 1)
184 #define UNLIKELY(v) __builtin_expect(!!(v), 0)
185
186 """
187
188         self.c_file_pfx = self.c_file_pfx + "#include <stdio.h>\n#define DEBUG_PRINT(...) fprintf(stderr, __VA_ARGS__)\n"
189
190         if not DEBUG or sys.platform == "darwin":
191             self.c_file_pfx = self.c_file_pfx + """#define do_MALLOC(a, _b, _c) malloc(a)
192 #define MALLOC(a, _) malloc(a)
193 #define FREE(p) if ((uint64_t)(p) > 4096) { free(p); }
194 #define CHECK_ACCESS(p)
195 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
196 """
197         if not DEBUG:
198             self.c_file_pfx += """#define DO_ASSERT(a) (void)(a)
199 #define CHECK(a)
200 """
201         if DEBUG:
202             self.c_file_pfx = self.c_file_pfx + """#include <assert.h>
203 // Always run a, then assert it is true:
204 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
205 // Assert a is true or do nothing
206 #define CHECK(a) DO_ASSERT(a)
207
208 void __attribute__((constructor)) debug_log_version() {
209         if (check_get_ldk_version() == NULL)
210                 DEBUG_PRINT("LDK version did not match the header we built against\\n");
211         if (check_get_ldk_bindings_version() == NULL)
212                 DEBUG_PRINT("LDK C Bindings version did not match the header we built against\\n");
213 }
214 """
215
216             if sys.platform != "darwin":
217                 self.c_file_pfx += """
218 // Running a leak check across all the allocations and frees of the JDK is a mess,
219 // so instead we implement our own naive leak checker here, relying on the -wrap
220 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
221 // and free'd in Rust or C across the generated bindings shared library.
222 #include <threads.h>
223 """
224
225                 self.c_file_pfx = self.c_file_pfx + "#include <execinfo.h>\n"
226                 self.c_file_pfx = self.c_file_pfx + """
227 #include <unistd.h>
228 #include <pthread.h>
229 static pthread_mutex_t allocation_mtx;
230
231 void __attribute__((constructor)) init_mtx() {
232         DO_ASSERT(!pthread_mutex_init(&allocation_mtx, NULL));
233 }
234
235 #define BT_MAX 128
236 typedef struct allocation {
237         struct allocation* next;
238         void* ptr;
239         const char* struct_name;
240         void* bt[BT_MAX];
241         int bt_len;
242         unsigned long alloc_len;
243 } allocation;
244 static allocation* allocation_ll = NULL;
245
246 void* __real_malloc(size_t len);
247 void* __real_calloc(size_t nmemb, size_t len);
248 static void new_allocation(void* res, const char* struct_name, size_t len) {
249         allocation* new_alloc = __real_malloc(sizeof(allocation));
250         new_alloc->ptr = res;
251         new_alloc->struct_name = struct_name;
252         new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
253         new_alloc->alloc_len = len;
254         DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
255         new_alloc->next = allocation_ll;
256         allocation_ll = new_alloc;
257         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
258 }
259 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
260         void* res = __real_malloc(len);
261         new_allocation(res, struct_name, lineno);
262         return res;
263 }
264 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
265
266 void __real_free(void* ptr);
267 static void alloc_freed(void* ptr) {
268         allocation* p = NULL;
269         DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
270         allocation* it = allocation_ll;
271         while (it->ptr != ptr) {
272                 p = it; it = it->next;
273                 if (it == NULL) {
274                         DEBUG_PRINT("ERROR: Tried to free unknown pointer %p at:\\n", ptr);
275                         void* bt[BT_MAX];
276                         int bt_len = backtrace(bt, BT_MAX);
277                         backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
278                         DEBUG_PRINT("\\n\\n");
279                         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
280                         return; // addrsan should catch malloc-unknown and print more info than we have
281                 }
282         }
283         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
284         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
285         DO_ASSERT(it->ptr == ptr);
286         __real_free(it);
287 }
288 static void FREE(void* ptr) {
289         if ((uint64_t)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
290         alloc_freed(ptr);
291         __real_free(ptr);
292 }
293
294 void* __wrap_malloc(size_t len) {
295         void* res = __real_malloc(len);
296         new_allocation(res, "malloc call", len);
297         return res;
298 }
299 void* __wrap_calloc(size_t nmemb, size_t len) {
300         void* res = __real_calloc(nmemb, len);
301         new_allocation(res, "calloc call", len);
302         return res;
303 }
304 void __wrap_free(void* ptr) {
305         if (ptr == NULL) return;
306         alloc_freed(ptr);
307         __real_free(ptr);
308 }
309
310 static void CHECK_ACCESS(const void* ptr) {
311         DO_ASSERT(!pthread_mutex_lock(&allocation_mtx));
312         allocation* it = allocation_ll;
313         while (it->ptr != ptr) {
314                 it = it->next;
315                 if (it == NULL) {
316                         DEBUG_PRINT("ERROR: Tried to access unknown pointer %p at:\\n", ptr);
317                         void* bt[BT_MAX];
318                         int bt_len = backtrace(bt, BT_MAX);
319                         backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
320                         DEBUG_PRINT("\\n\\n");
321                         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
322                         return; // addrsan should catch and print more info than we have
323                 }
324         }
325         DO_ASSERT(!pthread_mutex_unlock(&allocation_mtx));
326 }
327 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
328         if (v.is_owned && v.inner != NULL) { \\
329                 const void *p = __unmangle_inner_ptr(v.inner); \\
330                 if (p != NULL) { \\
331                         CHECK_ACCESS(p); \\
332                 } \\
333         }
334
335 void* __real_realloc(void* ptr, size_t newlen);
336 void* __wrap_realloc(void* ptr, size_t len) {
337         if (ptr != NULL) alloc_freed(ptr);
338         void* res = __real_realloc(ptr, len);
339         new_allocation(res, "realloc call", len);
340         return res;
341 }
342 void __wrap_reallocarray(void* ptr, size_t new_sz) {
343         // Rust doesn't seem to use reallocarray currently
344         DO_ASSERT(false);
345 }
346
347 void __attribute__((destructor)) check_leaks() {
348         unsigned long alloc_count = 0;
349         unsigned long alloc_size = 0;
350         DEBUG_PRINT("The following LDK-allocated blocks still remain.\\n");
351         DEBUG_PRINT("Note that this is only accurate if System.gc(); System.runFinalization()\\n");
352         DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
353         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
354                 DEBUG_PRINT("%s %p (%lu bytes) remains:\\n", a->struct_name, a->ptr, a->alloc_len);
355                 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
356                 DEBUG_PRINT("\\n\\n");
357                 alloc_count++;
358                 alloc_size += a->alloc_len;
359         }
360         DEBUG_PRINT("%lu allocations remained for %lu bytes.\\n", alloc_count, alloc_size);
361         DEBUG_PRINT("Note that this is only accurate if System.gc(); System.runFinalization()\\n");
362         DEBUG_PRINT("was called prior to exit after all LDK objects were out of scope.\\n");
363 }
364 """
365         self.c_file_pfx = self.c_file_pfx + """
366
367 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
368 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
369 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
370 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
371
372 _Static_assert(sizeof(void*) <= 8, "Pointers must fit into 64 bits");
373
374 #define DECL_ARR_TYPE(ty, name) \\
375         struct name##array { \\
376                 uint64_t arr_len; /* uint32_t would suffice but we want to align uint64_ts as well */ \\
377                 ty elems[]; \\
378         }; \\
379         typedef struct name##array * name##Array; \\
380         static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
381                 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint64_t), #name" array init", lineno); \\
382                 arr->arr_len = arr_len; \\
383                 return arr; \\
384         }
385
386 DECL_ARR_TYPE(int64_t, int64_t);
387 DECL_ARR_TYPE(uint64_t, uint64_t);
388 DECL_ARR_TYPE(int8_t, int8_t);
389 DECL_ARR_TYPE(int16_t, int16_t);
390 DECL_ARR_TYPE(uint32_t, uint32_t);
391 DECL_ARR_TYPE(void*, ptr);
392 DECL_ARR_TYPE(char, char);
393 typedef charArray jstring;
394
395 static inline jstring str_ref_to_cs(const char* chars, size_t len) {
396         charArray arr = init_charArray(len, __LINE__);
397         memcpy(arr->elems, chars, len);
398         return arr;
399 }
400 static inline LDKStr str_ref_to_owned_c(const jstring str) {
401         char* newchars = MALLOC(str->arr_len + 1, "String chars");
402         memcpy(newchars, str->elems, str->arr_len);
403         newchars[str->arr_len] = 0;
404         LDKStr res = {
405                 .chars = newchars,
406                 .len = str->arr_len,
407                 .chars_is_owned = true
408         };
409         return res;
410 }
411
412 jstring CS_LDK_get_ldk_c_bindings_version() {
413         return str_ref_to_cs(check_get_ldk_bindings_version(), strlen(check_get_ldk_bindings_version()));
414 }
415 jstring CS_LDK_get_ldk_version() {
416         return str_ref_to_cs(check_get_ldk_version(), strlen(check_get_ldk_version()));
417 }
418 #include "version.c"
419 """
420         self.c_version_file = """const char* CS_LDK_get_lib_version_string() {
421         return "<git_version_ldk_garbagecollected>";
422 }"""
423
424         self.hu_struct_file_prefix = """using org.ldk.impl;
425 using org.ldk.enums;
426 using org.ldk.util;
427 using System;
428
429 namespace org { namespace ldk { namespace structs {
430
431 """
432         self.hu_struct_file_suffix = "} } }\n"
433         self.c_fn_args_pfx = ""
434         self.c_fn_ty_pfx = ""
435         self.file_ext = ".cs"
436         self.ptr_c_ty = "int64_t"
437         self.ptr_native_ty = "long"
438         self.u128_native_ty = "UInt128"
439         self.usize_c_ty = "int64_t"
440         self.usize_native_ty = "long"
441         self.native_zero_ptr = "0"
442         self.result_c_ty = "jclass"
443         self.ptr_arr = "jobjectArray"
444         self.is_arr_some_check = ("", " != NULL")
445         self.get_native_arr_len_call = ("(*env)->GetArrayLength(env, ", ")")
446
447         self.bindings_footer_wip = "\tstatic bindings() {\n"
448     def bindings_footer(self):
449         return self.bindings_footer_wip + "\t}\n}\n} } }\n"
450
451     def native_meth_decl(self, meth_name, ret_ty_str):
452         return "\t[DllImport (\"ldkcsharp\", EntryPoint=\"CS_LDK_" + meth_name + "\")] public static extern " + ret_ty_str + " " + meth_name
453
454     def c_fn_name_define_pfx(self, fn_name, have_args):
455         return " CS_LDK_" + fn_name + "("
456
457     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
458         return None
459     def create_native_arr_call(self, arr_len, ty_info):
460         if ty_info.c_ty == "ptrArray":
461             assert ty_info.rust_obj == "LDKCVec_U5Z" or (ty_info.subty is not None and (ty_info.subty.c_ty.endswith("Array") or ty_info.subty.rust_obj == "LDKStr"))
462         return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
463     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
464         if ty_info.c_ty == "int8_tArray":
465             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
466         elif ty_info.c_ty == "int16_tArray":
467             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + " * 2)")
468         else:
469             assert False
470     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
471         if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
472             if copy:
473                 byte_len = arr_len
474                 if ty_info.c_ty == "int16_tArray":
475                     byte_len = arr_len + " * 2"
476                 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + byte_len + "); FREE(" + arr_name + ")"
477         assert not copy
478         if ty_info.c_ty == "ptrArray":
479             return "(void*) " + arr_name + "->elems"
480         else:
481             return arr_name + "->elems"
482     def get_native_arr_elem(self, arr_name, idxc, ty_info):
483         assert False # Only called if above is None
484     def get_native_arr_ptr_call(self, ty_info):
485         if ty_info.subty is not None:
486             return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 8)"
487         return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 8)"
488     def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
489         return None
490     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
491         if ty_info.c_ty == "int8_tArray":
492             return "FREE(" + arr_name + ");"
493         else:
494             return "FREE(" + arr_name + ")"
495
496     def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
497         if elem_ty.java_hu_ty == "UInt5":
498             return arr_name + " != null ? InternalUtils.convUInt5Array(" + arr_name + ") : null"
499         elif elem_ty.java_hu_ty == "WitnessVersion":
500             return arr_name + " != null ? InternalUtils.convWitnessVersionArray(" + arr_name + ") : null"
501         else:
502             return arr_name + " != null ? InternalUtils.mapArray(" + arr_name + ", " + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
503
504     def str_ref_to_native_call(self, var_name, str_len):
505         return "str_ref_to_cs(" + var_name + ", " + str_len + ")"
506     def str_ref_to_c_call(self, var_name):
507         return "str_ref_to_owned_c(" + var_name + ")"
508     def str_to_hu_conv(self, var_name):
509         return None
510     def str_from_hu_conv(self, var_name):
511         return None
512
513     def init_str(self):
514         return ""
515
516     def var_decl_statement(self, ty_string, var_name, statement):
517         return ty_string + " " + var_name + " = " + statement
518
519     def get_java_arr_len(self, arr_name):
520         return arr_name + ".Length"
521     def get_java_arr_elem(self, elem_ty, arr_name, idx):
522         return arr_name + "[" + idx + "]"
523     def constr_hu_array(self, ty_info, arr_len):
524         base_ty = ty_info.subty.java_hu_ty.split("[")[0].split("<")[0]
525         conv = "new " + base_ty + "[" + arr_len + "]"
526         if "[" in ty_info.subty.java_hu_ty.split("<")[0]:
527             # Do a bit of a dance to move any excess [] to the end
528             conv += "[" + ty_info.subty.java_hu_ty.split("<")[0].split("[")[1]
529         return conv
530     def cleanup_converted_native_array(self, ty_info, arr_name):
531         return None
532
533     def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
534         mapped_ty = arr_ty.subty
535         if arr_ty.rust_obj == "LDKU128":
536             return ("" + arr_name + ".getLEBytes()", "")
537         if fixed_len is not None:
538             return ("InternalUtils.check_arr_len(" + arr_name + ", " + fixed_len + ")", "")
539         return None
540     def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
541         if arr_ty.rust_obj == "LDKU128":
542             return "org.ldk.util.UInt128 " + conv_name + " = new org.ldk.util.UInt128(" + arr_name + ");"
543         return None
544
545     def java_arr_ty_str(self, elem_ty_str):
546         return elem_ty_str + "[]"
547
548     def for_n_in_range(self, n, minimum, maximum):
549         return "for (int " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
550     def for_n_in_arr(self, n, arr_name, arr_elem_ty):
551         return ("foreach (" + arr_elem_ty.java_hu_ty + " " + n + " in " + arr_name + ") { ", " }")
552
553     def get_ptr(self, var):
554         return var + ".ptr"
555     def set_null_skip_free(self, var):
556         return var + ".ptr" + " = 0;"
557
558     def add_ref(self, holder, referent):
559         return "if (" + holder + " != null) { " + holder + ".ptrs_to.AddLast(" + referent + "); }"
560
561     def fully_qualified_hu_ty_path(self, ty):
562         if ty.java_fn_ty_arg.startswith("L") and ty.java_fn_ty_arg.endswith(";"):
563             return ty.java_hu_ty
564         if ty.java_hu_ty == "UnqualifiedError" or ty.java_hu_ty == "UInt128" or ty.java_hu_ty == "UInt5" or ty.java_hu_ty == "WitnessVersion":
565             return "org.ldk.util." + ty.java_hu_ty
566         if not ty.is_native_primitive and ty.rust_obj is not None and not "[]" in ty.java_hu_ty:
567             return "org.ldk.structs." + ty.java_hu_ty
568         return ty.java_hu_ty
569
570     def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
571         out_java_enum = "namespace org { namespace ldk { namespace enums {"
572         out_java = ""
573         out_c = ""
574
575         out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_cs(int32_t ord) {\n"
576         out_c += "\tswitch (ord) {\n"
577
578         if enum_doc_comment is not None:
579             out_java_enum += "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
580         out_java_enum += "public enum " + struct_name + " {\n"
581         ord_v = 0
582         for var, var_docs in variants:
583             if var_docs is not None:
584                 out_java_enum += "\t/**\n\t * " + var_docs.replace("\n", "\n\t * ") + "\n\t */\n"
585             out_java_enum += "\t" + var + ",\n"
586             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
587             ord_v = ord_v + 1
588         out_java_enum += "}"
589         out_c += "\t\tdefault: abort();\n"
590         out_c += "\t}\n"
591         out_c += "}\n"
592
593         out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_cs(LDK" + struct_name + " val) {\n"
594         out_c = out_c + "\tswitch (val) {\n"
595         ord_v = 0
596         for var, _ in variants:
597             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
598             ord_v = ord_v + 1
599         out_c = out_c + "\t\tdefault: abort();\n"
600         out_c = out_c + "\t}\n"
601         out_c = out_c + "}\n"
602
603         return (out_c, out_java_enum + "} } }\n", out_java)
604
605     def c_unitary_enum_to_native_call(self, ty_info):
606         return (ty_info.rust_obj + "_to_cs(", ")")
607     def native_unitary_enum_to_c_call(self, ty_info):
608         return (ty_info.rust_obj + "_from_cs(", ")")
609
610     def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
611         out_c = ""
612         for var in variants:
613             out_c = out_c + "static jclass " + struct_name + "_" + var + "_class = NULL;\n"
614             out_c = out_c + "static jmethodID " + struct_name + "_" + var + "_meth = NULL;\n"
615         out_c += "void" + self.c_fn_name_define_pfx(struct_name.replace("_", "_1") + "_init", True) + self.c_fn_args_pfx + ") {\n"
616         for var_name in variants:
617             out_c += "\t" + struct_name + "_" + var_name + "_class =\n"
618             out_c += "\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"org/ldk/impl/bindings$" + struct_name + "$" + var_name + "\"));\n"
619             out_c += "\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n"
620             out_c += "\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n"
621             out_c += "\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n"
622         out_c = out_c + "}\n"
623         return out_c
624
625     def c_complex_enum_pass_ty(self, struct_name):
626         return "jobject"
627
628     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
629         ret = "(*env)->NewObject(env, " + struct_name + "_" + variant + "_class, " + struct_name + "_" + variant + "_meth"
630         for param in c_params:
631             ret = ret + ", " + param
632         return ret + ")"
633
634     def native_c_map_trait(self, struct_name, field_vars, flattened_field_vars, field_fns, trait_doc_comment):
635         out_java_trait = ""
636         out_java = ""
637
638         # First generate most of the Java code, note that we need information about java method argument strings for C
639         out_java_trait += self.hu_struct_file_prefix
640         if trait_doc_comment is not None:
641             out_java_trait += "/**\n * " + trait_doc_comment.replace("\n", "\n * ") + "\n */\n"
642         out_java_trait = out_java_trait + "public class " + struct_name.replace("LDK","") + " : CommonBase {\n"
643         out_java_trait = out_java_trait + "\tinternal readonly bindings." + struct_name + " bindings_instance;\n"
644         out_java_trait = out_java_trait + "\tinternal " + struct_name.replace("LDK", "") + "(object _dummy, long ptr) : base(ptr) { bindings_instance = null; }\n"
645         out_java_trait = out_java_trait + "\tprivate " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg"
646         for var in flattened_field_vars:
647             if isinstance(var, ConvInfo):
648                 out_java_trait += ", " + var.java_hu_ty + " " + var.arg_name
649             else:
650                 out_java_trait += ", bindings." + var[0] + " " + var[1]
651         out_java_trait += ") : base(bindings." + struct_name + "_new(arg"
652         for var in flattened_field_vars:
653             if isinstance(var, ConvInfo):
654                 if var.from_hu_conv is not None:
655                     out_java_trait = out_java_trait + ", " + var.from_hu_conv[0]
656                 else:
657                     out_java_trait = out_java_trait + ", " + var.arg_name
658             else:
659                 out_java_trait = out_java_trait + ", " + var[1]
660         out_java_trait = out_java_trait + ")) {\n"
661         out_java_trait = out_java_trait + "\t\tthis.ptrs_to.AddLast(arg);\n"
662         for var in flattened_field_vars:
663             if isinstance(var, ConvInfo):
664                 if var.from_hu_conv is not None and var.from_hu_conv[1] != "":
665                     out_java_trait = out_java_trait + "\t\t" + var.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n"
666             else:
667                 out_java_trait = out_java_trait + "\t\tthis.ptrs_to.AddLast(" + var[1] + ");\n"
668         out_java_trait = out_java_trait + "\t\tthis.bindings_instance = arg;\n"
669         out_java_trait = out_java_trait + "\t}\n"
670         out_java_trait = out_java_trait + "\t~" + struct_name.replace("LDK","") + "() {\n"
671         out_java_trait = out_java_trait + "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n"
672         out_java_trait = out_java_trait + "\t}\n\n"
673
674         java_trait_wrapper = "\tprivate class " + struct_name + "Holder { internal " + struct_name.replace("LDK", "") + " held; }\n"
675         java_trait_wrapper += "\tprivate class " + struct_name + "Impl : bindings." + struct_name + " {\n"
676         java_trait_wrapper += "\t\tinternal " + struct_name + "Impl(" + struct_name.replace("LDK", "") + "Interface arg, " + struct_name + "Holder impl_holder) { this.arg = arg; this.impl_holder = impl_holder; }\n"
677         java_trait_wrapper += "\t\tprivate " + struct_name.replace("LDK", "") + "Interface arg;\n"
678         java_trait_wrapper += "\t\tprivate " + struct_name + "Holder impl_holder;\n"
679         java_trait_constr = "\tpublic static " + struct_name.replace("LDK", "") + " new_impl(" + struct_name.replace("LDK", "") + "Interface arg"
680         for var in flattened_field_vars:
681             if isinstance(var, ConvInfo):
682                 java_trait_constr += ", " + var.java_hu_ty + " " + var.arg_name
683             else:
684                 # Ideally we'd be able to take any instance of the interface, but our C code can only represent
685                 # Java-implemented version, so we require users pass a Java implementation here :/
686                 java_trait_constr += ", " + var[0].replace("LDK", "") + "." + var[0].replace("LDK", "") + "Interface " + var[1] + "_impl"
687         java_trait_constr = java_trait_constr + ") {\n\t\t" + struct_name + "Holder impl_holder = new " + struct_name + "Holder();\n"
688         java_trait_constr = java_trait_constr + "\t\timpl_holder.held = new " + struct_name.replace("LDK", "") + "(new " + struct_name + "Impl(arg, impl_holder)"
689         out_java_trait += "\tpublic interface " + struct_name.replace("LDK", "") + "Interface {\n"
690         out_java += "\tpublic interface " + struct_name + " {\n"
691         java_meths = []
692         for fn_line in field_fns:
693             java_meth_descr = "("
694             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
695                 fn_name = fn_line.fn_name
696                 if fn_name == "lock": # reserved symbol
697                     fn_name = "do_lock"
698                 out_java += "\t\t" + fn_line.ret_ty_info.java_ty + " " + fn_name + "("
699                 java_trait_wrapper += "\t\tpublic " + fn_line.ret_ty_info.java_ty + " " + fn_name + "("
700                 out_java_trait += "\t\t/**\n\t\t * " + fn_line.docs.replace("\n", "\n\t\t * ") + "\n\t\t */\n"
701                 out_java_trait += "\t\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_name + "("
702
703                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
704                     if idx >= 1:
705                         out_java += ", "
706                         java_trait_wrapper += ", "
707                         out_java_trait += ", "
708                     out_java += arg_conv_info.java_ty + " _" + arg_conv_info.arg_name
709                     out_java_trait += arg_conv_info.java_hu_ty + " _" + arg_conv_info.arg_name
710                     java_trait_wrapper += arg_conv_info.java_ty + " _" + arg_conv_info.arg_name
711                     java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
712                 java_meth_descr = java_meth_descr + ")" + fn_line.ret_ty_info.java_fn_ty_arg
713                 java_meths.append((fn_line.fn_name, java_meth_descr))
714
715                 out_java += ");\n"
716                 out_java_trait += ");\n"
717                 java_trait_wrapper += ") {\n"
718
719                 for arg_info in fn_line.args_ty:
720                     if arg_info.to_hu_conv is not None:
721                         java_trait_wrapper += "\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t").replace(arg_info.arg_name, "_" + arg_info.arg_name) + "\n"
722
723                 if fn_line.ret_ty_info.java_ty != "void":
724                     java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_name + "("
725                 else:
726                     java_trait_wrapper += "\t\t\targ." + fn_name + "("
727
728                 for idx, arg_info in enumerate(fn_line.args_ty):
729                     if idx != 0:
730                         java_trait_wrapper += ", "
731                     if arg_info.to_hu_conv_name is not None:
732                         java_trait_wrapper += arg_info.to_hu_conv_name.replace(arg_info.arg_name, "_" + arg_info.arg_name)
733                     else:
734                         java_trait_wrapper += "_" + arg_info.arg_name
735
736                 java_trait_wrapper += ");\n"
737                 java_trait_wrapper += "\t\t\t\tGC.KeepAlive(arg);\n"
738                 if fn_line.ret_ty_info.java_ty != "void":
739                     if fn_line.ret_ty_info.from_hu_conv is not None:
740                         java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
741                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
742                             java_trait_wrapper += "\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
743                         java_trait_wrapper += "\t\t\treturn result;\n"
744                     else:
745                         java_trait_wrapper += "\t\t\treturn ret;\n"
746                 java_trait_wrapper += "\t\t}\n"
747         java_trait_wrapper += "\t}"
748         for var in field_vars:
749             if isinstance(var, ConvInfo):
750                 java_trait_constr = java_trait_constr + ", " + var.arg_name
751             else:
752                 java_trait_constr += ", " + var[1] + ".new_impl(" + var[1] + "_impl"
753                 suptrait_constr = ""
754                 for suparg in var[2]:
755                     if isinstance(suparg, ConvInfo):
756                         suptrait_constr += ", " + suparg.arg_name
757                     else:
758                         suptrait_constr += ", " + suparg[1] + "_impl"
759                 java_trait_constr += suptrait_constr + ").bindings_instance"
760                 for suparg in var[2]:
761                     if isinstance(suparg, ConvInfo):
762                         java_trait_constr += ", " + suparg.arg_name
763                     else:
764                         java_trait_constr += ", " + suparg[1] + ".new_impl("
765                         # Blindly assume that we can just strip the first arg to build the args for the supertrait
766                         java_trait_constr += suptrait_constr.split(", ", 1)[1]
767                         java_trait_constr += ").bindings_instance"
768         out_java_trait += "\t}\n" + java_trait_wrapper + "\n"
769         out_java_trait += java_trait_constr + ");\n\t\treturn impl_holder.held;\n\t}\n"
770
771         out_java += "\t}\n"
772
773         out_java += self.native_meth_decl(struct_name + "_new", "long") + "(" + struct_name + " impl"
774         for var in flattened_field_vars:
775             if isinstance(var, ConvInfo):
776                 out_java += ", " + var.java_ty + " " + var.arg_name
777             else:
778                 out_java += ", " + var[0] + " " + var[1]
779         out_java += ");\n"
780
781         # Now that we've written out our java code (and created java_meths), generate C
782         out_c = "typedef struct " + struct_name + "_JCalls {\n"
783         out_c = out_c + "\tatomic_size_t refcnt;\n"
784         out_c = out_c + "\tJavaVM *vm;\n"
785         out_c = out_c + "\tjweak o;\n"
786         for var in flattened_field_vars:
787             if isinstance(var, ConvInfo):
788                 # We're a regular ol' field
789                 pass
790             else:
791                 # We're a supertrait
792                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
793         for fn in field_fns:
794             if fn.fn_name != "free" and fn.fn_name != "cloned":
795                 out_c = out_c + "\tjmethodID " + fn.fn_name + "_meth;\n"
796         out_c = out_c + "} " + struct_name + "_JCalls;\n"
797
798         for fn_line in field_fns:
799             if fn_line.fn_name == "free":
800                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
801                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
802                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
803                 out_c = out_c + "\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n"
804                 out_c = out_c + "\t\tFREE(j_calls);\n"
805                 out_c = out_c + "\t}\n}\n"
806
807         for idx, fn_line in enumerate(field_fns):
808             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
809                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
810                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
811                 if fn_line.self_is_const:
812                     out_c = out_c + "const void* this_arg"
813                 else:
814                     out_c = out_c + "void* this_arg"
815
816                 for idx, arg in enumerate(fn_line.args_ty):
817                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
818
819                 out_c = out_c + ") {\n"
820                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
821
822                 for arg_info in fn_line.args_ty:
823                     if arg_info.ret_conv is not None:
824                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
825                         out_c = out_c + arg_info.arg_name
826                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
827
828                 out_c = out_c + "\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tCHECK(obj != NULL);\n"
829                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
830                     out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " ret = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
831                 elif fn_line.ret_ty_info.c_ty == "void":
832                     out_c += "\t(*env)->CallVoidMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
833                 elif fn_line.ret_ty_info.java_hu_ty == "string" or "org/ldk/enums" in fn_line.ret_ty_info.java_fn_ty_arg:
834                     # Manually write out string methods as they're just an Object
835                     out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
836                 elif not fn_line.ret_ty_info.passed_as_ptr:
837                     out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (*env)->Call" + fn_line.ret_ty_info.java_ty.title() + "Method(env, obj, j_calls->" + fn_line.fn_name + "_meth"
838                 else:
839                     out_c = out_c + "\tuint64_t ret = (*env)->CallLongMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
840
841                 for idx, arg_info in enumerate(fn_line.args_ty):
842                     if arg_info.ret_conv is not None:
843                         out_c = out_c + ", " + arg_info.ret_conv_name
844                     else:
845                         out_c = out_c + ", " + arg_info.arg_name
846                 out_c = out_c + ");\n"
847
848                 out_c += "\tif (UNLIKELY((*env)->ExceptionCheck(env))) {\n"
849                 out_c += "\t\t(*env)->ExceptionDescribe(env);\n"
850                 out_c += "\t\t(*env)->FatalError(env, \"A call to " + fn_line.fn_name + " in " + struct_name + " from rust threw an exception.\");\n"
851                 out_c += "\t}\n"
852
853                 if fn_line.ret_ty_info.arg_conv is not None:
854                     out_c += "\t" + fn_line.ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n"
855                     out_c += "\treturn " + fn_line.ret_ty_info.arg_conv_name + ";\n"
856                 else:
857                     if not fn_line.ret_ty_info.passed_as_ptr and fn_line.ret_ty_info.c_ty != "void":
858                         out_c += "\treturn ret;\n"
859
860                 out_c = out_c + "}\n"
861
862         # If we can, write out a clone function whether we need one or not, as we use them in moving to rust
863         can_clone_with_ptr = True
864         for var in field_vars:
865             if isinstance(var, ConvInfo):
866                 can_clone_with_ptr = False
867         if can_clone_with_ptr:
868             out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
869             out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
870             out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
871             for var in field_vars:
872                 if not isinstance(var, ConvInfo):
873                     out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
874             out_c = out_c + "}\n"
875
876         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (" + self.c_fn_args_pfx + ", jobject o"
877         for var in flattened_field_vars:
878             if isinstance(var, ConvInfo):
879                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
880             else:
881                 out_c = out_c + ", jobject " + var[1]
882         out_c = out_c + ") {\n"
883
884         out_c = out_c + "\tjclass c = (*env)->GetObjectClass(env, o);\n"
885         out_c = out_c + "\tCHECK(c != NULL);\n"
886         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
887         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
888         out_c = out_c + "\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n"
889         out_c = out_c + "\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n"
890
891         for (fn_name, java_meth_descr) in java_meths:
892             if fn_name != "free" and fn_name != "cloned":
893                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
894                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
895
896         for var in flattened_field_vars:
897             if isinstance(var, ConvInfo) and var.arg_conv is not None:
898                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
899         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
900         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
901         for fn_line in field_fns:
902             if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
903                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
904             elif fn_line.fn_name == "free":
905                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
906             else:
907                 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
908         for var in field_vars:
909             if isinstance(var, ConvInfo):
910                 if var.arg_conv_name is not None:
911                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
912                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
913                 else:
914                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
915                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
916             else:
917                 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(env, clz, " + var[1]
918                 for suparg in var[2]:
919                     if isinstance(suparg, ConvInfo):
920                         out_c = out_c + ", " + suparg.arg_name
921                     else:
922                         out_c = out_c + ", " + suparg[1]
923                 out_c += "),\n"
924         out_c = out_c + "\t};\n"
925         for var in flattened_field_vars:
926             if not isinstance(var, ConvInfo):
927                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
928         out_c = out_c + "\treturn ret;\n"
929         out_c = out_c + "}\n"
930
931         out_c += "int64_t " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "jobject o"
932         for var in flattened_field_vars:
933             if isinstance(var, ConvInfo):
934                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
935             else:
936                 out_c = out_c + ", jobject " + var[1]
937         out_c = out_c + ") {\n"
938         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
939         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(env, clz, o"
940         for var in flattened_field_vars:
941             if isinstance(var, ConvInfo):
942                 out_c = out_c + ", " + var.arg_name
943             else:
944                 out_c = out_c + ", " + var[1]
945         out_c = out_c + ");\n"
946         out_c = out_c + "\treturn tag_ptr(res_ptr, true);\n"
947         out_c = out_c + "}\n"
948
949         for var in flattened_field_vars:
950             if not isinstance(var, ConvInfo):
951                 out_java_trait += "\n\t/**\n"
952                 out_java_trait += "\t * Gets the underlying " + var[1] + ".\n"
953                 out_java_trait += "\t */\n"
954                 underscore_name = ''.join('_' + c.lower() if c.isupper() else c for c in var[1]).strip('_')
955                 out_java_trait += "\tpublic " + var[1] + " get_" + underscore_name + "() {\n"
956                 out_java_trait += "\t\t" + var[1] + " res = new " + var[1] + "(null, bindings." + struct_name + "_get_" + var[1] + "(this.ptr));\n"
957                 out_java_trait += "\t\tthis.ptrs_to.AddLast(res);\n"
958                 out_java_trait += "\t\treturn res;\n"
959                 out_java_trait += "\t}\n"
960                 out_java_trait += "\n"
961
962                 out_java += self.native_meth_decl(struct_name + "_get_" + var[1], "long") + "(long arg);\n"
963
964                 out_c += "int64_t " + self.c_fn_name_define_pfx(struct_name + "_get_" + var[1], True) + "int64_t arg) {\n"
965                 out_c += "\t" + struct_name + " *inp = (" + struct_name + " *)untag_ptr(arg);\n"
966                 out_c += "\treturn tag_ptr(&inp->" + var[1] + ", false);\n"
967                 out_c += "}\n"
968
969         return (out_java, out_java_trait, out_c)
970
971     def trait_struct_inc_refcnt(self, ty_info):
972         base_conv = "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
973         base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
974         base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_cloned(&" + ty_info.var_name + "_conv);\n}"
975         return base_conv
976
977     def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
978         bindings_type = struct_name.replace("LDK", "")
979         java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
980
981         out_java_enum = ""
982         out_java = ""
983         out_c = ""
984
985         out_java_enum += (self.hu_struct_file_prefix)
986
987         java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
988         java_hu_class += "public class " + java_hu_type + " : CommonBase {\n"
989         java_hu_class += f"\tprotected {java_hu_type}(object _dummy, long ptr) : base(ptr)" + " { }\n"
990         java_hu_class += "\t~" + java_hu_type + "() {\n"
991         java_hu_class += "\t\tif (ptr != 0) { bindings." + bindings_type + "_free(ptr); }\n"
992         java_hu_class += "\t}\n\n"
993         java_hu_class += f"\tinternal static {java_hu_type} constr_from_ptr(long ptr) {{\n"
994         java_hu_class += f"\t\tlong raw_ty = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
995         out_c += self.c_fn_ty_pfx + "uint32_t" + self.c_fn_name_define_pfx(struct_name + "_ty_from_ptr", True) + self.ptr_c_ty + " ptr) {\n"
996         out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
997         out_c += "\tswitch(obj->tag) {\n"
998         java_hu_class += "\t\tswitch (raw_ty) {\n"
999         java_hu_subclasses = ""
1000
1001         var_idx = 0
1002         for var in variant_list:
1003             java_hu_subclasses += "\t/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1004             java_hu_subclasses += "\tpublic class " + java_hu_type + "_" + var.var_name + " : " + java_hu_type + " {\n"
1005             java_hu_class += f"\t\t\tcase {var_idx}: "
1006             java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1007             out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1008             hu_conv_body = ""
1009             for idx, (field_ty, field_docs) in enumerate(var.fields):
1010                 if field_docs is not None:
1011                     java_hu_subclasses += "\t\t/**\n\t\t * " + field_docs.replace("\n", "\n\t\t * ") + "\n\t\t */\n"
1012                 java_hu_subclasses += f"\t\tpublic {field_ty.java_hu_ty} {field_ty.arg_name};\n"
1013                 if field_ty.to_hu_conv is not None:
1014                     hu_conv_body += f"\t\t\t{field_ty.java_ty} {field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1015                     hu_conv_body += f"\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1016                     hu_conv_body += f"\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1017                 else:
1018                     hu_conv_body += f"\t\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1019             java_hu_subclasses += "\t\tinternal " + java_hu_type + "_" + var.var_name + "(long ptr) : base(null, ptr) {\n"
1020             java_hu_subclasses += hu_conv_body
1021             java_hu_subclasses += "\t\t}\n\t}\n"
1022             var_idx += 1
1023         java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new ArgumentException(\"Impossible enum variant\");\n\t\t}\n\t}\n\n"
1024         out_java += self.native_meth_decl(struct_name + "_ty_from_ptr", "long") + "(long ptr);\n"
1025         out_c += ("\t\tdefault: abort();\n")
1026         out_c += ("\t}\n}\n")
1027
1028         for var in variant_list:
1029             for idx, (field_map, _) in enumerate(var.fields):
1030                 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1031                 out_c += self.c_fn_ty_pfx + field_map.c_ty + self.c_fn_name_define_pfx(fn_name, True) + self.ptr_c_ty + " ptr) {\n"
1032                 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)untag_ptr(ptr);\n"
1033                 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1034                 if field_map.ret_conv is not None:
1035                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1036                     if var.tuple_variant:
1037                         out_c += "obj->" + camel_to_snake(var.var_name)
1038                     else:
1039                         out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1040                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1041                     out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1042                 else:
1043                     if var.tuple_variant:
1044                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1045                     else:
1046                         out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1047                 out_c += "}\n"
1048                 out_java += self.native_meth_decl(fn_name, field_map.java_ty) + "(long ptr);\n"
1049         out_java_enum += java_hu_class
1050         out_java_enum += java_hu_subclasses
1051         return (out_java, out_java_enum, out_c)
1052
1053     def map_opaque_struct(self, struct_name, struct_doc_comment):
1054         out_opaque_struct_human = ""
1055         out_opaque_struct_human += self.hu_struct_file_prefix
1056         out_opaque_struct_human += "\n/**\n * " + struct_doc_comment.replace("\n", "\n * ") + "\n */\n"
1057         hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1058         out_opaque_struct_human += ("public class " + hu_name + " : CommonBase")
1059         if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1060             out_opaque_struct_human += (", IDisposable")
1061         out_opaque_struct_human += (" {\n")
1062         out_opaque_struct_human += ("\tinternal " + hu_name + "(object _dummy, long ptr) : base(ptr) { }\n")
1063         if struct_name.startswith("LDKLocked") or struct_name.startswith("LDKReadOnly"):
1064             out_opaque_struct_human += ("\tpublic void Dispose() {\n")
1065         else:
1066             out_opaque_struct_human += ("\t~" + hu_name + "() {\n")
1067         out_opaque_struct_human += ("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1068         out_opaque_struct_human += ("\t}\n\n")
1069         return out_opaque_struct_human
1070
1071     def map_tuple(self, struct_name):
1072         return self.map_opaque_struct(struct_name, "A Tuple")
1073
1074     def map_result(self, struct_name, res_map, err_map):
1075         human_ty = struct_name.replace("LDKCResult", "Result")
1076         java_hu_struct = ""
1077         java_hu_struct += self.hu_struct_file_prefix
1078         java_hu_struct += "public class " + human_ty + " : CommonBase {\n"
1079         java_hu_struct += "\t" + human_ty + "(object _dummy, long ptr) : base(ptr) { }\n"
1080         java_hu_struct += "\t~" + human_ty + "() {\n"
1081         java_hu_struct += "\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n"
1082         java_hu_struct += "\t}\n\n"
1083         java_hu_struct += "\tinternal static " + human_ty + " constr_from_ptr(long ptr) {\n"
1084         java_hu_struct += "\t\tif (bindings." + struct_name.replace("LDK", "") + "_is_ok(ptr)) {\n"
1085         java_hu_struct += "\t\t\treturn new " + human_ty + "_OK(null, ptr);\n"
1086         java_hu_struct += "\t\t} else {\n"
1087         java_hu_struct += "\t\t\treturn new " + human_ty + "_Err(null, ptr);\n"
1088         java_hu_struct += "\t\t}\n"
1089         java_hu_struct += "\t}\n"
1090
1091         java_hu_struct += "\tpublic class " + human_ty + "_OK : " + human_ty + " {\n"
1092
1093         if res_map.java_hu_ty != "void":
1094             java_hu_struct += "\t\tpublic readonly " + res_map.java_hu_ty + " res;\n"
1095         java_hu_struct += "\t\tinternal " + human_ty + "_OK(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1096         if res_map.java_hu_ty == "void":
1097             pass
1098         elif res_map.to_hu_conv is not None:
1099             java_hu_struct += "\t\t\t" + res_map.java_ty + " res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1100             java_hu_struct += "\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t")
1101             java_hu_struct += "\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1102         else:
1103             java_hu_struct += "\t\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1104         java_hu_struct += "\t\t}\n"
1105         java_hu_struct += "\t}\n\n"
1106
1107         java_hu_struct += "\tpublic class " + human_ty + "_Err : " + human_ty + " {\n"
1108         if err_map.java_hu_ty != "void":
1109             java_hu_struct += "\t\tpublic readonly " + err_map.java_hu_ty + " err;\n"
1110         java_hu_struct += "\t\tinternal " + human_ty + "_Err(object _dummy, long ptr) : base(_dummy, ptr) {\n"
1111         if err_map.java_hu_ty == "void":
1112             pass
1113         elif err_map.to_hu_conv is not None:
1114             java_hu_struct += "\t\t\t" + err_map.java_ty + " err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1115             java_hu_struct += "\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t")
1116             java_hu_struct += "\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1117         else:
1118             java_hu_struct += "\t\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1119         java_hu_struct += "\t\t}\n"
1120
1121         java_hu_struct += "\t}\n\n"
1122         return java_hu_struct
1123
1124     def map_function(self, argument_types, c_call_string, method_name, meth_n, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
1125         arg_name_repl = lambda s, arg_name: s.replace(arg_name, "_" + arg_name) if arg_name == "lock" or arg_name == "event" or arg_name == "params" else s
1126         out_java = ""
1127         out_c = ""
1128         out_java_struct = None
1129
1130         out_java += self.native_meth_decl(method_name, return_type_info.java_ty) + "("
1131         out_c += (return_type_info.c_ty)
1132         if return_type_info.ret_conv is not None:
1133             ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1134         have_args = len(argument_types) > 1 or (len(argument_types) > 0 and argument_types[0].c_ty != "void")
1135         out_c += (" " + self.c_fn_name_define_pfx(method_name, have_args))
1136
1137         for idx, arg_conv_info in enumerate(argument_types):
1138             if idx != 0:
1139                 out_java += (", ")
1140                 out_c += (", ")
1141             if arg_conv_info.c_ty != "void":
1142                 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1143                 if "[]" in arg_conv_info.java_ty:
1144                     out_java += "[MarshalAs(UnmanagedType.CustomMarshaler, MarshalType=\"org.ldk.impl.ArrayCoder\")] "
1145                 out_java += (arg_conv_info.java_ty + " _" + arg_conv_info.arg_name) # Add a _ to avoid using reserved words
1146
1147         out_java_struct = ""
1148         extra_java_struct_out = ""
1149         if not args_known:
1150             out_java_struct += ("\t// Skipped " + method_name + "\n")
1151         else:
1152             if doc_comment is not None:
1153                 out_java_struct += "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1154             hu_ret_ty = return_type_info.java_hu_ty
1155             if return_type_info.nullable:
1156                 #hu_ret_ty += "?" - apparently mono doesn't support the nullable stuff
1157                 pass
1158             if not takes_self:
1159                 if meth_n == "new":
1160                     out_java_struct += "\tpublic static " + hu_ret_ty + " of("
1161                 elif meth_n == "default":
1162                     out_java_struct += "\tpublic static " + hu_ret_ty + " with_default("
1163                 else:
1164                     out_java_struct += "\tpublic static " + hu_ret_ty + " " + meth_n + "("
1165             elif meth_n == "clone_ptr" or (struct_meth.startswith("LDKCResult") and (meth_n == "get_ok" or meth_n == "get_err")):
1166                 out_java_struct += "\tinternal " + hu_ret_ty + " " + meth_n + "("
1167             else:
1168                 if meth_n == "hash" and return_type_info.java_hu_ty == "long":
1169                     extra_java_struct_out = "\tpublic override int GetHashCode() {\n"
1170                     extra_java_struct_out += "\t\treturn (int)this.hash();\n"
1171                     extra_java_struct_out += "\t}\n"
1172                 elif meth_n == "eq" and return_type_info.java_hu_ty == "bool":
1173                     extra_java_struct_out = "\tpublic override bool Equals(object o) {\n"
1174                     extra_java_struct_out += "\t\tif (!(o is " + struct_meth + ")) return false;\n"
1175                     extra_java_struct_out += "\t\treturn this.eq((" + struct_meth + ")o);\n"
1176                     extra_java_struct_out += "\t}\n"
1177                 if meth_n == "lock":
1178                     out_java_struct += "\tpublic " + hu_ret_ty + " do_lock("
1179                 else:
1180                     out_java_struct += "\tpublic " + hu_ret_ty + " " + meth_n + "("
1181             for idx, arg in enumerate(argument_types):
1182                 if idx != 0:
1183                     if not takes_self or idx > 1:
1184                         out_java_struct += ", "
1185                 elif takes_self:
1186                     continue
1187                 if arg.java_ty != "void":
1188                     if arg.arg_name in default_constructor_args:
1189                         assert not arg.nullable
1190                         for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1191                             if explode_idx != 0:
1192                                 out_java_struct += (", ")
1193                             out_java_struct += (
1194                                 explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
1195                     else:
1196                         ty_string = arg.java_hu_ty
1197                         if arg.nullable:
1198                             #ty_string += "?" - apparently mono doesn't support the nullable stuff
1199                             pass
1200                         ty_string = self.fully_qualified_hu_ty_path(arg)
1201                         out_java_struct += ty_string + " " + arg_name_repl(arg.arg_name, arg.arg_name)
1202         out_java += (");\n")
1203         out_c += (") {\n")
1204         if out_java_struct is not None:
1205             out_java_struct += (") {\n")
1206         for info in argument_types:
1207             if info.arg_conv is not None:
1208                 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1209         if return_type_info.ret_conv is not None:
1210             out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1211         elif return_type_info.c_ty != "void":
1212             out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1213         else:
1214             out_c += ("\t")
1215         if c_call_string is None:
1216             out_c += (method_name + "(")
1217         else:
1218             out_c += (c_call_string)
1219         for idx, info in enumerate(argument_types):
1220             if info.arg_conv_name is not None:
1221                 if idx != 0:
1222                     out_c += (", ")
1223                 elif c_call_string is not None:
1224                     continue
1225                 out_c += (info.arg_conv_name)
1226         out_c += (")")
1227         if return_type_info.ret_conv is not None:
1228             out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1229         else:
1230             out_c += (";")
1231         for info in argument_types:
1232             if info.arg_conv_cleanup is not None:
1233                 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1234         if return_type_info.ret_conv is not None:
1235             out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1236         elif return_type_info.c_ty != "void":
1237             out_c += ("\n\treturn ret_val;")
1238         out_c += ("\n}\n\n")
1239
1240         if args_known:
1241             out_java_struct += ("\t\t")
1242             if return_type_info.java_ty != "void":
1243                 out_java_struct += (return_type_info.java_ty + " ret = ")
1244             out_java_struct += ("bindings." + method_name + "(")
1245             for idx, info in enumerate(argument_types):
1246                 if idx != 0:
1247                     out_java_struct += (", ")
1248                 if idx == 0 and takes_self:
1249                     out_java_struct += ("this.ptr")
1250                 elif info.arg_name in default_constructor_args:
1251                     out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1252                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1253                         if explode_idx != 0:
1254                             out_java_struct += (", ")
1255                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1256                         if explode_arg.from_hu_conv is not None:
1257                             out_java_struct += (
1258                                 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1259                         else:
1260                             out_java_struct += (expl_arg_name)
1261                     out_java_struct += (")")
1262                 elif info.from_hu_conv is not None:
1263                     out_java_struct += arg_name_repl(info.from_hu_conv[0], info.arg_name)
1264                 else:
1265                     out_java_struct += arg_name_repl(info.arg_name, info.arg_name)
1266             out_java_struct += (");\n")
1267
1268             # Like Java, the C# GC is quite aggressive and can finalize an object while a method
1269             # on it is operating. Unlike Java, this behavior appears to be better documented,
1270             # which is nice.
1271             for idx, info in enumerate(argument_types):
1272                 if idx == 0 and takes_self:
1273                     out_java_struct += ("\t\tGC.KeepAlive(this);\n")
1274                 elif info.arg_name in default_constructor_args:
1275                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1276                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1277                         out_java_struct += ("\t\tGC.KeepAlive(" + expl_arg_name + ");\n")
1278                 elif info.c_ty != "void":
1279                     out_java_struct += ("\t\tGC.KeepAlive(" + arg_name_repl(info.arg_name, info.arg_name) + ");\n")
1280
1281             if return_type_info.java_ty == "long" and return_type_info.java_hu_ty != "long":
1282                 out_java_struct += "\t\tif (ret >= 0 && ret <= 4096) { return null; }\n"
1283
1284             if return_type_info.to_hu_conv is not None:
1285                 if not takes_self:
1286                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t")
1287                         .replace("this", return_type_info.to_hu_conv_name) + "\n")
1288                 else:
1289                     out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1290
1291             for idx, info in enumerate(argument_types):
1292                 if idx == 0 and takes_self:
1293                     pass
1294                 elif info.arg_name in default_constructor_args:
1295                     for explode_arg in default_constructor_args[info.arg_name]:
1296                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1297                         if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1298                             out_java_struct += ("\t\t" +
1299                                 arg_name_repl(explode_arg.from_hu_conv[1], info.arg_name)
1300                                 .replace(explode_arg.arg_name, expl_arg_name)
1301                                 .replace("this", return_type_info.to_hu_conv_name) + ";\n")
1302                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1303                     if not takes_self and return_type_info.to_hu_conv_name is not None:
1304                         out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1305                             .replace("this", return_type_info.to_hu_conv_name)
1306                             .replace("\n", "\n\t\t") + ";\n")
1307                     else:
1308                         out_java_struct += ("\t\t" + arg_name_repl(info.from_hu_conv[1], info.arg_name)
1309                             .replace("\n", "\n\t\t") + ";\n")
1310
1311             if takes_self and not takes_self_as_ref:
1312                 out_java_struct += "\t\t" + argument_types[0].from_hu_conv[1].replace("\n", "\n\t\t").replace("this_arg", "this") + ";\n"
1313             if return_type_info.to_hu_conv_name is not None:
1314                 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1315             elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1316                 out_java_struct += ("\t\treturn ret;\n")
1317             out_java_struct += ("\t}\n\n")
1318
1319         return (out_java, out_c, out_java_struct + extra_java_struct_out)
1320
1321     def cleanup(self):
1322         pass