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