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