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