Walk back some of the clone updates, with comments to fix later
[ldk-java] / genbindings.py
1 #!/usr/bin/env python3
2 import sys, re
3
4 if len(sys.argv) != 6:
5     print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /path/to/bindings/ /path/to/bindings/output.c debug")
6     print("debug should be true or false and indicates whether to track allocations and ensure we don't leak")
7     sys.exit(1)
8
9 hu_struct_file_prefix = """package org.ldk.structs;
10
11 import org.ldk.impl.bindings;
12 import org.ldk.enums.*;
13 import org.ldk.util.*;
14 import java.util.Arrays;
15
16 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
17 """
18
19 c_file_pfx = """#include \"org_ldk_impl_bindings.h\"
20 #include <rust_types.h>
21 #include <lightning.h>
22 #include <string.h>
23 #include <stdatomic.h>
24 """
25
26 if sys.argv[5] == "false":
27     c_file_pfx = c_file_pfx + """#define MALLOC(a, _) malloc(a)
28 #define FREE(p) if ((long)(p) > 1024) { free(p); }
29 #define DO_ASSERT(a) (void)(a)
30 #define CHECK(a)
31 """
32 else:
33     c_file_pfx = c_file_pfx + """#include <assert.h>
34 // Always run a, then assert it is true:
35 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
36 // Assert a is true or do nothing
37 #define CHECK(a) DO_ASSERT(a)
38
39 // Running a leak check across all the allocations and frees of the JDK is a mess,
40 // so instead we implement our own naive leak checker here, relying on the -wrap
41 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
42 // and free'd in Rust or C across the generated bindings shared library.
43 #include <threads.h>
44 #include <execinfo.h>
45 #include <unistd.h>
46 static mtx_t allocation_mtx;
47
48 void __attribute__((constructor)) init_mtx() {
49         DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
50 }
51
52 #define BT_MAX 128
53 typedef struct allocation {
54         struct allocation* next;
55         void* ptr;
56         const char* struct_name;
57         void* bt[BT_MAX];
58         int bt_len;
59 } allocation;
60 static allocation* allocation_ll = NULL;
61
62 void* __real_malloc(size_t len);
63 void* __real_calloc(size_t nmemb, size_t len);
64 static void new_allocation(void* res, const char* struct_name) {
65         allocation* new_alloc = __real_malloc(sizeof(allocation));
66         new_alloc->ptr = res;
67         new_alloc->struct_name = struct_name;
68         new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
69         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
70         new_alloc->next = allocation_ll;
71         allocation_ll = new_alloc;
72         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
73 }
74 static void* MALLOC(size_t len, const char* struct_name) {
75         void* res = __real_malloc(len);
76         new_allocation(res, struct_name);
77         return res;
78 }
79 void __real_free(void* ptr);
80 static void alloc_freed(void* ptr) {
81         allocation* p = NULL;
82         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
83         allocation* it = allocation_ll;
84         while (it->ptr != ptr) {
85                 p = it; it = it->next;
86                 if (it == NULL) {
87                         fprintf(stderr, "Tried to free unknown pointer %p at:\\n", ptr);
88                         void* bt[BT_MAX];
89                         int bt_len = backtrace(bt, BT_MAX);
90                         backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
91                         fprintf(stderr, "\\n\\n");
92                         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
93                         return; // addrsan should catch malloc-unknown and print more info than we have
94                 }
95         }
96         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
97         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
98         DO_ASSERT(it->ptr == ptr);
99         __real_free(it);
100 }
101 static void FREE(void* ptr) {
102         if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
103         alloc_freed(ptr);
104         __real_free(ptr);
105 }
106
107 void* __wrap_malloc(size_t len) {
108         void* res = __real_malloc(len);
109         new_allocation(res, "malloc call");
110         return res;
111 }
112 void* __wrap_calloc(size_t nmemb, size_t len) {
113         void* res = __real_calloc(nmemb, len);
114         new_allocation(res, "calloc call");
115         return res;
116 }
117 void __wrap_free(void* ptr) {
118         if (ptr == NULL) return;
119         alloc_freed(ptr);
120         __real_free(ptr);
121 }
122
123 void* __real_realloc(void* ptr, size_t newlen);
124 void* __wrap_realloc(void* ptr, size_t len) {
125         if (ptr != NULL) alloc_freed(ptr);
126         void* res = __real_realloc(ptr, len);
127         new_allocation(res, "realloc call");
128         return res;
129 }
130 void __wrap_reallocarray(void* ptr, size_t new_sz) {
131         // Rust doesn't seem to use reallocarray currently
132         assert(false);
133 }
134
135 void __attribute__((destructor)) check_leaks() {
136         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
137                 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
138                 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
139                 fprintf(stderr, "\\n\\n");
140         }
141         DO_ASSERT(allocation_ll == NULL);
142 }
143 """
144
145 c_file = ""
146 def write_c(s):
147     global c_file
148     c_file += s
149
150 class TypeInfo:
151     def __init__(self, is_native_primitive, rust_obj, java_ty, java_fn_ty_arg, java_hu_ty, c_ty, passed_as_ptr, is_ptr, var_name, arr_len, arr_access, subty=None):
152         self.is_native_primitive = is_native_primitive
153         self.rust_obj = rust_obj
154         self.java_ty = java_ty
155         self.java_hu_ty = java_hu_ty
156         self.java_fn_ty_arg = java_fn_ty_arg
157         self.c_ty = c_ty
158         self.passed_as_ptr = passed_as_ptr
159         self.is_ptr = is_ptr
160         self.var_name = var_name
161         self.arr_len = arr_len
162         self.arr_access = arr_access
163         self.subty = subty
164         self.pass_by_ref = is_ptr
165         self.requires_clone = None
166
167 class ConvInfo:
168     def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, arg_conv_cleanup, ret_conv, ret_conv_name, to_hu_conv, to_hu_conv_name, from_hu_conv):
169         assert(ty_info.c_ty is not None)
170         assert(ty_info.java_ty is not None)
171         assert(arg_name is not None)
172         self.passed_as_ptr = ty_info.passed_as_ptr
173         self.rust_obj = ty_info.rust_obj
174         self.c_ty = ty_info.c_ty
175         self.java_ty = ty_info.java_ty
176         self.java_hu_ty = ty_info.java_hu_ty
177         self.java_fn_ty_arg = ty_info.java_fn_ty_arg
178         self.is_native_primitive = ty_info.is_native_primitive
179         self.arg_name = arg_name
180         self.arg_conv = arg_conv
181         self.arg_conv_name = arg_conv_name
182         self.arg_conv_cleanup = arg_conv_cleanup
183         self.ret_conv = ret_conv
184         self.ret_conv_name = ret_conv_name
185         self.to_hu_conv = to_hu_conv
186         self.to_hu_conv_name = to_hu_conv_name
187         self.from_hu_conv = from_hu_conv
188
189     def print_ty(self):
190         write_c(self.c_ty)
191         out_java.write(self.java_ty)
192
193     def print_name(self):
194         if self.arg_name != "":
195             out_java.write(" " + self.arg_name)
196             write_c(" " + self.arg_name)
197         else:
198             out_java.write(" arg")
199             write_c(" arg")
200
201 def camel_to_snake(s):
202     # Convert camel case to snake case, in a way that appears to match cbindgen
203     con = "_"
204     ret = ""
205     lastchar = ""
206     lastund = False
207     for char in s:
208         if lastchar.isupper():
209             if not char.isupper() and not lastund:
210                 ret = ret + "_"
211                 lastund = True
212             else:
213                 lastund = False
214             ret = ret + lastchar.lower()
215         else:
216             ret = ret + lastchar
217             if char.isupper() and not lastund:
218                 ret = ret + "_"
219                 lastund = True
220             else:
221                 lastund = False
222         lastchar = char
223         if char.isnumeric():
224             lastund = True
225     return (ret + lastchar.lower()).strip("_")
226
227 unitary_enums = set()
228 complex_enums = set()
229 opaque_structs = set()
230 trait_structs = set()
231 result_types = set()
232 tuple_types = {}
233
234 var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([a-z0-9]*)\]")
235 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
236 java_c_types_none_allowed = True # Unset when we do the real pass that populates the above sets
237 def java_c_types(fn_arg, ret_arr_len):
238     fn_arg = fn_arg.strip()
239     if fn_arg.startswith("MUST_USE_RES "):
240         fn_arg = fn_arg[13:]
241     is_const = False
242     if fn_arg.startswith("const "):
243         fn_arg = fn_arg[6:]
244         is_const = True
245     if fn_arg.startswith("struct "):
246         fn_arg = fn_arg[7:]
247     if fn_arg.startswith("enum "):
248         fn_arg = fn_arg[5:]
249     fn_arg = fn_arg.replace("NONNULL_PTR", "")
250
251     is_ptr = False
252     take_by_ptr = False
253     rust_obj = None
254     arr_access = None
255     java_hu_ty = None
256     if fn_arg.startswith("LDKThirtyTwoBytes"):
257         fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
258         assert var_is_arr_regex.match(fn_arg[8:])
259         rust_obj = "LDKThirtyTwoBytes"
260         arr_access = "data"
261     elif fn_arg.startswith("LDKPublicKey"):
262         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
263         assert var_is_arr_regex.match(fn_arg[8:])
264         rust_obj = "LDKPublicKey"
265         arr_access = "compressed_form"
266     elif fn_arg.startswith("LDKSecretKey"):
267         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
268         assert var_is_arr_regex.match(fn_arg[8:])
269         rust_obj = "LDKSecretKey"
270         arr_access = "bytes"
271     elif fn_arg.startswith("LDKSignature"):
272         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
273         assert var_is_arr_regex.match(fn_arg[8:])
274         rust_obj = "LDKSignature"
275         arr_access = "compact_form"
276     elif fn_arg.startswith("LDKThreeBytes"):
277         fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
278         assert var_is_arr_regex.match(fn_arg[8:])
279         rust_obj = "LDKThreeBytes"
280         arr_access = "data"
281     elif fn_arg.startswith("LDKFourBytes"):
282         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[4]"
283         assert var_is_arr_regex.match(fn_arg[8:])
284         rust_obj = "LDKFourBytes"
285         arr_access = "data"
286     elif fn_arg.startswith("LDKSixteenBytes"):
287         fn_arg = "uint8_t (*" + fn_arg[16:] + ")[16]"
288         assert var_is_arr_regex.match(fn_arg[8:])
289         rust_obj = "LDKSixteenBytes"
290         arr_access = "data"
291     elif fn_arg.startswith("LDKTenBytes"):
292         fn_arg = "uint8_t (*" + fn_arg[12:] + ")[10]"
293         assert var_is_arr_regex.match(fn_arg[8:])
294         rust_obj = "LDKTenBytes"
295         arr_access = "data"
296     elif fn_arg.startswith("LDKu8slice"):
297         fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
298         assert var_is_arr_regex.match(fn_arg[8:])
299         rust_obj = "LDKu8slice"
300         arr_access = "data"
301     elif fn_arg.startswith("LDKCVec_u8Z"):
302         fn_arg = "uint8_t (*" + fn_arg[12:] + ")[datalen]"
303         rust_obj = "LDKCVec_u8Z"
304         assert var_is_arr_regex.match(fn_arg[8:])
305         arr_access = "data"
306     elif fn_arg.startswith("LDKTransaction"):
307         fn_arg = "uint8_t (*" + fn_arg[15:] + ")[datalen]"
308         rust_obj = "LDKTransaction"
309         assert var_is_arr_regex.match(fn_arg[8:])
310         arr_access = "data"
311     elif fn_arg.startswith("LDKCVec_"):
312         is_ptr = False
313         if "*" in fn_arg:
314             fn_arg = fn_arg.replace("*", "")
315             is_ptr = True
316
317         tyn = fn_arg[8:].split(" ")
318         assert tyn[0].endswith("Z")
319         if tyn[0] == "u64Z":
320             new_arg = "uint64_t"
321         else:
322             new_arg = "LDK" + tyn[0][:-1]
323         for a in tyn[1:]:
324             new_arg = new_arg + " " + a
325         res = java_c_types(new_arg, ret_arr_len)
326         if res is None:
327             assert java_c_types_none_allowed
328             return None
329         if is_ptr:
330             res.pass_by_ref = True
331         if res.is_native_primitive or res.passed_as_ptr:
332             return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
333                 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=res.c_ty + "Array", passed_as_ptr=False, is_ptr=is_ptr,
334                 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
335         else:
336             return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
337                 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty="jobjectArray", passed_as_ptr=False, is_ptr=is_ptr,
338                 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
339
340     is_primitive = False
341     arr_len = None
342     if fn_arg.startswith("void"):
343         java_ty = "void"
344         c_ty = "void"
345         fn_ty_arg = "V"
346         fn_arg = fn_arg[4:].strip()
347         is_primitive = True
348     elif fn_arg.startswith("bool"):
349         java_ty = "boolean"
350         c_ty = "jboolean"
351         fn_ty_arg = "Z"
352         fn_arg = fn_arg[4:].strip()
353         is_primitive = True
354     elif fn_arg.startswith("uint8_t"):
355         java_ty = "byte"
356         c_ty = "jbyte"
357         fn_ty_arg = "B"
358         fn_arg = fn_arg[7:].strip()
359         is_primitive = True
360     elif fn_arg.startswith("uint16_t"):
361         java_ty = "short"
362         c_ty = "jshort"
363         fn_ty_arg = "S"
364         fn_arg = fn_arg[8:].strip()
365         is_primitive = True
366     elif fn_arg.startswith("uint32_t"):
367         java_ty = "int"
368         c_ty = "jint"
369         fn_ty_arg = "I"
370         fn_arg = fn_arg[8:].strip()
371         is_primitive = True
372     elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
373         java_ty = "long"
374         c_ty = "jlong"
375         fn_ty_arg = "J"
376         if fn_arg.startswith("uint64_t"):
377             fn_arg = fn_arg[8:].strip()
378         else:
379             fn_arg = fn_arg[9:].strip()
380         is_primitive = True
381     elif is_const and fn_arg.startswith("char *"):
382         java_ty = "String"
383         c_ty = "const char*"
384         fn_ty_arg = "Ljava/lang/String;"
385         fn_arg = fn_arg[6:].strip()
386     elif fn_arg.startswith("LDKStr"):
387         java_ty = "String"
388         c_ty = "jstring"
389         fn_ty_arg = "Ljava/lang/String;"
390         fn_arg = fn_arg[6:].strip()
391         arr_access = "chars"
392         arr_len = "len"
393     else:
394         ma = var_ty_regex.match(fn_arg)
395         if ma.group(1).strip() in unitary_enums:
396             java_ty = ma.group(1).strip()
397             c_ty = "jclass"
398             fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
399             fn_arg = ma.group(2).strip()
400             rust_obj = ma.group(1).strip()
401             take_by_ptr = True
402         elif ma.group(1).strip().startswith("LDKC2Tuple"):
403             java_ty = "long"
404             java_hu_ty = "TwoTuple<"
405             if not ma.group(1).strip() in tuple_types:
406                 assert java_c_types_none_allowed
407                 return None
408             for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
409                 if idx != 0:
410                     java_hu_ty = java_hu_ty + ", "
411                 if ty_info.is_native_primitive:
412                     if ty_info.java_hu_ty == "int":
413                         java_hu_ty = java_hu_ty + "Integer" # Java concrete integer type is Integer, not Int
414                     else:
415                         java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
416                 else:
417                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty
418             java_hu_ty = java_hu_ty + ">"
419             c_ty = "jlong"
420             fn_ty_arg = "J"
421             fn_arg = ma.group(2).strip()
422             rust_obj = ma.group(1).strip()
423             take_by_ptr = True
424         elif ma.group(1).strip().startswith("LDKC3Tuple"):
425             java_ty = "long"
426             java_hu_ty = "ThreeTuple<"
427             if not ma.group(1).strip() in tuple_types:
428                 assert java_c_types_none_allowed
429                 return None
430             for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
431                 if idx != 0:
432                     java_hu_ty = java_hu_ty + ", "
433                 if ty_info.is_native_primitive:
434                     if ty_info.java_hu_ty == "int":
435                         java_hu_ty = java_hu_ty + "Integer" # Java concrete integer type is Integer, not Int
436                     else:
437                         java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
438                 else:
439                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty
440             java_hu_ty = java_hu_ty + ">"
441             c_ty = "jlong"
442             fn_ty_arg = "J"
443             fn_arg = ma.group(2).strip()
444             rust_obj = ma.group(1).strip()
445             take_by_ptr = True
446         else:
447             java_ty = "long"
448             java_hu_ty = ma.group(1).strip().replace("LDKCResult", "Result").replace("LDK", "")
449             c_ty = "jlong"
450             fn_ty_arg = "J"
451             fn_arg = ma.group(2).strip()
452             rust_obj = ma.group(1).strip()
453             take_by_ptr = True
454
455     if fn_arg.startswith(" *") or fn_arg.startswith("*"):
456         fn_arg = fn_arg.replace("*", "").strip()
457         is_ptr = True
458         c_ty = "jlong"
459         java_ty = "long"
460         fn_ty_arg = "J"
461         is_primitive = False
462
463     var_is_arr = var_is_arr_regex.match(fn_arg)
464     if var_is_arr is not None or ret_arr_len is not None:
465         assert(not take_by_ptr)
466         assert(not is_ptr)
467         java_ty = java_ty + "[]"
468         c_ty = c_ty + "Array"
469         if var_is_arr is not None:
470             if var_is_arr.group(1) == "":
471                 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
472                     passed_as_ptr=False, is_ptr=False, var_name="arg", arr_len=var_is_arr.group(2), arr_access=arr_access, is_native_primitive=False)
473             return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
474                 passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2), arr_access=arr_access, is_native_primitive=False)
475
476     if java_hu_ty is None:
477         java_hu_ty = java_ty
478     return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_hu_ty, java_fn_ty_arg=fn_ty_arg, c_ty=c_ty, passed_as_ptr=is_ptr or take_by_ptr,
479         is_ptr=is_ptr, var_name=fn_arg, arr_len=arr_len, arr_access=arr_access, is_native_primitive=is_primitive)
480
481 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
482 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
483 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
484 clone_fns = set()
485 constructor_fns = {}
486 c_array_class_caches = set()
487 with open(sys.argv[1]) as in_h:
488     for line in in_h:
489         reg_fn = reg_fn_regex.match(line)
490         if reg_fn is not None:
491             if reg_fn.group(2).endswith("_clone"):
492                 clone_fns.add(reg_fn.group(2))
493             else:
494                 rty = java_c_types(reg_fn.group(1), None)
495                 if rty is not None and rty.rust_obj is not None and reg_fn.group(2) == rty.java_hu_ty + "_new":
496                     constructor_fns[rty.rust_obj] = reg_fn.group(3)
497             continue
498         arr_fn = fn_ret_arr_regex.match(line)
499         if arr_fn is not None:
500             if arr_fn.group(2).endswith("_clone"):
501                 clone_fns.add(arr_fn.group(2))
502             # No object constructors return arrays, as then they wouldn't be an object constructor
503             continue
504
505 # Define some manual clones...
506 clone_fns.add("ThirtyTwoBytes_clone")
507 write_c("static inline struct LDKThirtyTwoBytes ThirtyTwoBytes_clone(const struct LDKThirtyTwoBytes *orig) { struct LDKThirtyTwoBytes ret; memcpy(ret.data, orig->data, 32); return ret; }\n")
508
509 java_c_types_none_allowed = False # C structs created by cbindgen are declared in dependency order
510
511 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java:
512     def map_type(fn_arg, print_void, ret_arr_len, is_free, holds_ref):
513         ty_info = java_c_types(fn_arg, ret_arr_len)
514         return map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref)
515
516     def map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref):
517         if ty_info.c_ty == "void":
518             if not print_void:
519                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
520                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
521                     ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
522         if ty_info.c_ty.endswith("Array"):
523             arr_len = ty_info.arr_len
524             if arr_len is not None:
525                 arr_name = ty_info.var_name
526             else:
527                 arr_name = "ret"
528                 arr_len = ret_arr_len
529             if ty_info.c_ty == "jbyteArray":
530                 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", ", "")
531                 arg_conv_cleanup = None
532                 if not arr_len.isdigit():
533                     arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
534                     arg_conv = arg_conv + arr_name + "_ref." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");\n"
535                     if (not ty_info.is_ptr or not holds_ref) and ty_info.rust_obj != "LDKu8slice":
536                         arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = MALLOC(" + arr_name + "_ref." + arr_len + ", \"" + ty_info.rust_obj + " Bytes\");\n"
537                         arg_conv = arg_conv + "(*_env)->GetByteArrayRegion(_env, " + arr_name + ", 0, " + arr_name + "_ref." + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
538                     else:
539                         arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = (*_env)->GetByteArrayElements (_env, " + arr_name + ", NULL);"
540                         arg_conv_cleanup = "(*_env)->ReleaseByteArrayElements(_env, " + arr_name + ", (int8_t*)" + arr_name + "_ref." + ty_info.arr_access + ", 0);"
541                     if ty_info.rust_obj == "LDKTransaction":
542                         arg_conv = arg_conv + "\n" + arr_name + "_ref.data_is_owned = " + str(holds_ref).lower() + ";"
543                     ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
544                     ret_conv = (ret_conv[0], ";\njbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_name + "_var." + arr_len + ");\n")
545                     ret_conv = (ret_conv[0], ret_conv[1] + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_name + "_var." + arr_len + ", " + arr_name + "_var." + ty_info.arr_access + ");")
546                     if not holds_ref and ty_info.rust_obj != "LDKu8slice":
547                         ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
548                 elif ty_info.rust_obj is not None:
549                     arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
550                     arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
551                     arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
552                     ret_conv = (ret_conv[0], "." + ty_info.arr_access + ");")
553                 else:
554                     arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n"
555                     arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
556                     arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
557                     ret_conv = (ret_conv[0] + "*", ");")
558                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
559                     arg_conv = arg_conv, arg_conv_name = arr_name + "_ref", arg_conv_cleanup = arg_conv_cleanup,
560                     ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
561             else:
562                 assert not arr_len.isdigit() # fixed length arrays not implemented
563                 assert ty_info.java_ty[len(ty_info.java_ty) - 2:] == "[]"
564                 conv_name = "arr_conv_" + str(len(ty_info.java_hu_ty))
565                 idxc = chr(ord('a') + (len(ty_info.java_hu_ty) % 26))
566                 ty_info.subty.var_name = conv_name
567                 #XXX: We'd really prefer to only ever set to False, avoiding lots of clone, but need smarter free logic
568                 #if ty_info.is_ptr or holds_ref:
569                 #    ty_info.subty.requires_clone = False
570                 ty_info.subty.requires_clone = not ty_info.is_ptr or not holds_ref
571                 subty = map_type_with_info(ty_info.subty, False, None, is_free, holds_ref)
572                 if arr_name == "":
573                     arr_name = "arg"
574                 arg_conv = ty_info.rust_obj + " " + arr_name + "_constr;\n"
575                 arg_conv = arg_conv + arr_name + "_constr." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");\n"
576                 arg_conv = arg_conv + "if (" + arr_name + "_constr." + arr_len + " > 0)\n"
577                 if subty.rust_obj is None:
578                     szof = subty.c_ty
579                 else:
580                     szof = subty.rust_obj
581                 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = MALLOC(" + arr_name + "_constr." + arr_len + " * sizeof(" + szof + "), \"" + ty_info.rust_obj + " Elements\");\n"
582                 arg_conv = arg_conv + "else\n"
583                 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = NULL;\n"
584                 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
585                     arg_conv = arg_conv + ty_info.java_ty.strip("[]") + "* " + arr_name + "_vals = (*_env)->Get" + ty_info.subty.java_ty.title() + "ArrayElements (_env, " + arr_name + ", NULL);\n"
586                 arg_conv = arg_conv + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_constr." + arr_len + "; " + idxc + "++) {\n"
587                 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
588                     arg_conv = arg_conv + "\t" + ty_info.java_ty.strip("[]") + " " + conv_name + " = " + arr_name + "_vals[" + idxc + "];"
589                     if subty.arg_conv is not None:
590                         arg_conv = arg_conv + "\n\t" + subty.arg_conv.replace("\n", "\n\t")
591                 else:
592                     arg_conv = arg_conv + "\tjobject " + conv_name + " = (*_env)->GetObjectArrayElement(_env, " + arr_name + ", " + idxc + ");\n"
593                     arg_conv = arg_conv + "\t" + subty.arg_conv.replace("\n", "\n\t")
594                 arg_conv = arg_conv + "\n\t" + arr_name + "_constr." + ty_info.arr_access + "[" + idxc + "] = " + subty.arg_conv_name + ";\n}"
595                 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
596                     arg_conv = arg_conv + "\n(*_env)->Release" + ty_info.java_ty.strip("[]").title() + "ArrayElements (_env, " + arr_name + ", " + arr_name + "_vals, 0);"
597                 if ty_info.is_ptr:
598                     arg_conv_name = "&" + arr_name + "_constr"
599                 else:
600                     arg_conv_name = arr_name + "_constr"
601                 arg_conv_cleanup = None
602                 if ty_info.is_ptr:
603                     arg_conv_cleanup = "FREE(" + arr_name + "_constr." + ty_info.arr_access + ");"
604
605                 if arr_name == "arg":
606                     arr_name = "ret"
607                 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
608                 if subty.ret_conv is None:
609                     ret_conv = ("DUMMY", "DUMMY")
610                 elif not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
611                     ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = (*_env)->New" + ty_info.java_ty.strip("[]").title() + "Array(_env, " + arr_name + "_var." + arr_len + ");\n")
612                     ret_conv = (ret_conv[0], ret_conv[1] + subty.c_ty + " *" + arr_name + "_arr_ptr = (*_env)->GetPrimitiveArrayCritical(_env, " + arr_name + "_arr, NULL);\n")
613                     ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
614                     ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
615                     ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
616                     ret_conv = (ret_conv[0], ret_conv[1] + "\n\t" + arr_name + "_arr_ptr[" + idxc + "] = " + subty.ret_conv_name + ";\n")
617                     ret_conv = (ret_conv[0], ret_conv[1] + "}\n(*_env)->ReleasePrimitiveArrayCritical(_env, " + arr_name + "_arr, " + arr_name + "_arr_ptr, 0);")
618                 else:
619                     assert ty_info.java_fn_ty_arg.startswith("[")
620                     clz_var = ty_info.java_fn_ty_arg[1:].replace("[", "arr_of_")
621                     c_array_class_caches.add(clz_var)
622                     ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = (*_env)->NewObjectArray(_env, " + arr_name + "_var." + arr_len + ", " + clz_var + "_clz, NULL);\n")
623                     ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
624                     ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
625                     ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
626                     ret_conv = (ret_conv[0], ret_conv[1] + "\n\t(*_env)->SetObjectArrayElement(_env, " + arr_name + "_arr, " + idxc + ", " + subty.ret_conv_name + ");\n")
627                     ret_conv = (ret_conv[0], ret_conv[1] + "}")
628                 if not holds_ref:
629                     # XXX: The commented if's are a bit smarter freeing, but we need to be a nudge smarter still
630                     # Note that we don't drop the full vec here - we're passing ownership to java (or have cloned) or free'd by now!
631                     ret_conv = (ret_conv[0], ret_conv[1] + "\nFREE(" + arr_name + "_var." + ty_info.arr_access + ");")
632                     #if subty.rust_obj is not None and subty.rust_obj in opaque_structs:
633                     #    ret_conv = (ret_conv[0], ret_conv[1] + "\nFREE(" + arr_name + "_var." + ty_info.arr_access + ");")
634                     #else:
635                     #    ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
636
637                 to_hu_conv = None
638                 to_hu_conv_name = None
639                 if subty.to_hu_conv is not None:
640                     to_hu_conv = ty_info.java_hu_ty + " " + conv_name + "_arr = new " + ty_info.subty.java_hu_ty.split("<")[0] + "[" + arr_name + ".length];\n"
641                     to_hu_conv = to_hu_conv + "for (int " + idxc + " = 0; " + idxc + " < " + arr_name + ".length; " + idxc + "++) {\n"
642                     to_hu_conv = to_hu_conv + "\t" + subty.java_ty + " " + conv_name + " = " + arr_name + "[" + idxc + "];\n"
643                     to_hu_conv = to_hu_conv + "\t" + subty.to_hu_conv.replace("\n", "\n\t") + "\n"
644                     to_hu_conv = to_hu_conv + "\t" + conv_name + "_arr[" + idxc + "] = " + subty.to_hu_conv_name + ";\n}"
645                     to_hu_conv_name = conv_name + "_arr"
646                 from_hu_conv = None
647                 if subty.from_hu_conv is not None:
648                     if subty.java_ty == "long" and subty.java_hu_ty != "long":
649                         from_hu_conv = ("Arrays.stream(" + arr_name + ").mapToLong(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + "  */")
650                     elif subty.java_ty == "long":
651                         from_hu_conv = ("Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + "  */")
652                     else:
653                         from_hu_conv = ("(" + ty_info.java_ty + ")Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + "  */")
654
655                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
656                     arg_conv = arg_conv, arg_conv_name = arg_conv_name, arg_conv_cleanup = arg_conv_cleanup,
657                     ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = to_hu_conv, to_hu_conv_name = to_hu_conv_name, from_hu_conv = from_hu_conv)
658         elif ty_info.java_ty == "String":
659             if ty_info.arr_access is None:
660                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
661                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
662                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv",
663                     to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
664             else:
665                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
666                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
667                     ret_conv = ("LDKStr " + ty_info.var_name + "_str = ",
668                         ";\nchar* " + ty_info.var_name + "_buf = MALLOC(" + ty_info.var_name + "_str." + ty_info.arr_len + " + 1, \"str conv buf\");\n" +
669                         "memcpy(" + ty_info.var_name + "_buf, " + ty_info.var_name + "_str." + ty_info.arr_access + ", " + ty_info.var_name + "_str." + ty_info.arr_len + ");\n" +
670                         ty_info.var_name + "_buf[" + ty_info.var_name + "_str." + ty_info.arr_len + "] = 0;\n" +
671                         "jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, " + ty_info.var_name + "_str." + ty_info.arr_access + ");\n" +
672                         "FREE(" + ty_info.var_name + "_buf);"),
673                     ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
674         elif ty_info.var_name == "" and not print_void:
675             # We don't have a parameter name, and want one, just call it arg
676             if ty_info.rust_obj is not None:
677                 assert(not is_free or ty_info.rust_obj not in opaque_structs)
678                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
679                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
680                     arg_conv_name = "arg_conv", arg_conv_cleanup = None,
681                     ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 7", to_hu_conv_name = None, from_hu_conv = None)
682             else:
683                 assert(not is_free)
684                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
685                     arg_conv = None, arg_conv_name = "arg", arg_conv_cleanup = None,
686                     ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 8", to_hu_conv_name = None, from_hu_conv = None)
687         elif ty_info.rust_obj is None:
688             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
689                 arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None,
690                 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
691         else:
692             if ty_info.var_name == "":
693                 ty_info.var_name = "ret"
694
695             if ty_info.rust_obj in opaque_structs:
696                 opaque_arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv;\n"
697                 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
698                 if ty_info.is_ptr and holds_ref:
699                     opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = false;"
700                 else:
701                     opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
702                 if not is_free and (not ty_info.is_ptr or not holds_ref or ty_info.requires_clone == True) and ty_info.requires_clone != False:
703                     if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
704                         # TODO: This is a bit too naive, even with the checks above, we really need to know if rust wants a ref or not, not just if its pass as a ptr.
705                         opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
706                         opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&" + ty_info.var_name + "_conv);"
707                     elif ty_info.passed_as_ptr:
708                         opaque_arg_conv = opaque_arg_conv + "\n// Warning: we may need a move here but can't clone!"
709
710                 opaque_ret_conv_suf = ";\n"
711                 if not holds_ref and ty_info.is_ptr and (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns: # is_ptr, not holds_ref implies passing a pointed-to value to java, which needs copied
712                     opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "->inner != NULL)\n"
713                     opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_var = " + ty_info.rust_obj.replace("LDK", "") + "_clone(" + ty_info.var_name + ");\n"
714                 elif not holds_ref and ty_info.is_ptr:
715                     opaque_ret_conv_suf = opaque_ret_conv_suf + "// Warning: we may need a move here but can't clone!\n"
716
717                 opaque_ret_conv_suf = opaque_ret_conv_suf + "CHECK((((long)" + ty_info.var_name + "_var.inner) & 1) == 0); // We rely on a free low bit, malloc guarantees this.\n"
718                 opaque_ret_conv_suf = opaque_ret_conv_suf + "CHECK((((long)&" + ty_info.var_name + "_var) & 1) == 0); // We rely on a free low bit, pointer alignment guarantees this.\n"
719                 if holds_ref:
720                     opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner & ~1;"
721                 else:
722                     opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner;\n"
723                     opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "_var.is_owned) {\n"
724                     opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_ref |= 1;\n"
725                     opaque_ret_conv_suf = opaque_ret_conv_suf + "}"
726
727                 if ty_info.is_ptr:
728                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
729                         arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv", arg_conv_cleanup = None,
730                         ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = *", opaque_ret_conv_suf),
731                         ret_conv_name = ty_info.var_name + "_ref",
732                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
733                         to_hu_conv_name = ty_info.var_name + "_hu_conv",
734                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
735                 else:
736                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
737                         arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
738                         ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", opaque_ret_conv_suf),
739                         ret_conv_name = ty_info.var_name + "_ref",
740                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
741                         to_hu_conv_name = ty_info.var_name + "_hu_conv",
742                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
743
744             if not ty_info.is_ptr:
745                 if ty_info.rust_obj in unitary_enums:
746                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
747                         arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
748                         arg_conv_name = ty_info.var_name + "_conv",
749                         arg_conv_cleanup = None,
750                         ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
751                         ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
752                 base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";"
753                 if ty_info.rust_obj in trait_structs:
754                     if not is_free:
755                         needs_full_clone = not is_free and (not ty_info.is_ptr and not holds_ref or ty_info.requires_clone == True) and ty_info.requires_clone != False
756                         if needs_full_clone and (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
757                             base_conv = base_conv + "\n" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(" + ty_info.var_name + ");"
758                         else:
759                             base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
760                             base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
761                             base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
762                             if needs_full_clone:
763                                 base_conv = base_conv + "// Warning: we may need a move here but can't do a full clone!\n"
764
765                     else:
766                         base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
767                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
768                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
769                         ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
770                         ret_conv_name = "(long)ret",
771                         to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");\nret_hu_conv.ptrs_to.add(this);",
772                         to_hu_conv_name = "ret_hu_conv",
773                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
774                 if ty_info.rust_obj != "LDKu8slice":
775                     # Don't bother free'ing slices passed in - Rust doesn't auto-free the
776                     # underlying unlike Vecs, and it gives Java more freedom.
777                     base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
778                 if ty_info.rust_obj in complex_enums:
779                     ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";")
780                     if not holds_ref:
781                         ret_conv = (ty_info.rust_obj + " *" + ty_info.var_name + "_copy = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n", "")
782                         if ty_info.requires_clone == True: # Set in object array mapping
783                             if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
784                                 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&", ");\n")
785                             else:
786                                 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", "; // XXX: We likely need to clone here, but no _clone fn is available!\n")
787                         else:
788                             ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", ";\n")
789                         ret_conv = (ret_conv[0], ret_conv[1] + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_copy;")
790                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
791                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
792                         ret_conv = ret_conv, ret_conv_name = ty_info.var_name + "_ref",
793                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");\n" + ty_info.var_name + "_hu_conv.ptrs_to.add(this);",
794                         to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
795                 if ty_info.rust_obj in result_types:
796                     if holds_ref:
797                         # If we're trying to return a ref, we have to clone.
798                         # We just blindly assume its implemented and let the compiler fail if its not.
799                         ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_conv = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_conv = ", ";")
800                         ret_conv = (ret_conv[0], ret_conv[1] + "\n*" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(" + ty_info.var_name + "_conv);")
801                     else:
802                         ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_conv = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_conv = ", ";")
803                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
804                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
805                         ret_conv = ret_conv, ret_conv_name = "(long)" + ty_info.var_name + "_conv",
806                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");",
807                         to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + " != null ? " + ty_info.var_name + ".ptr : 0", ""))
808                 if ty_info.rust_obj in tuple_types:
809                     from_hu_conv = "bindings." + tuple_types[ty_info.rust_obj][1].replace("LDK", "") + "_new("
810                     to_hu_conv_pfx = ""
811                     to_hu_conv_sfx = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " + ty_info.java_hu_ty + "("
812                     clone_ret_str = ""
813                     for idx, conv in enumerate(tuple_types[ty_info.rust_obj][0]):
814                         if idx != 0:
815                             to_hu_conv_sfx = to_hu_conv_sfx + ", "
816                             from_hu_conv = from_hu_conv + ", "
817                         conv.var_name = ty_info.var_name + "_" + chr(idx + ord("a"))
818                         conv_map = map_type_with_info(conv, False, None, is_free, holds_ref)
819                         to_hu_conv_pfx = to_hu_conv_pfx + conv.java_ty + " " + ty_info.var_name + "_" + chr(idx + ord("a")) + " = " + "bindings." + tuple_types[ty_info.rust_obj][1] + "_get_" + chr(idx + ord("a")) + "(" + ty_info.var_name + ");\n"
820                         if conv_map.to_hu_conv is not None:
821                             to_hu_conv_pfx = to_hu_conv_pfx + conv_map.to_hu_conv + ";\n"
822                             to_hu_conv_sfx = to_hu_conv_sfx + conv_map.to_hu_conv_name
823                         else:
824                             to_hu_conv_sfx = to_hu_conv_sfx + ty_info.var_name + "_" + chr(idx + ord("a"))
825                         if conv_map.from_hu_conv is not None:
826                             from_hu_conv = from_hu_conv + conv_map.from_hu_conv[0].replace(ty_info.var_name + "_" + chr(idx + ord("a")), ty_info.var_name + "." + chr(idx + ord("a")))
827                             if conv_map.from_hu_conv[1] != "":
828                                 from_hu_conv = from_hu_conv + "/*XXX: " + conv_map.from_hu_conv[1] + "*/"
829                         else:
830                             from_hu_conv = from_hu_conv + ty_info.var_name + "." + chr(idx + ord("a"))
831
832                         if conv.is_native_primitive:
833                             pass
834                         elif (conv_map.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
835                             accessor = ty_info.var_name + "_ref->" + chr(idx + ord("a"))
836                             clone_ret_str = clone_ret_str + "\n" + accessor + " = " + conv_map.rust_obj.replace("LDK", "") + "_clone(&" + accessor + ");"
837                         else:
838                             clone_ret_str = clone_ret_str + "\n// XXX: We likely need to clone here, but no _clone fn is available for " + conv_map.java_hu_ty
839                     if not ty_info.is_ptr and not holds_ref:
840                         ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_ref = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_ref = ", ";")
841                         if not is_free and (not ty_info.is_ptr and not holds_ref or ty_info.requires_clone == True) and ty_info.requires_clone != False:
842                             ret_conv = (ret_conv[0], ret_conv[1] + clone_ret_str)
843                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
844                             arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
845                             ret_conv = ret_conv,
846                             ret_conv_name = "(long)" + ty_info.var_name + "_ref",
847                             to_hu_conv = to_hu_conv_pfx + to_hu_conv_sfx + ");", to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (from_hu_conv + ")", ""))
848                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
849                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
850                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
851                         to_hu_conv = to_hu_conv_pfx + to_hu_conv_sfx + ");", to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (from_hu_conv + ")", ""))
852
853                 # The manually-defined types - TxOut and Transaction
854                 assert ty_info.rust_obj == "LDKTxOut"
855                 if not ty_info.is_ptr and not holds_ref:
856                     ret_conv = ("LDKTxOut* " + ty_info.var_name + "_ref = MALLOC(sizeof(LDKTxOut), \"LDKTxOut\");\n*" + ty_info.var_name + "_ref = ", ";")
857                 else:
858                     ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";")
859                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
860                     arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
861                     ret_conv = ret_conv, ret_conv_name = "(long)" + ty_info.var_name + "_ref",
862                     to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " +ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
863                     to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
864             elif ty_info.is_ptr:
865                 assert(not is_free)
866                 if ty_info.rust_obj in complex_enums:
867                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
868                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
869                         arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
870                         ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
871                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");",
872                         to_hu_conv_name = ty_info.var_name + "_hu_conv",
873                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
874                 elif ty_info.rust_obj in trait_structs:
875                     if ty_info.rust_obj.replace("LDK", "") + "_clone" in clone_fns:
876                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
877                             arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
878                             arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
879                             ret_conv = (ty_info.rust_obj + " *" + ty_info.var_name + "_clone = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n" +
880                                 "*" + ty_info.var_name + "_clone = " + ty_info.rust_obj.replace("LDK", "") + "_clone(", ");"),
881                             ret_conv_name = "(long)" + ty_info.var_name + "_clone",
882                             to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");\nret_hu_conv.ptrs_to.add(this);",
883                             to_hu_conv_name = "ret_hu_conv",
884                             from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
885                     else:
886                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
887                             arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
888                             arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
889                             ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
890                             to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");\nret_hu_conv.ptrs_to.add(this);",
891                             to_hu_conv_name = "ret_hu_conv",
892                             from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
893                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
894                     arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
895                     arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
896                     ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
897                     to_hu_conv = "TODO 3", to_hu_conv_name = None, from_hu_conv = None) # its a pointer, no conv needed
898             assert False # We should have handled every case by now.
899
900     def map_fn(line, re_match, ret_arr_len, c_call_string):
901         out_java.write("\t// " + line)
902         out_java.write("\tpublic static native ")
903         write_c("JNIEXPORT ")
904
905         is_free = re_match.group(2).endswith("_free")
906         struct_meth = re_match.group(2).split("_")[0]
907
908         ret_info = map_type(re_match.group(1), True, ret_arr_len, False, False)
909         ret_info.print_ty()
910
911         if ret_info.ret_conv is not None:
912             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
913
914         out_java.write(" " + re_match.group(2) + "(")
915         write_c(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
916
917         arg_names = []
918         default_constructor_args = {}
919         takes_self = False
920         args_known = True
921         for idx, arg in enumerate(re_match.group(3).split(',')):
922             if idx != 0:
923                 out_java.write(", ")
924             if arg != "void":
925                 write_c(", ")
926             arg_conv_info = map_type(arg, False, None, is_free, True)
927             if arg_conv_info.c_ty != "void":
928                 arg_conv_info.print_ty()
929                 arg_conv_info.print_name()
930             if idx == 0 and arg_conv_info.java_hu_ty == struct_meth:
931                 takes_self = True
932             if arg_conv_info.arg_conv is not None and "Warning" in arg_conv_info.arg_conv:
933                 if arg_conv_info.rust_obj in constructor_fns:
934                     assert not is_free
935                     for explode_arg in constructor_fns[arg_conv_info.rust_obj].split(','):
936                         explode_arg_conv = map_type(explode_arg, False, None, False, True)
937                         if explode_arg_conv.c_ty == "void":
938                             # We actually want to handle this case, but for now its only used in NetGraphMsgHandler::new()
939                             # which ends up resulting in a redundant constructor - both without arguments for the NetworkGraph.
940                             args_known = False
941                             pass
942                         if not arg_conv_info.arg_name in default_constructor_args:
943                             default_constructor_args[arg_conv_info.arg_name] = []
944                         default_constructor_args[arg_conv_info.arg_name].append(explode_arg_conv)
945             arg_names.append(arg_conv_info)
946
947         out_java_struct = None
948         if ("LDK" + struct_meth in opaque_structs or "LDK" + struct_meth in trait_structs) and not is_free:
949             out_java_struct = open(sys.argv[3] + "/structs/" + struct_meth + ".java", "a")
950             if not args_known:
951                 out_java_struct.write("\t// Skipped " + re_match.group(2) + "\n")
952                 out_java_struct.close()
953                 out_java_struct = None
954             else:
955                 meth_n = re_match.group(2)[len(struct_meth) + 1:]
956                 if not takes_self:
957                     out_java_struct.write("\tpublic static " + ret_info.java_hu_ty + " constructor_" + meth_n + "(")
958                 else:
959                     out_java_struct.write("\tpublic " + ret_info.java_hu_ty + " " + meth_n + "(")
960                 for idx, arg in enumerate(arg_names):
961                     if idx != 0:
962                         if not takes_self or idx > 1:
963                             out_java_struct.write(", ")
964                     elif takes_self:
965                         continue
966                     if arg.java_ty != "void":
967                         if arg.arg_name in default_constructor_args:
968                             for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
969                                 if explode_idx != 0:
970                                     out_java_struct.write(", ")
971                                 out_java_struct.write(explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
972                         else:
973                             out_java_struct.write(arg.java_hu_ty + " " + arg.arg_name)
974
975
976         out_java.write(");\n")
977         write_c(") {\n")
978         if out_java_struct is not None:
979             out_java_struct.write(") {\n")
980
981         for info in arg_names:
982             if info.arg_conv is not None:
983                 write_c("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
984
985         if ret_info.ret_conv is not None:
986             write_c("\t" + ret_conv_pfx.replace('\n', '\n\t'))
987         elif ret_info.c_ty != "void":
988             write_c("\t" + ret_info.c_ty + " ret_val = ")
989         else:
990             write_c("\t")
991
992         if c_call_string is None:
993             write_c(re_match.group(2) + "(")
994         else:
995             write_c(c_call_string)
996         for idx, info in enumerate(arg_names):
997             if info.arg_conv_name is not None:
998                 if idx != 0:
999                     write_c(", ")
1000                 elif c_call_string is not None:
1001                     continue
1002                 write_c(info.arg_conv_name)
1003         write_c(")")
1004         if ret_info.ret_conv is not None:
1005             write_c(ret_conv_sfx.replace('\n', '\n\t'))
1006         else:
1007             write_c(";")
1008         for info in arg_names:
1009             if info.arg_conv_cleanup is not None:
1010                 write_c("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1011         if ret_info.ret_conv is not None:
1012             write_c("\n\treturn " + ret_info.ret_conv_name + ";")
1013         elif ret_info.c_ty != "void":
1014             write_c("\n\treturn ret_val;")
1015         write_c("\n}\n\n")
1016         if out_java_struct is not None:
1017             out_java_struct.write("\t\t")
1018             if ret_info.java_ty != "void":
1019                 out_java_struct.write(ret_info.java_ty + " ret = ")
1020             out_java_struct.write("bindings." + re_match.group(2) + "(")
1021             for idx, info in enumerate(arg_names):
1022                 if idx != 0:
1023                     out_java_struct.write(", ")
1024                 if idx == 0 and takes_self:
1025                     out_java_struct.write("this.ptr")
1026                 elif info.arg_name in default_constructor_args:
1027                     out_java_struct.write("bindings." + info.java_hu_ty + "_new(")
1028                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1029                         if explode_idx != 0:
1030                             out_java_struct.write(", ")
1031                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1032                         if explode_arg.from_hu_conv is not None:
1033                             out_java_struct.write(explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1034                         else:
1035                             out_java_struct.write(expl_arg_name)
1036                     out_java_struct.write(")")
1037                 elif info.from_hu_conv is not None:
1038                     out_java_struct.write(info.from_hu_conv[0])
1039                 else:
1040                     out_java_struct.write(info.arg_name)
1041             out_java_struct.write(");\n")
1042             if ret_info.to_hu_conv is not None:
1043                 if not takes_self:
1044                     out_java_struct.write("\t\t" + ret_info.to_hu_conv.replace("\n", "\n\t\t").replace("this", ret_info.to_hu_conv_name) + "\n")
1045                 else:
1046                     out_java_struct.write("\t\t" + ret_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1047
1048             for idx, info in enumerate(arg_names):
1049                 if idx == 0 and takes_self:
1050                     pass
1051                 elif info.arg_name in default_constructor_args:
1052                     for explode_arg in default_constructor_args[info.arg_name]:
1053                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1054                         if explode_arg.from_hu_conv is not None and ret_info.to_hu_conv_name:
1055                             out_java_struct.write("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name, expl_arg_name).replace("this", ret_info.to_hu_conv_name) + ";\n")
1056                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1057                     if not takes_self and ret_info.to_hu_conv_name is not None:
1058                         out_java_struct.write("\t\t" + info.from_hu_conv[1].replace("this", ret_info.to_hu_conv_name) + ";\n")
1059                     else:
1060                         out_java_struct.write("\t\t" + info.from_hu_conv[1] + ";\n")
1061
1062             if ret_info.to_hu_conv_name is not None:
1063                 out_java_struct.write("\t\treturn " + ret_info.to_hu_conv_name + ";\n")
1064             elif ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
1065                 out_java_struct.write("\t\treturn ret;\n")
1066             out_java_struct.write("\t}\n\n")
1067             out_java_struct.close()
1068
1069     def map_unitary_enum(struct_name, field_lines):
1070         with open(sys.argv[3] + "/enums/" + struct_name + ".java", "w") as out_java_enum:
1071             out_java_enum.write("package org.ldk.enums;\n\n")
1072             unitary_enums.add(struct_name)
1073             write_c("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
1074             write_c("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
1075             ord_v = 0
1076             for idx, struct_line in enumerate(field_lines):
1077                 if idx == 0:
1078                     out_java_enum.write("public enum " + struct_name + " {\n")
1079                 elif idx == len(field_lines) - 3:
1080                     assert(struct_line.endswith("_Sentinel,"))
1081                 elif idx == len(field_lines) - 2:
1082                     out_java_enum.write("\t; static native void init();\n")
1083                     out_java_enum.write("\tstatic { init(); }\n")
1084                     out_java_enum.write("}")
1085                     out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
1086                 elif idx == len(field_lines) - 1:
1087                     assert(struct_line == "")
1088                 else:
1089                     out_java_enum.write(struct_line + "\n")
1090                     write_c("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
1091                     ord_v = ord_v + 1
1092             write_c("\t}\n")
1093             write_c("\tabort();\n")
1094             write_c("}\n")
1095
1096             ord_v = 0
1097             write_c("static jclass " + struct_name + "_class = NULL;\n")
1098             for idx, struct_line in enumerate(field_lines):
1099                 if idx > 0 and idx < len(field_lines) - 3:
1100                     variant = struct_line.strip().strip(",")
1101                     write_c("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
1102             write_c("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
1103             write_c("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
1104             write_c("\tCHECK(" + struct_name + "_class != NULL);\n")
1105             for idx, struct_line in enumerate(field_lines):
1106                 if idx > 0 and idx < len(field_lines) - 3:
1107                     variant = struct_line.strip().strip(",")
1108                     write_c("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
1109                     write_c("\tCHECK(" + struct_name + "_" + variant + " != NULL);\n")
1110             write_c("}\n")
1111             write_c("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
1112             write_c("\tswitch (val) {\n")
1113             for idx, struct_line in enumerate(field_lines):
1114                 if idx > 0 and idx < len(field_lines) - 3:
1115                     variant = struct_line.strip().strip(",")
1116                     write_c("\t\tcase " + variant + ":\n")
1117                     write_c("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
1118                     ord_v = ord_v + 1
1119             write_c("\t\tdefault: abort();\n")
1120             write_c("\t}\n")
1121             write_c("}\n\n")
1122
1123     def map_complex_enum(struct_name, union_enum_items):
1124         java_hu_type = struct_name.replace("LDK", "")
1125         complex_enums.add(struct_name)
1126         with open(sys.argv[3] + "/structs/" + java_hu_type + ".java", "w") as out_java_enum:
1127             out_java_enum.write(hu_struct_file_prefix)
1128             out_java_enum.write("public class " + java_hu_type + " extends CommonBase {\n")
1129             out_java_enum.write("\tprivate " + java_hu_type + "(Object _dummy, long ptr) { super(ptr); }\n")
1130             out_java_enum.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1131             out_java_enum.write("\tprotected void finalize() throws Throwable {\n")
1132             out_java_enum.write("\t\tsuper.finalize();\n")
1133             out_java_enum.write("\t\tif (ptr != 0) { bindings." + java_hu_type + "_free(ptr); }\n")
1134             out_java_enum.write("\t}\n")
1135             out_java_enum.write("\tstatic " + java_hu_type + " constr_from_ptr(long ptr) {\n")
1136             out_java_enum.write("\t\tbindings." + struct_name + " raw_val = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
1137             java_hu_subclasses = ""
1138
1139             tag_field_lines = union_enum_items["field_lines"]
1140             init_meth_jty_strs = {}
1141             for idx, struct_line in enumerate(tag_field_lines):
1142                 if idx == 0:
1143                     out_java.write("\tpublic static class " + struct_name + " {\n")
1144                     out_java.write("\t\tprivate " + struct_name + "() {}\n")
1145                 elif idx == len(tag_field_lines) - 3:
1146                     assert(struct_line.endswith("_Sentinel,"))
1147                 elif idx == len(tag_field_lines) - 2:
1148                     out_java.write("\t\tstatic native void init();\n")
1149                     out_java.write("\t}\n")
1150                 elif idx == len(tag_field_lines) - 1:
1151                     assert(struct_line == "")
1152                 else:
1153                     var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1154                     out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
1155                     java_hu_subclasses = java_hu_subclasses + "\tpublic final static class " + var_name + " extends " + java_hu_type + " {\n"
1156                     out_java_enum.write("\t\tif (raw_val.getClass() == bindings." + struct_name + "." + var_name + ".class) {\n")
1157                     out_java_enum.write("\t\t\treturn new " + var_name + "(ptr, (bindings." + struct_name + "." + var_name + ")raw_val);\n")
1158                     write_c("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
1159                     write_c("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
1160                     init_meth_jty_str = ""
1161                     init_meth_params = ""
1162                     init_meth_body = ""
1163                     hu_conv_body = ""
1164                     if "LDK" + var_name in union_enum_items:
1165                         enum_var_lines = union_enum_items["LDK" + var_name]
1166                         for idx, field in enumerate(enum_var_lines):
1167                             if idx != 0 and idx < len(enum_var_lines) - 2:
1168                                 field_ty = map_type(field.strip(' ;'), False, None, False, True)
1169                                 out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
1170                                 java_hu_subclasses = java_hu_subclasses + "\t\tpublic final " + field_ty.java_hu_ty + " " + field_ty.arg_name + ";\n"
1171                                 if field_ty.to_hu_conv is not None:
1172                                     hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.java_ty + " " + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1173                                     hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1174                                     hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1175                                 else:
1176                                     hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1177                                 init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
1178                                 if idx > 1:
1179                                     init_meth_params = init_meth_params + ", "
1180                                 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
1181                                 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
1182                         out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
1183                         out_java.write(init_meth_body)
1184                         out_java.write("}\n")
1185                     out_java.write("\t\t}\n")
1186                     out_java_enum.write("\t\t}\n")
1187                     java_hu_subclasses = java_hu_subclasses + "\t\tprivate " + var_name + "(long ptr, bindings." + struct_name + "." + var_name + " obj) {\n\t\t\tsuper(null, ptr);\n"
1188                     java_hu_subclasses = java_hu_subclasses + hu_conv_body
1189                     java_hu_subclasses = java_hu_subclasses + "\t\t}\n\t}\n"
1190                     init_meth_jty_strs[var_name] = init_meth_jty_str
1191             out_java_enum.write("\t\tassert false; return null; // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
1192             out_java_enum.write(java_hu_subclasses)
1193             out_java.write("\tstatic { " + struct_name + ".init(); }\n")
1194             out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
1195
1196             write_c("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
1197             for idx, struct_line in enumerate(tag_field_lines):
1198                 if idx != 0 and idx < len(tag_field_lines) - 3:
1199                     var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1200                     write_c("\t" + struct_name + "_" + var_name + "_class =\n")
1201                     write_c("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
1202                     write_c("\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n")
1203                     write_c("\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n")
1204                     write_c("\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n")
1205             write_c("}\n")
1206             write_c("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (JNIEnv * _env, jclass _c, jlong ptr) {\n")
1207             write_c("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
1208             write_c("\tswitch(obj->tag) {\n")
1209             for idx, struct_line in enumerate(tag_field_lines):
1210                 if idx != 0 and idx < len(tag_field_lines) - 3:
1211                     var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1212                     write_c("\t\tcase " + struct_name + "_" + var_name + ": {\n")
1213                     c_params_text = ""
1214                     if "LDK" + var_name in union_enum_items:
1215                         enum_var_lines = union_enum_items["LDK" + var_name]
1216                         for idx, field in enumerate(enum_var_lines):
1217                             if idx != 0 and idx < len(enum_var_lines) - 2:
1218                                 field_map = map_type(field.strip(' ;'), False, None, False, True)
1219                                 if field_map.ret_conv is not None:
1220                                     write_c("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1221                                     write_c("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
1222                                     write_c(field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1223                                     c_params_text = c_params_text + ", " + field_map.ret_conv_name
1224                                 else:
1225                                     c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
1226                     write_c("\t\t\treturn (*_env)->NewObject(_env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
1227                     write_c("\t\t}\n")
1228             write_c("\t\tdefault: abort();\n")
1229             write_c("\t}\n}\n")
1230             out_java_enum.write("}\n")
1231
1232     def map_trait(struct_name, field_var_lines, trait_fn_lines):
1233         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_trait:
1234             write_c("typedef struct " + struct_name + "_JCalls {\n")
1235             write_c("\tatomic_size_t refcnt;\n")
1236             write_c("\tJavaVM *vm;\n")
1237             write_c("\tjweak o;\n")
1238             field_var_convs = []
1239             for var_line in field_var_lines:
1240                 if var_line.group(1) in trait_structs:
1241                     write_c("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
1242                     field_var_convs.append(None)
1243                 else:
1244                     field_var_convs.append(map_type(var_line.group(1) + " " + var_line.group(2), False, None, False, False))
1245             for fn_line in trait_fn_lines:
1246                 if fn_line.group(3) != "free" and fn_line.group(3) != "clone":
1247                     write_c("\tjmethodID " + fn_line.group(3) + "_meth;\n")
1248             write_c("} " + struct_name + "_JCalls;\n")
1249
1250             out_java_trait.write(hu_struct_file_prefix)
1251             out_java_trait.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
1252             out_java_trait.write("\tfinal bindings." + struct_name + " bindings_instance;\n")
1253             out_java_trait.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); bindings_instance = null; }\n")
1254             out_java_trait.write("\tprivate " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg")
1255             for idx, var_line in enumerate(field_var_lines):
1256                 if var_line.group(1) in trait_structs:
1257                     out_java_trait.write(", bindings." + var_line.group(1) + " " + var_line.group(2))
1258                 else:
1259                     out_java_trait.write(", " + field_var_convs[idx].java_hu_ty + " " + var_line.group(2))
1260             out_java_trait.write(") {\n")
1261             out_java_trait.write("\t\tsuper(bindings." + struct_name + "_new(arg")
1262             for idx, var_line in enumerate(field_var_lines):
1263                 if var_line.group(1) in trait_structs:
1264                     out_java_trait.write(", " + var_line.group(2))
1265                 elif field_var_convs[idx].from_hu_conv is not None:
1266                     out_java_trait.write(", " + field_var_convs[idx].from_hu_conv[0])
1267                 else:
1268                     out_java_trait.write(", " + var_line.group(2))
1269             out_java_trait.write("));\n")
1270             out_java_trait.write("\t\tthis.ptrs_to.add(arg);\n")
1271             for idx, var_line in enumerate(field_var_lines):
1272                 if var_line.group(1) in trait_structs:
1273                     out_java_trait.write("\t\tthis.ptrs_to.add(" + var_line.group(2) + ");\n")
1274                 elif field_var_convs[idx].from_hu_conv is not None and field_var_convs[idx].from_hu_conv[1] != "":
1275                     out_java_trait.write("\t\t" + field_var_convs[idx].from_hu_conv[1] + ";\n")
1276             out_java_trait.write("\t\tthis.bindings_instance = arg;\n")
1277             out_java_trait.write("\t}\n")
1278             out_java_trait.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1279             out_java_trait.write("\tprotected void finalize() throws Throwable {\n")
1280             out_java_trait.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
1281             out_java_trait.write("\t}\n\n")
1282
1283             java_trait_constr = "\tprivate static class " + struct_name + "Holder { " + struct_name.replace("LDK", "") + " held; }\n"
1284             java_trait_constr = java_trait_constr + "\tpublic static " + struct_name.replace("LDK", "") + " new_impl(" + struct_name.replace("LDK", "") + "Interface arg"
1285             for idx, var_line in enumerate(field_var_lines):
1286                 if var_line.group(1) in trait_structs:
1287                     # Ideally we'd be able to take any instance of the interface, but our C code can only represent
1288                     # Java-implemented version, so we require users pass a Java implementation here :/
1289                     java_trait_constr = java_trait_constr + ", " + var_line.group(1).replace("LDK", "") + "." + var_line.group(1).replace("LDK", "") + "Interface " + var_line.group(2) + "_impl"
1290                 else:
1291                     java_trait_constr = java_trait_constr + ", " + field_var_convs[idx].java_hu_ty + " " + var_line.group(2)
1292             java_trait_constr = java_trait_constr + ") {\n\t\tfinal " + struct_name + "Holder impl_holder = new " + struct_name + "Holder();\n"
1293             java_trait_constr = java_trait_constr + "\t\timpl_holder.held = new " + struct_name.replace("LDK", "") + "(new bindings." + struct_name + "() {\n"
1294             out_java_trait.write("\tpublic static interface " + struct_name.replace("LDK", "") + "Interface {\n")
1295             out_java.write("\tpublic interface " + struct_name + " {\n")
1296             java_meths = []
1297             for fn_line in trait_fn_lines:
1298                 java_meth_descr = "("
1299                 if fn_line.group(3) != "free" and fn_line.group(3) != "clone":
1300                     ret_ty_info = map_type(fn_line.group(2), True, None, False, False)
1301
1302                     out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(3) + "(")
1303                     java_trait_constr = java_trait_constr + "\t\t\t@Override public " + ret_ty_info.java_ty + " " + fn_line.group(3) + "("
1304                     out_java_trait.write("\t\t" + ret_ty_info.java_hu_ty + " " + fn_line.group(3) + "(")
1305                     is_const = fn_line.group(4) is not None
1306                     write_c(fn_line.group(2) + fn_line.group(3) + "_jcall(")
1307                     if is_const:
1308                         write_c("const void* this_arg")
1309                     else:
1310                         write_c("void* this_arg")
1311
1312                     arg_names = []
1313                     for idx, arg in enumerate(fn_line.group(5).split(',')):
1314                         if arg == "":
1315                             continue
1316                         if idx >= 2:
1317                             out_java.write(", ")
1318                             java_trait_constr = java_trait_constr + ", "
1319                             out_java_trait.write(", ")
1320                         write_c(", ")
1321                         arg_conv_info = map_type(arg, True, None, False, False)
1322                         write_c(arg.strip())
1323                         out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
1324                         out_java_trait.write(arg_conv_info.java_hu_ty + " " + arg_conv_info.arg_name)
1325                         java_trait_constr = java_trait_constr + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
1326                         arg_names.append(arg_conv_info)
1327                         java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
1328                     java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
1329                     java_meths.append((fn_line, java_meth_descr))
1330
1331                     out_java.write(");\n")
1332                     out_java_trait.write(");\n")
1333                     java_trait_constr = java_trait_constr + ") {\n"
1334                     write_c(") {\n")
1335                     write_c("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1336                     write_c("\tJNIEnv *_env;\n")
1337                     write_c("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&_env, JNI_VERSION_1_8) == JNI_OK);\n")
1338
1339                     for arg_info in arg_names:
1340                         if arg_info.ret_conv is not None:
1341                             write_c("\t" + arg_info.ret_conv[0].replace('\n', '\n\t'));
1342                             write_c(arg_info.arg_name)
1343                             write_c(arg_info.ret_conv[1].replace('\n', '\n\t') + "\n")
1344                         if arg_info.to_hu_conv is not None:
1345                             java_trait_constr = java_trait_constr + "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
1346
1347                     write_c("\tjobject obj = (*_env)->NewLocalRef(_env, j_calls->o);\n\tCHECK(obj != NULL);\n")
1348                     if ret_ty_info.c_ty.endswith("Array"):
1349                         write_c("\t" + ret_ty_info.c_ty + " arg = (*_env)->CallObjectMethod(_env, obj, j_calls->" + fn_line.group(3) + "_meth")
1350                     elif not ret_ty_info.passed_as_ptr:
1351                         write_c("\treturn (*_env)->Call" + ret_ty_info.java_ty.title() + "Method(_env, obj, j_calls->" + fn_line.group(3) + "_meth")
1352                     else:
1353                         write_c("\t" + fn_line.group(2).strip() + "* ret = (" + fn_line.group(2).strip() + "*)(*_env)->CallLongMethod(_env, obj, j_calls->" + fn_line.group(3) + "_meth");
1354                     if ret_ty_info.java_ty != "void":
1355                         java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.java_hu_ty + " ret = arg." + fn_line.group(3) + "("
1356                     else:
1357                         java_trait_constr = java_trait_constr + "\t\t\t\targ." + fn_line.group(3) + "("
1358
1359                     for idx, arg_info in enumerate(arg_names):
1360                         if arg_info.ret_conv is not None:
1361                             write_c(", " + arg_info.ret_conv_name)
1362                         else:
1363                             write_c(", " + arg_info.arg_name)
1364                         if idx != 0:
1365                             java_trait_constr = java_trait_constr + ", "
1366                         if arg_info.to_hu_conv_name is not None:
1367                             java_trait_constr = java_trait_constr + arg_info.to_hu_conv_name
1368                         else:
1369                             java_trait_constr = java_trait_constr + arg_info.arg_name
1370                     write_c(");\n");
1371                     if ret_ty_info.arg_conv is not None:
1372                         write_c("\t" + ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + ret_ty_info.arg_conv_name + ";\n")
1373
1374                     write_c("}\n")
1375                     java_trait_constr = java_trait_constr + ");\n"
1376                     if ret_ty_info.java_ty != "void":
1377                         if ret_ty_info.from_hu_conv is not None:
1378                             java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.java_ty + " result = " + ret_ty_info.from_hu_conv[0] + ";\n"
1379                             if ret_ty_info.from_hu_conv[1] != "":
1380                                 java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
1381                             if ret_ty_info.rust_obj in result_types:
1382                                 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
1383                                 java_trait_constr = java_trait_constr + "\t\t\t\tret.ptr = 0;\n"
1384                             java_trait_constr = java_trait_constr + "\t\t\t\treturn result;\n"
1385                         else:
1386                             java_trait_constr = java_trait_constr + "\t\t\t\treturn ret;\n"
1387                     java_trait_constr = java_trait_constr + "\t\t\t}\n"
1388                 elif fn_line.group(3) == "free":
1389                     write_c("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
1390                     write_c("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1391                     write_c("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
1392                     write_c("\t\tJNIEnv *env;\n")
1393                     write_c("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
1394                     write_c("\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n")
1395                     write_c("\t\tFREE(j_calls);\n")
1396                     write_c("\t}\n}\n")
1397             java_trait_constr = java_trait_constr + "\t\t}"
1398             for var_line in field_var_lines:
1399                 if var_line.group(1) in trait_structs:
1400                     java_trait_constr = java_trait_constr + ", " + var_line.group(2) + ".new_impl(" + var_line.group(2) + "_impl).bindings_instance"
1401                 else:
1402                     java_trait_constr = java_trait_constr + ", " + var_line.group(2)
1403             out_java_trait.write("\t}\n")
1404             out_java_trait.write(java_trait_constr + ");\n\t\treturn impl_holder.held;\n\t}\n")
1405
1406             # Write out a clone function whether we need one or not, as we use them in moving to rust
1407             write_c("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
1408             write_c("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1409             write_c("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
1410             for var_line in field_var_lines:
1411                 if var_line.group(1) in trait_structs:
1412                     write_c("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
1413             write_c("\treturn (void*) this_arg;\n")
1414             write_c("}\n")
1415
1416             out_java.write("\t}\n")
1417
1418             out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
1419             write_c("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
1420             for idx, var_line in enumerate(field_var_lines):
1421                 if var_line.group(1) in trait_structs:
1422                     out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
1423                     write_c(", jobject " + var_line.group(2))
1424                 else:
1425                     out_java.write(", " + field_var_convs[idx].java_ty + " " + var_line.group(2))
1426                     write_c(", " + field_var_convs[idx].c_ty + " " + var_line.group(2))
1427             out_java.write(");\n")
1428             write_c(") {\n")
1429
1430             write_c("\tjclass c = (*env)->GetObjectClass(env, o);\n")
1431             write_c("\tCHECK(c != NULL);\n")
1432             write_c("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
1433             write_c("\tatomic_init(&calls->refcnt, 1);\n")
1434             write_c("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
1435             write_c("\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n")
1436             for (fn_line, java_meth_descr) in java_meths:
1437                 if fn_line.group(3) != "free" and fn_line.group(3) != "clone":
1438                     write_c("\tcalls->" + fn_line.group(3) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(3) + "\", \"" + java_meth_descr + "\");\n")
1439                     write_c("\tCHECK(calls->" + fn_line.group(3) + "_meth != NULL);\n")
1440             for idx, var_line in enumerate(field_var_lines):
1441                 if field_var_convs[idx] is not None and field_var_convs[idx].arg_conv is not None:
1442                     write_c("\n\t" + field_var_convs[idx].arg_conv.replace("\n", "\n\t") +"\n")
1443             write_c("\n\t" + struct_name + " ret = {\n")
1444             write_c("\t\t.this_arg = (void*) calls,\n")
1445             for fn_line in trait_fn_lines:
1446                 if fn_line.group(3) != "free" and fn_line.group(3) != "clone":
1447                     write_c("\t\t." + fn_line.group(3) + " = " + fn_line.group(3) + "_jcall,\n")
1448                 elif fn_line.group(3) == "free":
1449                     write_c("\t\t.free = " + struct_name + "_JCalls_free,\n")
1450                 else:
1451                     write_c("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
1452             for idx, var_line in enumerate(field_var_lines):
1453                 if var_line.group(1) in trait_structs:
1454                     write_c("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
1455                 elif field_var_convs[idx].arg_conv_name is not None:
1456                     write_c("\t\t." + var_line.group(2) + " = " + field_var_convs[idx].arg_conv_name + ",\n")
1457                     write_c("\t\t.set_" + var_line.group(2) + " = NULL,\n")
1458                 else:
1459                     write_c("\t\t." + var_line.group(2) + " = " + var_line.group(2) + ",\n")
1460                     write_c("\t\t.set_" + var_line.group(2) + " = NULL,\n")
1461             write_c("\t};\n")
1462             for var_line in field_var_lines:
1463                 if var_line.group(1) in trait_structs:
1464                     write_c("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
1465             write_c("\treturn ret;\n")
1466             write_c("}\n")
1467
1468             write_c("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
1469             for idx, var_line in enumerate(field_var_lines):
1470                 if var_line.group(1) in trait_structs:
1471                     write_c(", jobject " + var_line.group(2))
1472                 else:
1473                     write_c(", " + field_var_convs[idx].c_ty + " " + var_line.group(2))
1474             write_c(") {\n")
1475             write_c("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1476             write_c("\t*res_ptr = " + struct_name + "_init(env, _a, o")
1477             for var_line in field_var_lines:
1478                 write_c(", " + var_line.group(2))
1479             write_c(");\n")
1480             write_c("\treturn (long)res_ptr;\n")
1481             write_c("}\n")
1482
1483             out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
1484             write_c("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1get_1obj_1from_1jcalls (JNIEnv * env, jclass _a, jlong val) {\n")
1485             write_c("\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n")
1486             write_c("\tCHECK(ret != NULL);\n")
1487             write_c("\treturn ret;\n")
1488             write_c("}\n")
1489
1490         for fn_line in trait_fn_lines:
1491             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
1492             is_log = fn_line.group(3) == "log" and struct_name == "LDKLogger"
1493             if fn_line.group(3) != "free" and fn_line.group(3) != "clone" and fn_line.group(3) != "eq" and not is_log:
1494                 dummy_line = fn_line.group(2) + struct_name.replace("LDK", "") + "_" + fn_line.group(3) + " " + struct_name + "* this_arg" + fn_line.group(5) + "\n"
1495                 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(this_arg_conv->" + fn_line.group(3) + ")(this_arg_conv->this_arg")
1496         for idx, var_line in enumerate(field_var_lines):
1497             if var_line.group(1) not in trait_structs:
1498                 write_c(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
1499                 write_c("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
1500                 write_c("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
1501                 write_c("\treturn this_arg->" + var_line.group(2) + ";\n")
1502                 write_c("}\n")
1503                 dummy_line = var_line.group(1) + " " + struct_name.replace("LDK", "") + "_get_" + var_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(5) + "\n"
1504                 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, struct_name + "_set_get_" + var_line.group(2) + "(this_arg_conv")
1505
1506     def map_result(struct_name, res_ty, err_ty):
1507         result_types.add(struct_name)
1508         human_ty = struct_name.replace("LDKCResult", "Result")
1509         with open(sys.argv[3] + "/structs/" + human_ty + ".java", "w") as out_java_struct:
1510             out_java_struct.write(hu_struct_file_prefix)
1511             out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
1512             out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
1513             out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1514             out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
1515             out_java_struct.write("\t}\n\n")
1516             out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
1517             out_java_struct.write("\t\tif (bindings." + struct_name + "_result_ok(ptr)) {\n")
1518             out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
1519             out_java_struct.write("\t\t} else {\n")
1520             out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
1521             out_java_struct.write("\t\t}\n")
1522             out_java_struct.write("\t}\n")
1523
1524             res_map = map_type(res_ty + " res", True, None, False, True)
1525             err_map = map_type(err_ty + " err", True, None, False, True)
1526             can_clone = True
1527             if not res_map.is_native_primitive and (res_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
1528                 can_clone = False
1529             if not err_map.is_native_primitive and (err_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
1530                 can_clone = False
1531
1532             out_java.write("\tpublic static native boolean " + struct_name + "_result_ok(long arg);\n")
1533             write_c("JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1result_1ok (JNIEnv * env, jclass _a, jlong arg) {\n")
1534             write_c("\treturn ((" + struct_name + "*)arg)->result_ok;\n")
1535             write_c("}\n")
1536
1537             out_java.write("\tpublic static native " + res_map.java_ty + " " + struct_name + "_get_ok(long arg);\n")
1538             write_c("JNIEXPORT " + res_map.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1get_1ok (JNIEnv * _env, jclass _a, jlong arg) {\n")
1539             write_c("\t" + struct_name + " *val = (" + struct_name + "*)arg;\n")
1540             write_c("\tCHECK(val->result_ok);\n\t")
1541             out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
1542             if res_map.ret_conv is not None:
1543                 write_c(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
1544                 write_c(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
1545             else:
1546                 write_c("return *val->contents.result")
1547             write_c(";\n}\n")
1548
1549             if res_map.java_hu_ty != "void":
1550                 out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
1551             out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
1552             out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1553             if res_map.java_hu_ty == "void":
1554                 pass
1555             elif res_map.to_hu_conv is not None:
1556                 out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + struct_name + "_get_ok(ptr);\n")
1557                 out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1558                 out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
1559             else:
1560                 out_java_struct.write("\t\t\tthis.res = bindings." + struct_name + "_get_ok(ptr);\n")
1561             out_java_struct.write("\t\t}\n")
1562             if struct_name.startswith("LDKCResult_None"):
1563                 out_java_struct.write("\t\tpublic " + human_ty + "_OK() {\n\t\t\tthis(null, bindings.C" + human_ty + "_ok());\n")
1564             else:
1565                 out_java_struct.write("\t\tpublic " + human_ty + "_OK(" + res_map.java_hu_ty + " res) {\n")
1566                 if res_map.from_hu_conv is not None:
1567                     out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(" + res_map.from_hu_conv[0] + "));\n")
1568                     if res_map.from_hu_conv[1] != "":
1569                         out_java_struct.write("\t\t\t" + res_map.from_hu_conv[1] + ";\n")
1570                 else:
1571                     out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(res));\n")
1572             out_java_struct.write("\t\t}\n\t}\n\n")
1573
1574             out_java.write("\tpublic static native " + err_map.java_ty + " " + struct_name + "_get_err(long arg);\n")
1575             write_c("JNIEXPORT " + err_map.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1get_1err (JNIEnv * _env, jclass _a, jlong arg) {\n")
1576             write_c("\t" + struct_name + " *val = (" + struct_name + "*)arg;\n")
1577             write_c("\tCHECK(!val->result_ok);\n\t")
1578             out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
1579             if err_map.ret_conv is not None:
1580                 write_c(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
1581                 write_c(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
1582             else:
1583                 write_c("return *val->contents.err")
1584             write_c(";\n}\n")
1585
1586             if err_map.java_hu_ty != "void":
1587                 out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
1588             out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
1589             out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1590             if err_map.java_hu_ty == "void":
1591                 pass
1592             elif err_map.to_hu_conv is not None:
1593                 out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + struct_name + "_get_err(ptr);\n")
1594                 out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1595                 out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
1596             else:
1597                 out_java_struct.write("\t\t\tthis.err = bindings." + struct_name + "_get_err(ptr);\n")
1598             out_java_struct.write("\t\t}\n")
1599
1600             if struct_name.endswith("NoneZ"):
1601                 out_java_struct.write("\t\tpublic " + human_ty + "_Err() {\n\t\t\tthis(null, bindings.C" + human_ty + "_err());\n")
1602             else:
1603                 out_java_struct.write("\t\tpublic " + human_ty + "_Err(" + err_map.java_hu_ty + " err) {\n")
1604                 if err_map.from_hu_conv is not None:
1605                     out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(" + err_map.from_hu_conv[0] + "));\n")
1606                     if err_map.from_hu_conv[1] != "":
1607                         out_java_struct.write("\t\t\t" + err_map.from_hu_conv[1] + ";\n")
1608                 else:
1609                     out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(err));\n")
1610             out_java_struct.write("\t\t}\n\t}\n}\n")
1611
1612             if can_clone:
1613                 clone_fns.add(struct_name.replace("LDK", "") + "_clone")
1614                 write_c("static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n")
1615                 write_c("\t" + struct_name + " res = { .result_ok = orig->result_ok };\n")
1616                 write_c("\tif (orig->result_ok) {\n")
1617                 if res_map.c_ty == "void":
1618                     write_c("\t\tres.contents.result = NULL;\n")
1619                 else:
1620                     if res_map.is_native_primitive:
1621                         write_c("\t\t" + res_map.c_ty + "* contents = MALLOC(sizeof(" + res_map.c_ty + "), \"" + res_map.c_ty + " result OK clone\");\n")
1622                         write_c("\t\t*contents = *orig->contents.result;\n")
1623                     else:
1624                         write_c("\t\t" + res_map.rust_obj + "* contents = MALLOC(sizeof(" + res_map.rust_obj + "), \"" + res_map.rust_obj + " result OK clone\");\n")
1625                         write_c("\t\t*contents = " + res_map.rust_obj.replace("LDK", "") + "_clone(orig->contents.result);\n")
1626                     write_c("\t\tres.contents.result = contents;\n")
1627                 write_c("\t} else {\n")
1628                 if err_map.c_ty == "void":
1629                     write_c("\t\tres.contents.err = NULL;\n")
1630                 else:
1631                     if err_map.is_native_primitive:
1632                         write_c("\t\t" + err_map.c_ty + "* contents = MALLOC(sizeof(" + err_map.c_ty + "), \"" + err_map.c_ty + " result Err clone\");\n")
1633                         write_c("\t\t*contents = *orig->contents.err;\n")
1634                     else:
1635                         write_c("\t\t" + err_map.rust_obj + "* contents = MALLOC(sizeof(" + err_map.rust_obj + "), \"" + err_map.rust_obj + " result Err clone\");\n")
1636                         write_c("\t\t*contents = " + err_map.rust_obj.replace("LDK", "") + "_clone(orig->contents.err);\n")
1637                     write_c("\t\tres.contents.err = contents;\n")
1638                 write_c("\t}\n\treturn res;\n}\n")
1639
1640     def map_tuple(struct_name, field_lines):
1641         out_java.write("\tpublic static native long " + struct_name + "_new(")
1642         write_c("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *_env, jclass _b")
1643         ty_list = []
1644         for idx, line in enumerate(field_lines):
1645             if idx != 0 and idx < len(field_lines) - 2:
1646                 ty_info = java_c_types(line.strip(';'), None)
1647                 if idx != 1:
1648                     out_java.write(", ")
1649                 e = chr(ord('a') + idx - 1)
1650                 out_java.write(ty_info.java_ty + " " + e)
1651                 write_c(", " + ty_info.c_ty + " " + e)
1652                 ty_list.append(ty_info)
1653         tuple_types[struct_name] = (ty_list, struct_name)
1654         out_java.write(");\n")
1655         write_c(") {\n")
1656         write_c("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1657         can_clone = True
1658         clone_str = "static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n"
1659         clone_str = clone_str + "\t" + struct_name + " ret = {\n"
1660         for idx, line in enumerate(field_lines):
1661             if idx != 0 and idx < len(field_lines) - 2:
1662                 ty_info = map_type(line.strip(';'), False, None, False, False)
1663                 e = chr(ord('a') + idx - 1)
1664                 if ty_info.arg_conv is not None:
1665                     write_c("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
1666                     write_c("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
1667                 else:
1668                     write_c("\tret->" + e + " = " + e + ";\n")
1669                 if ty_info.arg_conv_cleanup is not None:
1670                     write_c("\t//TODO: Really need to call " + ty_info.arg_conv_cleanup + " here\n")
1671                 if not ty_info.is_native_primitive and (ty_info.rust_obj.replace("LDK", "") + "_clone") not in clone_fns:
1672                     can_clone = False
1673                 elif can_clone and ty_info.is_native_primitive:
1674                     clone_str = clone_str + "\t\t." + chr(ord('a') + idx - 1) + " = orig->" + chr(ord('a') + idx - 1) + ",\n"
1675                 elif can_clone:
1676                     clone_str = clone_str + "\t\t." + chr(ord('a') + idx - 1) + " = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&orig->" + chr(ord('a') + idx - 1) + "),\n"
1677         write_c("\treturn (long)ret;\n")
1678         write_c("}\n")
1679
1680         if can_clone:
1681             clone_fns.add(struct_name.replace("LDK", "") + "_clone")
1682             write_c(clone_str)
1683             write_c("\t};\n\treturn ret;\n}\n")
1684
1685         for idx, ty_info in enumerate(ty_list):
1686             e = chr(ord('a') + idx)
1687             out_java.write("\tpublic static native " + ty_info.java_ty + " " + struct_name + "_get_" + e + "(long ptr);\n")
1688             write_c("JNIEXPORT " + ty_info.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1get_1" + e + "(JNIEnv *_env, jclass _b, jlong ptr) {\n")
1689             write_c("\t" + struct_name + " *tuple = (" + struct_name + "*)ptr;\n")
1690             conv_info = map_type_with_info(ty_info, False, None, False, True)
1691             if conv_info.ret_conv is not None:
1692                 write_c("\t" + conv_info.ret_conv[0].replace("\n", "\n\t") + "tuple->" + e + conv_info.ret_conv[1].replace("\n", "\n\t") + "\n")
1693                 write_c("\treturn " + conv_info.ret_conv_name + ";\n")
1694             else:
1695                 write_c("\treturn tuple->" + e + ";\n")
1696             write_c("}\n")
1697
1698     out_java.write("""package org.ldk.impl;
1699 import org.ldk.enums.*;
1700
1701 public class bindings {
1702         public static class VecOrSliceDef {
1703                 public long dataptr;
1704                 public long datalen;
1705                 public long stride;
1706                 public VecOrSliceDef(long dataptr, long datalen, long stride) {
1707                         this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
1708                 }
1709         }
1710         static {
1711                 System.loadLibrary(\"lightningjni\");
1712                 init(java.lang.Enum.class, VecOrSliceDef.class);
1713                 init_class_cache();
1714         }
1715         static native void init(java.lang.Class c, java.lang.Class slicedef);
1716         static native void init_class_cache();
1717
1718         public static native boolean deref_bool(long ptr);
1719         public static native long deref_long(long ptr);
1720         public static native void free_heap_ptr(long ptr);
1721         public static native byte[] read_bytes(long ptr, long len);
1722         public static native byte[] get_u8_slice_bytes(long slice_ptr);
1723         public static native long bytes_to_u8_vec(byte[] bytes);
1724         public static native long new_txpointer_copy_data(byte[] txdata);
1725         public static native void txpointer_free(long ptr);
1726         public static native byte[] txpointer_get_buffer(long ptr);
1727         public static native long vec_slice_len(long vec);
1728         public static native long new_empty_slice_vec();
1729
1730 """)
1731     write_c("""
1732 static jmethodID ordinal_meth = NULL;
1733 static jmethodID slicedef_meth = NULL;
1734 static jclass slicedef_cls = NULL;
1735 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
1736         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
1737         CHECK(ordinal_meth != NULL);
1738         slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
1739         CHECK(slicedef_meth != NULL);
1740         slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
1741         CHECK(slicedef_cls != NULL);
1742 }
1743
1744 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
1745         return *((bool*)ptr);
1746 }
1747 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
1748         return *((long*)ptr);
1749 }
1750 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
1751         FREE((void*)ptr);
1752 }
1753 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
1754         jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
1755         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
1756         return ret_arr;
1757 }
1758 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
1759         LDKu8slice *slice = (LDKu8slice*)slice_ptr;
1760         jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
1761         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
1762         return ret_arr;
1763 }
1764 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
1765         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
1766         vec->datalen = (*_env)->GetArrayLength(_env, bytes);
1767         vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
1768         (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
1769         return (long)vec;
1770 }
1771 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_txpointer_1get_1buffer (JNIEnv * env, jclass _b, jlong ptr) {
1772         LDKTransaction *txdata = (LDKTransaction*)ptr;
1773         LDKu8slice slice;
1774         slice.data = txdata->data;
1775         slice.datalen = txdata->datalen;
1776         return Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes(env, _b, (long)&slice);
1777 }
1778 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
1779         LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
1780         txdata->datalen = (*env)->GetArrayLength(env, bytes);
1781         txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
1782         txdata->data_is_owned = false;
1783         (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
1784         return (long)txdata;
1785 }
1786 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_txpointer_1free (JNIEnv * env, jclass _b, jlong ptr) {
1787         LDKTransaction *tx = (LDKTransaction*)ptr;
1788         tx->data_is_owned = true;
1789         Transaction_free(*tx);
1790         FREE((void*)ptr);
1791 }
1792 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
1793         // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
1794         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
1795         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
1796         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
1797         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
1798         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
1799         return (long)vec->datalen;
1800 }
1801 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
1802         // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
1803         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
1804         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
1805         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
1806         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
1807         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
1808         vec->data = NULL;
1809         vec->datalen = 0;
1810         return (long)vec;
1811 }
1812
1813 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
1814 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
1815 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
1816 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
1817
1818 """)
1819
1820     with open(sys.argv[3] + "/structs/CommonBase.java", "a") as out_java_struct:
1821         out_java_struct.write("""package org.ldk.structs;
1822 import java.util.LinkedList;
1823 class CommonBase {
1824         long ptr;
1825         LinkedList<Object> ptrs_to = new LinkedList();
1826         protected CommonBase(long ptr) { this.ptr = ptr; }
1827         public long _test_only_get_ptr() { return this.ptr; }
1828 }
1829 """)
1830
1831     in_block_comment = False
1832     cur_block_obj = None
1833
1834     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1835
1836     line_indicates_result_regex = re.compile("^   union (LDKCResult_[A-Za-z_0-9]*Ptr) contents;$")
1837     line_indicates_vec_regex = re.compile("^   (struct |enum |union )?([A-Za-z_0-9]*) \*data;$")
1838     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
1839     line_indicates_trait_regex = re.compile("^   (struct |enum |union )?([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
1840     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
1841     assert(line_indicates_trait_regex.match("   struct LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
1842     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
1843     assert(line_indicates_trait_regex.match("   struct LDKCVec_u8Z (*write)(const void *this_arg);"))
1844     line_field_var_regex = re.compile("^   struct ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1845     assert(line_field_var_regex.match("   struct LDKMessageSendEventsProvider MessageSendEventsProvider;"))
1846     assert(line_field_var_regex.match("   struct LDKChannelPublicKeys pubkeys;"))
1847     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
1848     assert(struct_name_regex.match("typedef struct LDKCVec_u8Z {"))
1849     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
1850
1851     union_enum_items = {}
1852     result_ptr_struct_items = {}
1853     for line in in_h:
1854         if in_block_comment:
1855             if line.endswith("*/\n"):
1856                 in_block_comment = False
1857         elif cur_block_obj is not None:
1858             cur_block_obj  = cur_block_obj + line
1859             if line.startswith("} "):
1860                 field_lines = []
1861                 struct_name = None
1862                 vec_ty = None
1863                 obj_lines = cur_block_obj.split("\n")
1864                 is_opaque = False
1865                 result_contents = None
1866                 is_unitary_enum = False
1867                 is_union_enum = False
1868                 is_union = False
1869                 is_tuple = False
1870                 trait_fn_lines = []
1871                 field_var_lines = []
1872
1873                 for idx, struct_line in enumerate(obj_lines):
1874                     if struct_line.strip().startswith("/*"):
1875                         in_block_comment = True
1876                     if in_block_comment:
1877                         if struct_line.endswith("*/"):
1878                             in_block_comment = False
1879                     else:
1880                         struct_name_match = struct_name_regex.match(struct_line)
1881                         if struct_name_match is not None:
1882                             struct_name = struct_name_match.group(3)
1883                             if struct_name_match.group(1) == "enum":
1884                                 if not struct_name.endswith("_Tag"):
1885                                     is_unitary_enum = True
1886                                 else:
1887                                     is_union_enum = True
1888                             elif struct_name_match.group(1) == "union":
1889                                 is_union = True
1890                         if line_indicates_opaque_regex.match(struct_line):
1891                             is_opaque = True
1892                         result_match = line_indicates_result_regex.match(struct_line)
1893                         if result_match is not None:
1894                             result_contents = result_match.group(1)
1895                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
1896                         if vec_ty_match is not None and struct_name.startswith("LDKCVec_"):
1897                             vec_ty = vec_ty_match.group(2)
1898                         elif struct_name.startswith("LDKC2Tuple_") or struct_name.startswith("LDKC3Tuple_"):
1899                             is_tuple = True
1900                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
1901                         if trait_fn_match is not None:
1902                             trait_fn_lines.append(trait_fn_match)
1903                         field_var_match = line_field_var_regex.match(struct_line)
1904                         if field_var_match is not None:
1905                             field_var_lines.append(field_var_match)
1906                         field_lines.append(struct_line)
1907
1908                 assert(struct_name is not None)
1909                 assert(len(trait_fn_lines) == 0 or not (is_opaque or is_unitary_enum or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
1910                 assert(not is_opaque or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
1911                 assert(not is_unitary_enum or not (len(trait_fn_lines) != 0 or is_opaque or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
1912                 assert(not is_union_enum or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_opaque or is_union or result_contents is not None or vec_ty is not None))
1913                 assert(not is_union or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or result_contents is not None or vec_ty is not None))
1914                 assert(result_contents is None or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or vec_ty is not None))
1915                 assert(vec_ty is None or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or result_contents is not None))
1916
1917                 if is_opaque:
1918                     opaque_structs.add(struct_name)
1919                     with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_struct:
1920                         out_java_struct.write(hu_struct_file_prefix)
1921                         out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase")
1922                         if struct_name.startswith("LDKLocked"):
1923                             out_java_struct.write(" implements AutoCloseable")
1924                         out_java_struct.write(" {\n")
1925                         out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
1926                         if struct_name.startswith("LDKLocked"):
1927                             out_java_struct.write("\t@Override public void close() {\n")
1928                         else:
1929                             out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1930                             out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1931                             out_java_struct.write("\t\tsuper.finalize();\n")
1932                         out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1933                         out_java_struct.write("\t}\n\n")
1934                 elif result_contents is not None:
1935                     assert result_contents in result_ptr_struct_items
1936                     res_ty, err_ty = result_ptr_struct_items[result_contents]
1937                     map_result(struct_name, res_ty, err_ty)
1938                 elif struct_name.startswith("LDKCResult_") and struct_name.endswith("ZPtr"):
1939                     for line in field_lines:
1940                         if line.endswith("*result;"):
1941                             res_ty = line[:-8].strip()
1942                         elif line.endswith("*err;"):
1943                             err_ty = line[:-5].strip()
1944                     result_ptr_struct_items[struct_name] = (res_ty, err_ty)
1945                     result_types.add(struct_name[:-3])
1946                 elif is_tuple:
1947                     map_tuple(struct_name, field_lines)
1948                 elif vec_ty is not None:
1949                     if vec_ty in opaque_structs:
1950                         out_java.write("\tpublic static native long[] " + struct_name + "_arr_info(long vec_ptr);\n")
1951                         write_c("JNIEXPORT jlongArray JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1952                     else:
1953                         out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
1954                         write_c("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1955                     write_c("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
1956                     if vec_ty in opaque_structs:
1957                         write_c("\tjlongArray ret = (*env)->NewLongArray(env, vec->datalen);\n")
1958                         write_c("\tjlong *ret_elems = (*env)->GetPrimitiveArrayCritical(env, ret, NULL);\n")
1959                         write_c("\tfor (size_t i = 0; i < vec->datalen; i++) {\n")
1960                         write_c("\t\tCHECK((((long)vec->data[i].inner) & 1) == 0);\n")
1961                         write_c("\t\tret_elems[i] = (long)vec->data[i].inner | (vec->data[i].is_owned ? 1 : 0);\n")
1962                         write_c("\t}\n")
1963                         write_c("\t(*env)->ReleasePrimitiveArrayCritical(env, ret, ret_elems, 0);\n")
1964                         write_c("\treturn ret;\n")
1965                     else:
1966                         write_c("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
1967                     write_c("}\n")
1968
1969                     ty_info = map_type(vec_ty + " arr_elem", False, None, False, False)
1970                     if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
1971                         out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
1972                         write_c("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *env, jclass _b, j" + ty_info.java_ty + "Array elems){\n")
1973                         write_c("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1974                         write_c("\tret->datalen = (*env)->GetArrayLength(env, elems);\n")
1975                         write_c("\tif (ret->datalen == 0) {\n")
1976                         write_c("\t\tret->data = NULL;\n")
1977                         write_c("\t} else {\n")
1978                         write_c("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1979                         write_c("\t\t" + ty_info.c_ty + " *java_elems = (*env)->GetPrimitiveArrayCritical(env, elems, NULL);\n")
1980                         write_c("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1981                         if ty_info.arg_conv is not None:
1982                             write_c("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1983                             write_c("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1984                             write_c("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1985                             assert ty_info.arg_conv_cleanup is None
1986                         else:
1987                             write_c("\t\t\tret->data[i] = java_elems[i];\n")
1988                         write_c("\t\t}\n")
1989                         write_c("\t\t(*env)->ReleasePrimitiveArrayCritical(env, elems, java_elems, 0);\n")
1990                         write_c("\t}\n")
1991                         write_c("\treturn (long)ret;\n")
1992                         write_c("}\n")
1993
1994                     if ty_info.is_native_primitive:
1995                         clone_fns.add(struct_name.replace("LDK", "") + "_clone")
1996                         write_c("static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n")
1997                         write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.c_ty + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
1998                         write_c("\tmemcpy(ret.data, orig->data, sizeof(" + ty_info.c_ty + ") * ret.datalen);\n")
1999                         write_c("\treturn ret;\n}\n")
2000                     elif (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
2001                         ty_name = "CVec_" + ty_info.rust_obj.replace("LDK", "") + "Z";
2002                         clone_fns.add(ty_name + "_clone")
2003                         write_c("static inline " + struct_name + " " + ty_name + "_clone(const " + struct_name + " *orig) {\n")
2004                         write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.rust_obj + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
2005                         write_c("\tfor (size_t i = 0; i < ret.datalen; i++) {\n")
2006                         write_c("\t\tret.data[i] = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&orig->data[i]);\n")
2007                         write_c("\t}\n\treturn ret;\n}\n")
2008                 elif is_union_enum:
2009                     assert(struct_name.endswith("_Tag"))
2010                     struct_name = struct_name[:-4]
2011                     union_enum_items[struct_name] = {"field_lines": field_lines}
2012                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
2013                     enum_var_name = struct_name.split("_")
2014                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
2015                 elif struct_name in union_enum_items:
2016                     map_complex_enum(struct_name, union_enum_items[struct_name])
2017                 elif is_unitary_enum:
2018                     map_unitary_enum(struct_name, field_lines)
2019                 elif len(trait_fn_lines) > 0:
2020                     trait_structs.add(struct_name)
2021                     map_trait(struct_name, field_var_lines, trait_fn_lines)
2022                 elif struct_name == "LDKTxOut":
2023                     with open(sys.argv[3] + "/structs/TxOut.java", "w") as out_java_struct:
2024                         out_java_struct.write(hu_struct_file_prefix)
2025                         out_java_struct.write("public class TxOut extends CommonBase{\n")
2026                         out_java_struct.write("\tTxOut(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
2027                         out_java_struct.write("\tlong to_c_ptr() { return 0; }\n")
2028                         out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
2029                         out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
2030                         out_java_struct.write("\t\tsuper.finalize();\n")
2031                         out_java_struct.write("\t\tif (ptr != 0) { bindings.TxOut_free(ptr); }\n")
2032                         out_java_struct.write("\t}\n")
2033                         # TODO: TxOut body
2034                         out_java_struct.write("}")
2035                 else:
2036                     pass # Everything remaining is a byte[] or some form
2037                 cur_block_obj = None
2038         else:
2039             fn_ptr = fn_ptr_regex.match(line)
2040             fn_ret_arr = fn_ret_arr_regex.match(line)
2041             reg_fn = reg_fn_regex.match(line)
2042             const_val = const_val_regex.match(line)
2043
2044             if line.startswith("#include <"):
2045                 pass
2046             elif line.startswith("/*"):
2047                 #out_java.write("\t" + line)
2048                 if not line.endswith("*/\n"):
2049                     in_block_comment = True
2050             elif line.startswith("typedef enum "):
2051                 cur_block_obj = line
2052             elif line.startswith("typedef struct "):
2053                 cur_block_obj = line
2054             elif line.startswith("typedef union "):
2055                 cur_block_obj = line
2056             elif fn_ptr is not None:
2057                 map_fn(line, fn_ptr, None, None)
2058             elif fn_ret_arr is not None:
2059                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
2060             elif reg_fn is not None:
2061                 map_fn(line, reg_fn, None, None)
2062             elif const_val_regex is not None:
2063                 # TODO Map const variables
2064                 pass
2065             else:
2066                 assert(line == "\n")
2067
2068     out_java.write("}\n")
2069     for struct_name in opaque_structs:
2070         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
2071             out_java_struct.write("}\n")
2072     for struct_name in trait_structs:
2073         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
2074             out_java_struct.write("}\n")
2075 with open(sys.argv[4], "w") as out_c:
2076     out_c.write(c_file_pfx)
2077     for ty in c_array_class_caches:
2078         if ty + "_clz" in c_file:
2079             out_c.write("static jclass " + ty + "_clz = NULL;\n")
2080     out_c.write("JNIEXPORT void Java_org_ldk_impl_bindings_init_1class_1cache(JNIEnv * env, jclass _b) {\n")
2081     for ty in c_array_class_caches:
2082         if ty + "_clz" in c_file:
2083             out_c.write("\t" + ty + "_clz = (*env)->FindClass(env, \"" + ty.replace("arr_of_", "[") + "\");\n")
2084             out_c.write("\tCHECK(" + ty + "_clz != NULL);\n")
2085             out_c.write("\t" + ty + "_clz = (*env)->NewGlobalRef(env, " + ty + "_clz);\n")
2086     out_c.write("}\n")
2087     out_c.write(c_file)