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