5ba69e6d09082e262f02ad5889b4fc96e0f234c9
[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 class TypeInfo:
10     def __init__(self, rust_obj, java_ty, java_fn_ty_arg, c_ty, passed_as_ptr, is_ptr, var_name, arr_len, arr_access):
11         self.rust_obj = rust_obj
12         self.java_ty = java_ty
13         self.java_fn_ty_arg = java_fn_ty_arg
14         self.c_ty = c_ty
15         self.passed_as_ptr = passed_as_ptr
16         self.is_ptr = is_ptr
17         self.var_name = var_name
18         self.arr_len = arr_len
19         self.arr_access = arr_access
20
21 class ConvInfo:
22     def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, ret_conv, ret_conv_name):
23         assert(ty_info.c_ty is not None)
24         assert(ty_info.java_ty is not None)
25         assert(arg_name is not None)
26         self.passed_as_ptr = ty_info.passed_as_ptr
27         self.rust_obj = ty_info.rust_obj
28         self.c_ty = ty_info.c_ty
29         self.java_ty = ty_info.java_ty
30         self.java_fn_ty_arg = ty_info.java_fn_ty_arg
31         self.arg_name = arg_name
32         self.arg_conv = arg_conv
33         self.arg_conv_name = arg_conv_name
34         self.ret_conv = ret_conv
35         self.ret_conv_name = ret_conv_name
36
37     def print_ty(self):
38         out_c.write(self.c_ty)
39         out_java.write(self.java_ty)
40
41     def print_name(self):
42         if self.arg_name != "":
43             out_java.write(" " + self.arg_name)
44             out_c.write(" " + self.arg_name)
45         else:
46             out_java.write(" arg")
47             out_c.write(" arg")
48 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
49 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
50 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
51 clone_fns = set()
52 with open(sys.argv[1]) as in_h:
53     for line in in_h:
54         reg_fn = reg_fn_regex.match(line)
55         if reg_fn is not None:
56             if reg_fn.group(2).endswith("_clone"):
57                 clone_fns.add(reg_fn.group(2))
58             continue
59         arr_fn = fn_ret_arr_regex.match(line)
60         if arr_fn is not None:
61             if arr_fn.group(2).endswith("_clone"):
62                 clone_fns.add(arr_fn.group(2))
63             continue
64
65 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[4], "w") as out_c:
66     opaque_structs = set()
67     trait_structs = set()
68     unitary_enums = set()
69
70     def camel_to_snake(s):
71         # Convert camel case to snake case, in a way that appears to match cbindgen
72         con = "_"
73         ret = ""
74         lastchar = ""
75         lastund = False
76         for char in s:
77             if lastchar.isupper():
78                 if not char.isupper() and not lastund:
79                     ret = ret + "_"
80                     lastund = True
81                 else:
82                     lastund = False
83                 ret = ret + lastchar.lower()
84             else:
85                 ret = ret + lastchar
86                 if char.isupper() and not lastund:
87                     ret = ret + "_"
88                     lastund = True
89                 else:
90                     lastund = False
91             lastchar = char
92             if char.isnumeric():
93                 lastund = True
94         return (ret + lastchar.lower()).strip("_")
95
96     var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([0-9]*)\]")
97     var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
98     def java_c_types(fn_arg, ret_arr_len):
99         fn_arg = fn_arg.strip()
100         if fn_arg.startswith("MUST_USE_RES "):
101             fn_arg = fn_arg[13:]
102         is_const = False
103         if fn_arg.startswith("const "):
104             fn_arg = fn_arg[6:]
105             is_const = True
106
107         is_ptr = False
108         take_by_ptr = False
109         rust_obj = None
110         arr_access = None
111         if fn_arg.startswith("LDKThirtyTwoBytes"):
112             fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
113             assert var_is_arr_regex.match(fn_arg[8:])
114             rust_obj = "LDKThirtyTwoBytes"
115             arr_access = "data"
116         if fn_arg.startswith("LDKPublicKey"):
117             fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
118             assert var_is_arr_regex.match(fn_arg[8:])
119             rust_obj = "LDKPublicKey"
120             arr_access = "compressed_form"
121         #if fn_arg.startswith("LDKSignature"):
122         #    fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
123         #    assert var_is_arr_regex.match(fn_arg[8:])
124         #    rust_obj = "LDKSignature"
125
126         if fn_arg.startswith("void"):
127             java_ty = "void"
128             c_ty = "void"
129             fn_ty_arg = "V"
130             fn_arg = fn_arg[4:].strip()
131         elif fn_arg.startswith("bool"):
132             java_ty = "boolean"
133             c_ty = "jboolean"
134             fn_ty_arg = "Z"
135             fn_arg = fn_arg[4:].strip()
136         elif fn_arg.startswith("uint8_t"):
137             java_ty = "byte"
138             c_ty = "jbyte"
139             fn_ty_arg = "B"
140             fn_arg = fn_arg[7:].strip()
141         elif fn_arg.startswith("uint16_t"):
142             java_ty = "short"
143             c_ty = "jshort"
144             fn_ty_arg = "S"
145             fn_arg = fn_arg[8:].strip()
146         elif fn_arg.startswith("uint32_t"):
147             java_ty = "int"
148             c_ty = "jint"
149             fn_ty_arg = "I"
150             fn_arg = fn_arg[8:].strip()
151         elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
152             java_ty = "long"
153             c_ty = "jlong"
154             fn_ty_arg = "J"
155             if fn_arg.startswith("uint64_t"):
156                 fn_arg = fn_arg[8:].strip()
157             else:
158                 fn_arg = fn_arg[9:].strip()
159         elif is_const and fn_arg.startswith("char *"):
160             java_ty = "String"
161             c_ty = "const char*"
162             fn_ty_arg = "Ljava/lang/String;"
163             fn_arg = fn_arg[6:].strip()
164         else:
165             ma = var_ty_regex.match(fn_arg)
166             if ma.group(1).strip() in unitary_enums:
167                 java_ty = ma.group(1).strip()
168                 c_ty = "jclass"
169                 fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
170                 fn_arg = ma.group(2).strip()
171                 rust_obj = ma.group(1).strip()
172                 take_by_ptr = True
173             else:
174                 java_ty = "long"
175                 c_ty = "jlong"
176                 fn_ty_arg = "J"
177                 fn_arg = ma.group(2).strip()
178                 rust_obj = ma.group(1).strip()
179                 take_by_ptr = True
180
181         if fn_arg.startswith(" *") or fn_arg.startswith("*"):
182             fn_arg = fn_arg.replace("*", "").strip()
183             is_ptr = True
184             c_ty = "jlong"
185             java_ty = "long"
186             fn_ty_arg = "J"
187
188         var_is_arr = var_is_arr_regex.match(fn_arg)
189         if var_is_arr is not None or ret_arr_len is not None:
190             assert(not take_by_ptr)
191             assert(not is_ptr)
192             java_ty = java_ty + "[]"
193             c_ty = c_ty + "Array"
194             if var_is_arr is not None:
195                 if var_is_arr.group(1) == "":
196                     return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
197                         passed_as_ptr=False, is_ptr=False, var_name="arg", arr_len=var_is_arr.group(2), arr_access=arr_access)
198                 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
199                     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)
200         return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg=fn_ty_arg, c_ty=c_ty, passed_as_ptr=is_ptr or take_by_ptr,
201             is_ptr=is_ptr, var_name=fn_arg, arr_len=None, arr_access=None)
202
203     def map_type(fn_arg, print_void, ret_arr_len, is_free):
204         ty_info = java_c_types(fn_arg, ret_arr_len)
205
206         if ty_info.c_ty == "void":
207             if not print_void:
208                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
209                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
210
211         if ty_info.c_ty.endswith("Array"):
212             arr_len = ty_info.arr_len
213             if arr_len is not None:
214                 arr_name = ty_info.var_name
215             else:
216                 arr_name = "ret"
217                 arr_len = ret_arr_len
218             assert(ty_info.c_ty == "jbyteArray")
219             if ty_info.rust_obj is not None:
220                 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n" + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
221                 arr_access = ("", "." + ty_info.arr_access)
222             else:
223                 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n" + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
224                 arr_access = ("*", "")
225             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
226                 arg_conv = arg_conv,
227                 arg_conv_name = arr_name + "_ref",
228                 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
229                     "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", " + arr_access[0],
230                     arr_access[1] + ");"),
231                 ret_conv_name = arr_name + "_arr")
232         elif ty_info.var_name != "":
233             # If we have a parameter name, print it (noting that it may indicate its a pointer)
234             if ty_info.rust_obj is not None:
235                 assert(ty_info.passed_as_ptr)
236                 opaque_arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv;\n"
237                 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
238                 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
239                 if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns and not ty_info.is_ptr and not is_free:
240                     # 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.
241                     opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
242                     opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&" + ty_info.var_name + "_conv);"
243                 if not ty_info.is_ptr:
244                     if ty_info.rust_obj in unitary_enums:
245                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
246                             arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
247                             arg_conv_name = ty_info.var_name + "_conv",
248                             ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
249                             ret_conv_name = ty_info.var_name + "_conv")
250                     if ty_info.rust_obj in opaque_structs:
251                         ret_conv_suf = ";\nDO_ASSERT((((long)" + ty_info.var_name + "_var.inner) & 1) == 0); // We rely on a free low bit, malloc guarantees this.\n"
252                         ret_conv_suf = ret_conv_suf + "DO_ASSERT((((long)&" + ty_info.var_name + "_var) & 1) == 0); // We rely on a free low bit, pointer alignment guarantees this.\n"
253                         ret_conv_suf = ret_conv_suf + "long " + ty_info.var_name + "_ref;\n"
254                         ret_conv_suf = ret_conv_suf + "if (" + ty_info.var_name + "_var.is_owned) {\n"
255                         ret_conv_suf = ret_conv_suf + "\t" + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner | 1;\n"
256                         ret_conv_suf = ret_conv_suf + "} else {\n"
257                         ret_conv_suf = ret_conv_suf + "\t" + ty_info.var_name + "_ref = (long)&" + ty_info.var_name + "_var;\n"
258                         ret_conv_suf = ret_conv_suf + "}"
259                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
260                             arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv",
261                             ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", ret_conv_suf),
262                             ret_conv_name = ty_info.var_name + "_ref")
263                     base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
264                     if ty_info.rust_obj in trait_structs:
265                         if not is_free:
266                             base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
267                             base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
268                             base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
269                         else:
270                             base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
271                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
272                             arg_conv = base_conv,
273                             arg_conv_name = ty_info.var_name + "_conv",
274                             ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE")
275                     if ty_info.rust_obj != "LDKu8slice":
276                         # Don't bother free'ing slices passed in - Rust doesn't auto-free the
277                         # underlying unlike Vecs, and it gives Java more freedom.
278                         base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
279                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
280                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
281                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
282                 else:
283                     assert(not is_free)
284                     if ty_info.rust_obj in opaque_structs:
285                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
286                             arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv",
287                             ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
288                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
289                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
290                         arg_conv_name = ty_info.var_name + "_conv",
291                         ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
292             elif ty_info.is_ptr:
293                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
294                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
295             elif ty_info.java_ty == "String":
296                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
297                     arg_conv = None, arg_conv_name = None,
298                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
299             else:
300                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
301                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
302         elif not print_void:
303             # We don't have a parameter name, and want one, just call it arg
304             if ty_info.rust_obj is not None:
305                 assert(not is_free or ty_info.rust_obj not in opaque_structs);
306                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
307                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
308                     arg_conv_name = "arg_conv",
309                     ret_conv = None, ret_conv_name = None)
310             else:
311                 assert(not is_free)
312                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
313                     arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
314         else:
315             # We don't have a parameter name, and don't want one (cause we're returning)
316             if ty_info.rust_obj is not None:
317                 if not ty_info.is_ptr:
318                     if ty_info.rust_obj in unitary_enums:
319                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
320                             arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
321                             arg_conv_name = "ret",
322                             ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
323                     if ty_info.rust_obj in opaque_structs:
324                         # If we're returning a newly-allocated struct, we don't want Rust to ever
325                         # free, instead relying on the Java GC to lose the ref. We undo this in
326                         # any _free function.
327                         # To avoid any issues, we first assert that the incoming object is non-ref.
328                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
329                             ret_conv = (ty_info.rust_obj + " ret = ", ";"),
330                             ret_conv_name = "((long)ret.inner) | (ret.is_owned ? 1 : 0)",
331                             arg_conv = None, arg_conv_name = None)
332                     else:
333                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
334                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
335                             ret_conv_name = "(long)ret",
336                             arg_conv = None, arg_conv_name = None)
337                 else:
338                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
339                         ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
340                         arg_conv = None, arg_conv_name = None)
341             else:
342                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
343                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
344
345     def map_fn(line, re_match, ret_arr_len, c_call_string):
346         out_java.write("\t// " + line)
347         out_java.write("\tpublic static native ")
348         out_c.write("JNIEXPORT ")
349
350         is_free = re_match.group(2).endswith("_free")
351         struct_meth = re_match.group(2).split("_")[0]
352
353         ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
354         ret_info.print_ty()
355
356         if ret_info.ret_conv is not None:
357             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
358
359         out_java.write(" " + re_match.group(2) + "(")
360         out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
361
362         arg_names = []
363         takes_self = False
364         args_known = not ret_info.passed_as_ptr or ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs
365         for idx, arg in enumerate(re_match.group(3).split(',')):
366             if idx != 0:
367                 out_java.write(", ")
368             if arg != "void":
369                 out_c.write(", ")
370             arg_conv_info = map_type(arg, False, None, is_free)
371             if arg_conv_info.c_ty != "void":
372                 arg_conv_info.print_ty()
373                 arg_conv_info.print_name()
374             if arg_conv_info.arg_name == "this_arg":
375                 takes_self = True
376             if arg_conv_info.passed_as_ptr and not arg_conv_info.rust_obj in opaque_structs:
377                 if not arg_conv_info.rust_obj in trait_structs and not arg_conv_info.rust_obj in unitary_enums:
378                     print(re_match.group(2) + " bad - " + arg_conv_info.rust_obj)
379                     args_known = False
380             arg_names.append(arg_conv_info)
381
382         out_java_struct = None
383         if "LDK" + struct_meth in opaque_structs and not is_free:
384             out_java_struct = open(sys.argv[3] + "/structs/" + struct_meth + ".java", "a")
385             if not args_known:
386                 out_java_struct.write("\t// Skipped " + re_match.group(2) + "\n")
387                 out_java_struct.close()
388                 out_java_struct = None
389             else:
390                 out_java_struct.write("\tpublic ")
391                 meth_n = re_match.group(2)[len(struct_meth) + 1:]
392                 if ret_info.rust_obj == "LDK" + struct_meth:
393                     out_java_struct.write(struct_meth + "(")
394                 elif ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs:
395                     out_java_struct.write(ret_info.rust_obj.replace("LDK", "") + " " + meth_n + "(")
396                 else:
397                     out_java_struct.write(ret_info.java_ty + " " + meth_n + "(")
398                 for idx, arg in enumerate(arg_names):
399                     if idx != 0:
400                         if not takes_self or idx > 1:
401                             out_java_struct.write(", ")
402                     if arg.java_ty != "void" and arg.arg_name != "this_arg":
403                         if arg.passed_as_ptr:
404                             if arg.rust_obj in opaque_structs or arg.rust_obj in trait_structs:
405                                 out_java_struct.write(arg.rust_obj.replace("LDK", "") + " " + arg.arg_name)
406                             else:
407                                 out_java_struct.write(arg.rust_obj + " " + arg.arg_name)
408                         else:
409                             out_java_struct.write(arg.java_ty + " " + arg.arg_name)
410
411
412         out_java.write(");\n")
413         out_c.write(") {\n")
414         if out_java_struct is not None:
415             out_java_struct.write(") {\n")
416
417         for info in arg_names:
418             if info.arg_conv is not None:
419                 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
420
421         if ret_info.ret_conv is not None:
422             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
423         else:
424             out_c.write("\treturn ");
425
426         if c_call_string is None:
427             out_c.write(re_match.group(2) + "(")
428         else:
429             out_c.write(c_call_string)
430         for idx, info in enumerate(arg_names):
431             if info.arg_conv_name is not None:
432                 if idx != 0:
433                     out_c.write(", ")
434                 elif c_call_string is not None:
435                     continue
436                 out_c.write(info.arg_conv_name)
437         out_c.write(")")
438         if ret_info.ret_conv is not None:
439             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
440             out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
441         else:
442             out_c.write(";")
443         out_c.write("\n}\n\n")
444         if out_java_struct is not None:
445             out_java_struct.write("\t\t")
446             if ret_info.rust_obj == "LDK" + struct_meth:
447                 out_java_struct.write("super(")
448             elif ret_info.java_ty != "void" and not ret_info.passed_as_ptr:
449                 out_java_struct.write(ret_info.java_ty + " ret = ")
450             elif ret_info.java_ty != "void":
451                 out_java_struct.write(ret_info.rust_obj.replace("LDK", "") + " ret = ")
452                 if ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs:
453                     out_java_struct.write("new " + ret_info.rust_obj.replace("LDK", "") + "(null, ")
454             out_java_struct.write("bindings." + re_match.group(2) + "(")
455             for idx, info in enumerate(arg_names):
456                 if idx != 0:
457                     out_java_struct.write(", ")
458                 if info.arg_name == "this_arg":
459                     out_java_struct.write("this.ptr")
460                 elif info.passed_as_ptr and info.rust_obj in opaque_structs:
461                     out_java_struct.write(info.arg_name + ".ptr & ~1")
462                 elif info.passed_as_ptr and info.rust_obj in trait_structs:
463                     out_java_struct.write(info.arg_name + ".ptr")
464                 else:
465                     out_java_struct.write(info.arg_name)
466             out_java_struct.write(")")
467             if ret_info.rust_obj == "LDK" + struct_meth:
468                 out_java_struct.write(");\n")
469             elif ret_info.rust_obj in opaque_structs:
470                 out_java_struct.write(");\n")
471             elif ret_info.rust_obj in trait_structs:
472                 out_java_struct.write(");\n\t\tret.ptrs_to.add(this);\n")
473             else:
474                 out_java_struct.write(";\n")
475
476             for info in arg_names:
477                 if info.arg_name == "this_arg":
478                     pass
479                 elif info.passed_as_ptr and (info.rust_obj in opaque_structs or info.rust_obj in trait_structs):
480                     out_java_struct.write("\t\tthis.ptrs_to.add(" + info.arg_name + ");\n")
481
482             if ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
483                 out_java_struct.write("\t\treturn ret;\n")
484             out_java_struct.write("\t}\n\n")
485             out_java_struct.close()
486
487     def map_unitary_enum(struct_name, field_lines):
488         with open(sys.argv[3] + "/enums/" + struct_name + ".java", "w") as out_java_enum:
489             out_java_enum.write("package org.ldk.enums;\n\n")
490             unitary_enums.add(struct_name)
491             out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
492             out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
493             ord_v = 0
494             for idx, struct_line in enumerate(field_lines):
495                 if idx == 0:
496                     out_java_enum.write("public enum " + struct_name + " {\n")
497                 elif idx == len(field_lines) - 3:
498                     assert(struct_line.endswith("_Sentinel,"))
499                 elif idx == len(field_lines) - 2:
500                     out_java_enum.write("\t; static native void init();\n")
501                     out_java_enum.write("\tstatic { init(); }\n")
502                     out_java_enum.write("}")
503                     out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
504                 elif idx == len(field_lines) - 1:
505                     assert(struct_line == "")
506                 else:
507                     out_java_enum.write(struct_line + "\n")
508                     out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
509                     ord_v = ord_v + 1
510             out_c.write("\t}\n")
511             out_c.write("\tabort();\n")
512             out_c.write("}\n")
513
514             ord_v = 0
515             out_c.write("static jclass " + struct_name + "_class = NULL;\n")
516             for idx, struct_line in enumerate(field_lines):
517                 if idx > 0 and idx < len(field_lines) - 3:
518                     variant = struct_line.strip().strip(",")
519                     out_c.write("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
520             out_c.write("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
521             out_c.write("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
522             out_c.write("\tDO_ASSERT(" + struct_name + "_class != NULL);\n")
523             for idx, struct_line in enumerate(field_lines):
524                 if idx > 0 and idx < len(field_lines) - 3:
525                     variant = struct_line.strip().strip(",")
526                     out_c.write("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
527                     out_c.write("\tDO_ASSERT(" + struct_name + "_" + variant + " != NULL);\n")
528             out_c.write("}\n")
529             out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
530             out_c.write("\tswitch (val) {\n")
531             for idx, struct_line in enumerate(field_lines):
532                 if idx > 0 and idx < len(field_lines) - 3:
533                     variant = struct_line.strip().strip(",")
534                     out_c.write("\t\tcase " + variant + ":\n")
535                     out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
536                     ord_v = ord_v + 1
537             out_c.write("\t\tdefault: abort();\n")
538             out_c.write("\t}\n")
539             out_c.write("}\n\n")
540
541     def map_complex_enum(struct_name, union_enum_items):
542         tag_field_lines = union_enum_items["field_lines"]
543         init_meth_jty_strs = {}
544         for idx, struct_line in enumerate(tag_field_lines):
545             if idx == 0:
546                 out_java.write("\tpublic static class " + struct_name + " {\n")
547                 out_java.write("\t\tprivate " + struct_name + "() {}\n")
548             elif idx == len(tag_field_lines) - 3:
549                 assert(struct_line.endswith("_Sentinel,"))
550             elif idx == len(tag_field_lines) - 2:
551                 out_java.write("\t\tstatic native void init();\n")
552                 out_java.write("\t}\n")
553             elif idx == len(tag_field_lines) - 1:
554                 assert(struct_line == "")
555             else:
556                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
557                 out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
558                 out_c.write("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
559                 out_c.write("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
560                 init_meth_jty_str = ""
561                 init_meth_params = ""
562                 init_meth_body = ""
563                 if "LDK" + var_name in union_enum_items:
564                     enum_var_lines = union_enum_items["LDK" + var_name]
565                     for idx, field in enumerate(enum_var_lines):
566                         if idx != 0 and idx < len(enum_var_lines) - 2:
567                             field_ty = java_c_types(field.strip(' ;'), None)
568                             out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.var_name + ";\n")
569                             init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
570                             if idx > 1:
571                                 init_meth_params = init_meth_params + ", "
572                             init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.var_name
573                             init_meth_body = init_meth_body + "this." + field_ty.var_name + " = " + field_ty.var_name + "; "
574                     out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
575                     out_java.write(init_meth_body)
576                     out_java.write("}\n")
577                 out_java.write("\t\t}\n")
578                 init_meth_jty_strs[var_name] = init_meth_jty_str
579         out_java.write("\tstatic { " + struct_name + ".init(); }\n")
580         out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
581
582         out_c.write("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
583         for idx, struct_line in enumerate(tag_field_lines):
584             if idx != 0 and idx < len(tag_field_lines) - 3:
585                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
586                 out_c.write("\t" + struct_name + "_" + var_name + "_class =\n")
587                 out_c.write("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
588                 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_class != NULL);\n")
589                 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")
590                 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_meth != NULL);\n")
591         out_c.write("}\n")
592         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")
593         out_c.write("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
594         out_c.write("\tswitch(obj->tag) {\n")
595         for idx, struct_line in enumerate(tag_field_lines):
596             if idx != 0 and idx < len(tag_field_lines) - 3:
597                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
598                 out_c.write("\t\tcase " + struct_name + "_" + var_name + ": {\n")
599                 c_params_text = ""
600                 if "LDK" + var_name in union_enum_items:
601                     enum_var_lines = union_enum_items["LDK" + var_name]
602                     for idx, field in enumerate(enum_var_lines):
603                         if idx != 0 and idx < len(enum_var_lines) - 2:
604                             field_map = map_type(field.strip(' ;'), False, None, False)
605                             if field_map.ret_conv is not None:
606                                 out_c.write("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t").replace("_env", "env"))
607                                 out_c.write("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
608                                 out_c.write(field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
609                                 c_params_text = c_params_text + ", " + field_map.ret_conv_name
610                             else:
611                                 c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
612                 out_c.write("\t\t\treturn (*env)->NewObject(env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
613                 out_c.write("\t\t}\n")
614         out_c.write("\t\tdefault: abort();\n")
615         out_c.write("\t}\n}\n")
616
617     def map_trait(struct_name, field_var_lines, trait_fn_lines):
618         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_trait:
619             out_c.write("typedef struct " + struct_name + "_JCalls {\n")
620             out_c.write("\tatomic_size_t refcnt;\n")
621             out_c.write("\tJavaVM *vm;\n")
622             out_c.write("\tjweak o;\n")
623             for var_line in field_var_lines:
624                 if var_line.group(1) in trait_structs:
625                     out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
626             for fn_line in trait_fn_lines:
627                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
628                     out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
629             out_c.write("} " + struct_name + "_JCalls;\n")
630
631             out_java_trait.write("package org.ldk.structs;\n\n")
632             out_java_trait.write("import org.ldk.impl.bindings;\n\n")
633             out_java_trait.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
634             out_java_trait.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
635             out_java_trait.write("\tpublic " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg")
636             for var_line in field_var_lines:
637                 if var_line.group(1) in trait_structs:
638                     out_java_trait.write(", bindings." + var_line.group(1) + " " + var_line.group(2))
639             out_java_trait.write(") {\n")
640             out_java_trait.write("\t\tsuper(bindings." + struct_name + "_new(arg")
641             for var_line in field_var_lines:
642                 if var_line.group(1) in trait_structs:
643                     out_java_trait.write(", " + var_line.group(2))
644             out_java_trait.write("));\n")
645             out_java_trait.write("\t\tthis.ptrs_to.add(arg);\n")
646             out_java_trait.write("\t}\n")
647             out_java_trait.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
648             out_java_trait.write("\tprotected void finalize() throws Throwable {\n")
649             out_java_trait.write("\t\tbindings." + struct_name.replace("LDK","") + "_free(ptr); super.finalize();\n")
650             out_java_trait.write("\t}\n\n")
651             out_java_trait.write("}\n")
652
653             out_java.write("\tpublic interface " + struct_name + " {\n")
654             java_meths = []
655             for fn_line in trait_fn_lines:
656                 java_meth_descr = "("
657                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
658                     ret_ty_info = java_c_types(fn_line.group(1), None)
659
660                     out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
661                     is_const = fn_line.group(3) is not None
662                     out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
663                     if is_const:
664                         out_c.write("const void* this_arg")
665                     else:
666                         out_c.write("void* this_arg")
667
668                     arg_names = []
669                     for idx, arg in enumerate(fn_line.group(4).split(',')):
670                         if arg == "":
671                             continue
672                         if idx >= 2:
673                             out_java.write(", ")
674                         out_c.write(", ")
675                         arg_conv_info = map_type(arg, True, None, False)
676                         out_c.write(arg.strip())
677                         out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
678                         arg_names.append(arg_conv_info)
679                         java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
680                     java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
681                     java_meths.append(java_meth_descr)
682
683                     out_java.write(");\n")
684                     out_c.write(") {\n")
685                     out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
686                     out_c.write("\tJNIEnv *env;\n")
687                     out_c.write("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
688
689                     for arg_info in arg_names:
690                         if arg_info.ret_conv is not None:
691                             out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "env"));
692                             out_c.write(arg_info.arg_name)
693                             out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "env") + "\n")
694
695                     out_c.write("\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tDO_ASSERT(obj != NULL);\n")
696                     if ret_ty_info.c_ty.endswith("Array"):
697                         assert(ret_ty_info.c_ty == "jbyteArray")
698                         out_c.write("\tjbyteArray jret = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.group(2) + "_meth")
699                     elif not ret_ty_info.passed_as_ptr:
700                         out_c.write("\treturn (*env)->Call" + ret_ty_info.java_ty.title() + "Method(env, obj, j_calls->" + fn_line.group(2) + "_meth")
701                     else:
702                         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");
703
704                     for arg_info in arg_names:
705                         if arg_info.ret_conv is not None:
706                             out_c.write(", " + arg_info.ret_conv_name)
707                         else:
708                             out_c.write(", " + arg_info.arg_name)
709                     out_c.write(");\n");
710                     if ret_ty_info.c_ty.endswith("Array"):
711                         out_c.write("\t" + ret_ty_info.rust_obj + " ret;\n")
712                         out_c.write("\t(*env)->GetByteArrayRegion(env, jret, 0, " + ret_ty_info.arr_len + ", ret." + ret_ty_info.arr_access + ");\n")
713                         out_c.write("\treturn ret;\n")
714
715                     if ret_ty_info.passed_as_ptr:
716                         out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
717                         out_c.write("\tFREE(ret);\n")
718                         out_c.write("\treturn res;\n")
719                     out_c.write("}\n")
720                 elif fn_line.group(2) == "free":
721                     out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
722                     out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
723                     out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
724                     out_c.write("\t\tJNIEnv *env;\n")
725                     out_c.write("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
726                     out_c.write("\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n")
727                     out_c.write("\t\tFREE(j_calls);\n")
728                     out_c.write("\t}\n}\n")
729
730             # Write out a clone function whether we need one or not, as we use them in moving to rust
731             out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
732             out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
733             out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
734             for var_line in field_var_lines:
735                 if var_line.group(1) in trait_structs:
736                     out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
737             out_c.write("\treturn (void*) this_arg;\n")
738             out_c.write("}\n")
739
740             out_java.write("\t}\n")
741
742             out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
743             out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
744             for var_line in field_var_lines:
745                 if var_line.group(1) in trait_structs:
746                     out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
747                     out_c.write(", jobject " + var_line.group(2))
748             out_java.write(");\n")
749             out_c.write(") {\n")
750
751             out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
752             out_c.write("\tDO_ASSERT(c != NULL);\n")
753             out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
754             out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
755             out_c.write("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
756             out_c.write("\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n")
757             for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
758                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
759                     out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
760                     out_c.write("\tDO_ASSERT(calls->" + fn_line.group(2) + "_meth != NULL);\n")
761             out_c.write("\n\t" + struct_name + " ret = {\n")
762             out_c.write("\t\t.this_arg = (void*) calls,\n")
763             for fn_line in trait_fn_lines:
764                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
765                     out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
766                 elif fn_line.group(2) == "free":
767                     out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
768                 else:
769                     out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
770             for var_line in field_var_lines:
771                 if var_line.group(1) in trait_structs:
772                     out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
773             out_c.write("\t};\n")
774             for var_line in field_var_lines:
775                 if var_line.group(1) in trait_structs:
776                     out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
777             out_c.write("\treturn ret;\n")
778             out_c.write("}\n")
779
780             out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
781             for var_line in field_var_lines:
782                 if var_line.group(1) in trait_structs:
783                     out_c.write(", jobject " + var_line.group(2))
784             out_c.write(") {\n")
785             out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
786             out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
787             for var_line in field_var_lines:
788                 if var_line.group(1) in trait_structs:
789                     out_c.write(", " + var_line.group(2))
790             out_c.write(");\n")
791             out_c.write("\treturn (long)res_ptr;\n")
792             out_c.write("}\n")
793
794             out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
795             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")
796             out_c.write("\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n")
797             out_c.write("\tDO_ASSERT(ret != NULL);\n")
798             out_c.write("\treturn ret;\n")
799             out_c.write("}\n")
800
801             for fn_line in trait_fn_lines:
802                 # For now, just disable enabling the _call_log - we don't know how to inverse-map String
803                 is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
804                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
805                     dummy_line = fn_line.group(1) + struct_name + "_call_" + fn_line.group(2) + " " + struct_name + "* arg" + fn_line.group(4) + "\n"
806                     map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(arg_conv->" + fn_line.group(2) + ")(arg_conv->this_arg")
807
808     out_c.write("""#include \"org_ldk_impl_bindings.h\"
809 #include <rust_types.h>
810 #include <lightning.h>
811 #include <string.h>
812 #include <stdatomic.h>
813 """)
814
815     if sys.argv[4] == "false":
816         out_c.write("#define MALLOC(a, _) malloc(a)\n")
817         out_c.write("#define FREE free\n")
818         out_c.write("#define DO_ASSERT(a) (void)(a)\n")
819     else:
820         out_c.write("""#include <assert.h>
821 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
822
823 // Running a leak check across all the allocations and frees of the JDK is a mess,
824 // so instead we implement our own naive leak checker here, relying on the -wrap
825 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
826 // and free'd in Rust or C across the generated bindings shared library.
827 #include <threads.h>
828 #include <execinfo.h>
829 #include <unistd.h>
830 static mtx_t allocation_mtx;
831
832 void __attribute__((constructor)) init_mtx() {
833         DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
834 }
835
836 #define BT_MAX 128
837 typedef struct allocation {
838         struct allocation* next;
839         void* ptr;
840         const char* struct_name;
841         void* bt[BT_MAX];
842         int bt_len;
843 } allocation;
844 static allocation* allocation_ll = NULL;
845
846 void* __real_malloc(size_t len);
847 void* __real_calloc(size_t nmemb, size_t len);
848 static void new_allocation(void* res, const char* struct_name) {
849         allocation* new_alloc = __real_malloc(sizeof(allocation));
850         new_alloc->ptr = res;
851         new_alloc->struct_name = struct_name;
852         new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
853         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
854         new_alloc->next = allocation_ll;
855         allocation_ll = new_alloc;
856         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
857 }
858 static void* MALLOC(size_t len, const char* struct_name) {
859         void* res = __real_malloc(len);
860         new_allocation(res, struct_name);
861         return res;
862 }
863 void __real_free(void* ptr);
864 static void alloc_freed(void* ptr) {
865         allocation* p = NULL;
866         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
867         allocation* it = allocation_ll;
868         while (it->ptr != ptr) { p = it; it = it->next; }
869         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
870         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
871         DO_ASSERT(it->ptr == ptr);
872         __real_free(it);
873 }
874 static void FREE(void* ptr) {
875         alloc_freed(ptr);
876         __real_free(ptr);
877 }
878
879 void* __wrap_malloc(size_t len) {
880         void* res = __real_malloc(len);
881         new_allocation(res, "malloc call");
882         return res;
883 }
884 void* __wrap_calloc(size_t nmemb, size_t len) {
885         void* res = __real_calloc(nmemb, len);
886         new_allocation(res, "calloc call");
887         return res;
888 }
889 void __wrap_free(void* ptr) {
890         alloc_freed(ptr);
891         __real_free(ptr);
892 }
893
894 void* __real_realloc(void* ptr, size_t newlen);
895 void* __wrap_realloc(void* ptr, size_t len) {
896         alloc_freed(ptr);
897         void* res = __real_realloc(ptr, len);
898         new_allocation(res, "realloc call");
899         return res;
900 }
901 void __wrap_reallocarray(void* ptr, size_t new_sz) {
902         // Rust doesn't seem to use reallocarray currently
903         assert(false);
904 }
905
906 void __attribute__((destructor)) check_leaks() {
907         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
908                 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
909                 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
910                 fprintf(stderr, "\\n\\n");
911         }
912         DO_ASSERT(allocation_ll == NULL);
913 }
914 """)
915     out_java.write("""package org.ldk.impl;
916 import org.ldk.enums.*;
917
918 public class bindings {
919         public static class VecOrSliceDef {
920                 public long dataptr;
921                 public long datalen;
922                 public long stride;
923                 public VecOrSliceDef(long dataptr, long datalen, long stride) {
924                         this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
925                 }
926         }
927         static {
928                 System.loadLibrary(\"lightningjni\");
929                 init(java.lang.Enum.class, VecOrSliceDef.class);
930         }
931         static native void init(java.lang.Class c, java.lang.Class slicedef);
932
933         public static native boolean deref_bool(long ptr);
934         public static native long deref_long(long ptr);
935         public static native void free_heap_ptr(long ptr);
936         public static native byte[] read_bytes(long ptr, long len);
937         public static native byte[] get_u8_slice_bytes(long slice_ptr);
938         public static native long bytes_to_u8_vec(byte[] bytes);
939         public static native long new_txpointer_copy_data(byte[] txdata);
940         public static native long vec_slice_len(long vec);
941         public static native long new_empty_slice_vec();
942
943 """)
944     out_c.write("""
945 static jmethodID ordinal_meth = NULL;
946 static jmethodID slicedef_meth = NULL;
947 static jclass slicedef_cls = NULL;
948 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
949         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
950         DO_ASSERT(ordinal_meth != NULL);
951         slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
952         DO_ASSERT(slicedef_meth != NULL);
953         slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
954         DO_ASSERT(slicedef_cls != NULL);
955 }
956
957 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
958         return *((bool*)ptr);
959 }
960 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
961         return *((long*)ptr);
962 }
963 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
964         FREE((void*)ptr);
965 }
966 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
967         jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
968         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
969         return ret_arr;
970 }
971 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
972         LDKu8slice *slice = (LDKu8slice*)slice_ptr;
973         jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
974         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
975         return ret_arr;
976 }
977 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
978         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
979         vec->datalen = (*_env)->GetArrayLength(_env, bytes);
980         vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
981         (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
982         return (long)vec;
983 }
984 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
985         LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
986         txdata->datalen = (*env)->GetArrayLength(env, bytes);
987         txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
988         txdata->data_is_owned = true;
989         (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
990         return (long)txdata;
991 }
992 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
993         // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
994         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
995         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
996         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
997         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
998         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
999         return (long)vec->datalen;
1000 }
1001 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
1002         // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
1003         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
1004         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
1005         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
1006         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
1007         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
1008         vec->data = NULL;
1009         vec->datalen = 0;
1010         return (long)vec;
1011 }
1012
1013 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
1014 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
1015 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
1016 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
1017
1018 """)
1019
1020     with open(sys.argv[3] + "/structs/CommonBase.java", "a") as out_java_struct:
1021         out_java_struct.write("""package org.ldk.structs;
1022 import java.util.LinkedList;
1023 class CommonBase {
1024         final long ptr;
1025         LinkedList<Object> ptrs_to = new LinkedList();
1026         protected CommonBase(long ptr) { this.ptr = ptr; }
1027         public long _test_only_get_ptr() { return this.ptr; }
1028 }
1029 """)
1030
1031     # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
1032     out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
1033     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
1034     out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)MALLOC(sizeof(LDKSecretKey), \"LDKSecretKey\");\n") # TODO: rm me
1035     out_c.write("\treturn (long)key;\n") # TODO: rm me
1036     out_c.write("}\n") # TODO: rm me
1037
1038     in_block_comment = False
1039     cur_block_obj = None
1040
1041     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1042
1043     line_indicates_result_regex = re.compile("^   (LDKCResultPtr_[A-Za-z_0-9]*) contents;$")
1044     line_indicates_vec_regex = re.compile("^   ([A-Za-z_0-9]*) \*data;$")
1045     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
1046     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
1047     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
1048     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
1049     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
1050     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1051     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
1052     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
1053     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
1054     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
1055     struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
1056     assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
1057
1058     result_templ_structs = set()
1059     union_enum_items = {}
1060     result_ptr_struct_items = {}
1061     for line in in_h:
1062         if in_block_comment:
1063             if line.endswith("*/\n"):
1064                 in_block_comment = False
1065         elif cur_block_obj is not None:
1066             cur_block_obj  = cur_block_obj + line
1067             if line.startswith("} "):
1068                 field_lines = []
1069                 struct_name = None
1070                 vec_ty = None
1071                 obj_lines = cur_block_obj.split("\n")
1072                 is_opaque = False
1073                 result_contents = None
1074                 is_unitary_enum = False
1075                 is_union_enum = False
1076                 is_union = False
1077                 is_tuple = False
1078                 trait_fn_lines = []
1079                 field_var_lines = []
1080
1081                 for idx, struct_line in enumerate(obj_lines):
1082                     if struct_line.strip().startswith("/*"):
1083                         in_block_comment = True
1084                     if in_block_comment:
1085                         if struct_line.endswith("*/"):
1086                             in_block_comment = False
1087                     else:
1088                         struct_name_match = struct_name_regex.match(struct_line)
1089                         if struct_name_match is not None:
1090                             struct_name = struct_name_match.group(3)
1091                             if struct_name_match.group(1) == "enum":
1092                                 if not struct_name.endswith("_Tag"):
1093                                     is_unitary_enum = True
1094                                 else:
1095                                     is_union_enum = True
1096                             elif struct_name_match.group(1) == "union":
1097                                 is_union = True
1098                         if line_indicates_opaque_regex.match(struct_line):
1099                             is_opaque = True
1100                         result_match = line_indicates_result_regex.match(struct_line)
1101                         if result_match is not None:
1102                             result_contents = result_match.group(1)
1103                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
1104                         if vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
1105                             vec_ty = vec_ty_match.group(1)
1106                         elif struct_name.startswith("LDKC2TupleTempl_") or struct_name.startswith("LDKC3TupleTempl_"):
1107                             is_tuple = True
1108                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
1109                         if trait_fn_match is not None:
1110                             trait_fn_lines.append(trait_fn_match)
1111                         field_var_match = line_field_var_regex.match(struct_line)
1112                         if field_var_match is not None:
1113                             field_var_lines.append(field_var_match)
1114                         field_lines.append(struct_line)
1115
1116                 assert(struct_name is not None)
1117                 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))
1118                 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))
1119                 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))
1120                 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))
1121                 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))
1122                 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))
1123                 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))
1124
1125                 if is_opaque:
1126                     opaque_structs.add(struct_name)
1127                     with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_struct:
1128                         out_java_struct.write("package org.ldk.structs;\n\n")
1129                         out_java_struct.write("import org.ldk.impl.bindings;\n")
1130                         out_java_struct.write("import org.ldk.enums.*;\n\n")
1131                         out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
1132                         out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
1133                         out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1134                         out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1135                         out_java_struct.write("\t\tbindings." + struct_name.replace("LDK","") + "_free(ptr); super.finalize();\n")
1136                         out_java_struct.write("\t}\n\n")
1137                 elif result_contents is not None:
1138                     result_templ_structs.add(struct_name)
1139                     assert result_contents in result_ptr_struct_items
1140                 elif struct_name.startswith("LDKCResultPtr_"):
1141                     for line in field_lines:
1142                         if line.endswith("*result;"):
1143                             res_ty = line[:-8].strip()
1144                         elif line.endswith("*err;"):
1145                             err_ty = line[:-5].strip()
1146                     result_ptr_struct_items[struct_name] = (res_ty, err_ty)
1147                 elif is_tuple:
1148                     out_java.write("\tpublic static native long " + struct_name + "_new(")
1149                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *_env, jclass _b")
1150                     for idx, line in enumerate(field_lines):
1151                         if idx != 0 and idx < len(field_lines) - 2:
1152                             ty_info = java_c_types(line.strip(';'), None)
1153                             if idx != 1:
1154                                 out_java.write(", ")
1155                             e = chr(ord('a') + idx - 1)
1156                             out_java.write(ty_info.java_ty + " " + e)
1157                             out_c.write(", " + ty_info.c_ty + " " + e)
1158                     out_java.write(");\n")
1159                     out_c.write(") {\n")
1160                     out_c.write("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1161                     for idx, line in enumerate(field_lines):
1162                         if idx != 0 and idx < len(field_lines) - 2:
1163                             ty_info = map_type(line.strip(';'), False, None, False)
1164                             e = chr(ord('a') + idx - 1)
1165                             if ty_info.arg_conv is not None:
1166                                 out_c.write("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
1167                                 out_c.write("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
1168                             else:
1169                                 out_c.write("\tret->" + e + " = " + e + ";\n")
1170                     out_c.write("\treturn (long)ret;\n")
1171                     out_c.write("}\n")
1172                 elif vec_ty is not None:
1173                     if vec_ty in opaque_structs:
1174                         out_java.write("\tpublic static native long[] " + struct_name + "_arr_info(long vec_ptr);\n")
1175                         out_c.write("JNIEXPORT jlongArray JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1176                     else:
1177                         out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
1178                         out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1179                     out_c.write("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
1180                     if vec_ty in opaque_structs:
1181                         out_c.write("\tjlongArray ret = (*env)->NewLongArray(env, vec->datalen);\n")
1182                         out_c.write("\tjlong *ret_elems = (*env)->GetPrimitiveArrayCritical(env, ret, NULL);\n")
1183                         out_c.write("\tfor (size_t i = 0; i < vec->datalen; i++) {\n")
1184                         out_c.write("\t\tDO_ASSERT((((long)vec->data[i].inner) & 1) == 0);\n")
1185                         out_c.write("\t\tret_elems[i] = (long)vec->data[i].inner | (vec->data[i].is_owned ? 1 : 0);\n")
1186                         out_c.write("\t}\n")
1187                         out_c.write("\t(*env)->ReleasePrimitiveArrayCritical(env, ret, ret_elems, 0);\n")
1188                         out_c.write("\treturn ret;\n")
1189                     else:
1190                         out_c.write("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
1191                     out_c.write("}\n")
1192
1193                     ty_info = map_type(vec_ty + " arr_elem", False, None, False)
1194                     if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
1195                         out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
1196                         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")
1197                         out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1198                         out_c.write("\tret->datalen = (*env)->GetArrayLength(env, elems);\n")
1199                         out_c.write("\tif (ret->datalen == 0) {\n")
1200                         out_c.write("\t\tret->data = NULL;\n")
1201                         out_c.write("\t} else {\n")
1202                         out_c.write("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1203                         out_c.write("\t\t" + ty_info.c_ty + " *java_elems = (*env)->GetPrimitiveArrayCritical(env, elems, NULL);\n")
1204                         out_c.write("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1205                         if ty_info.arg_conv is not None:
1206                             out_c.write("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1207                             out_c.write("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1208                             out_c.write("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1209                         else:
1210                             out_c.write("\t\t\tret->data[i] = java_elems[i];\n")
1211                         out_c.write("\t\t}\n")
1212                         out_c.write("\t\t(*env)->ReleasePrimitiveArrayCritical(env, elems, java_elems, 0);\n")
1213                         out_c.write("\t}\n")
1214                         out_c.write("\treturn (long)ret;\n")
1215                         out_c.write("}\n")
1216                 elif is_union_enum:
1217                     assert(struct_name.endswith("_Tag"))
1218                     struct_name = struct_name[:-4]
1219                     union_enum_items[struct_name] = {"field_lines": field_lines}
1220                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
1221                     enum_var_name = struct_name.split("_")
1222                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
1223                 elif struct_name in union_enum_items:
1224                     map_complex_enum(struct_name, union_enum_items[struct_name])
1225                 elif is_unitary_enum:
1226                     map_unitary_enum(struct_name, field_lines)
1227                 elif len(trait_fn_lines) > 0:
1228                     trait_structs.add(struct_name)
1229                     map_trait(struct_name, field_var_lines, trait_fn_lines)
1230                 cur_block_obj = None
1231         else:
1232             fn_ptr = fn_ptr_regex.match(line)
1233             fn_ret_arr = fn_ret_arr_regex.match(line)
1234             reg_fn = reg_fn_regex.match(line)
1235             const_val = const_val_regex.match(line)
1236
1237             if line.startswith("#include <"):
1238                 pass
1239             elif line.startswith("/*"):
1240                 #out_java.write("\t" + line)
1241                 if not line.endswith("*/\n"):
1242                     in_block_comment = True
1243             elif line.startswith("typedef enum "):
1244                 cur_block_obj = line
1245             elif line.startswith("typedef struct "):
1246                 cur_block_obj = line
1247             elif line.startswith("typedef union "):
1248                 cur_block_obj = line
1249             elif line.startswith("typedef "):
1250                 alias_match =  struct_alias_regex.match(line)
1251                 if alias_match.group(1) in result_templ_structs:
1252                     out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
1253                     out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
1254                     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")
1255                     out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
1256                     out_c.write("}\n")
1257                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1inner (JNIEnv * env, jclass _a, jlong arg) {\n")
1258                     contents_ty = alias_match.group(1).replace("LDKCResultTempl", "LDKCResultPtr")
1259                     res_ty, err_ty = result_ptr_struct_items[contents_ty]
1260                     out_c.write("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
1261                     out_c.write("\tif (val->result_ok) {\n")
1262                     if res_ty not in opaque_structs:
1263                         out_c.write("\t\treturn (long)val->contents.result;\n")
1264                     else:
1265                         out_c.write("\t\treturn (long)(val->contents.result->inner) | (val->contents.result->is_owned ? 1 : 0);\n")
1266                     out_c.write("\t} else {\n")
1267                     if err_ty not in opaque_structs:
1268                         out_c.write("\t\treturn (long)val->contents.err;\n")
1269                     else:
1270                         out_c.write("\t\treturn (long)(val->contents.err->inner) | (val->contents.err->is_owned ? 1 : 0);\n")
1271                     out_c.write("\t}\n}\n")
1272                 pass
1273             elif fn_ptr is not None:
1274                 map_fn(line, fn_ptr, None, None)
1275             elif fn_ret_arr is not None:
1276                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1277             elif reg_fn is not None:
1278                 map_fn(line, reg_fn, None, None)
1279             elif const_val_regex is not None:
1280                 # TODO Map const variables
1281                 pass
1282             else:
1283                 assert(line == "\n")
1284
1285     out_java.write("}\n")
1286     for struct_name in opaque_structs:
1287         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1288             out_java_struct.write("}\n")