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