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