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