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