Map tuples and ThirtyTwoBytes into array.
[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                 if not ty_info.is_ptr:
204                     if ty_info.rust_obj in unitary_enums:
205                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
206                             arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
207                             arg_conv_name = ty_info.var_name + "_conv",
208                             ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
209                             ret_conv_name = ty_info.var_name + "_conv")
210                     base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
211                     if ty_info.rust_obj in trait_structs:
212                         if not is_free:
213                             base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
214                             base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
215                             base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
216                         else:
217                             base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
218                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
219                             arg_conv = base_conv,
220                             arg_conv_name = ty_info.var_name + "_conv",
221                             ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE")
222                     if ty_info.rust_obj != "LDKu8slice":
223                         # Don't bother free'ing slices passed in - Rust doesn't auto-free the
224                         # underlying unlike Vecs, and it gives Java more freedom.
225                         base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
226                     if ty_info.rust_obj in opaque_structs:
227                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
228                             arg_conv = base_conv + "\n" + ty_info.var_name + "_conv.is_owned = true;",
229                             arg_conv_name = ty_info.var_name + "_conv",
230                             ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
231
232                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
233                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
234                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
235                 else:
236                     assert(not is_free)
237                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
238                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
239                         arg_conv_name = ty_info.var_name + "_conv",
240                         ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
241             elif ty_info.is_ptr:
242                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
243                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
244             elif ty_info.java_ty == "String":
245                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
246                     arg_conv = None, arg_conv_name = None,
247                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
248             else:
249                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
250                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
251         elif not print_void:
252             # We don't have a parameter name, and want one, just call it arg
253             if ty_info.rust_obj is not None:
254                 assert(not is_free or ty_info.rust_obj not in opaque_structs);
255                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
256                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
257                     arg_conv_name = "arg_conv",
258                     ret_conv = None, ret_conv_name = None)
259             else:
260                 assert(not is_free)
261                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
262                     arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
263         else:
264             # We don't have a parameter name, and don't want one (cause we're returning)
265             if ty_info.rust_obj is not None:
266                 if not ty_info.is_ptr:
267                     if ty_info.rust_obj in unitary_enums:
268                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
269                             arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
270                             arg_conv_name = "ret",
271                             ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
272                     if ty_info.rust_obj in opaque_structs:
273                         # If we're returning a newly-allocated struct, we don't want Rust to ever
274                         # free, instead relying on the Java GC to lose the ref. We undo this in
275                         # any _free function.
276                         # To avoid any issues, we first assert that the incoming object is non-ref.
277                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
278                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";\nDO_ASSERT(ret->is_owned);\nret->is_owned = false;"),
279                             ret_conv_name = "(long)ret",
280                             arg_conv = None, arg_conv_name = None)
281                     else:
282                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
283                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
284                             ret_conv_name = "(long)ret",
285                             arg_conv = None, arg_conv_name = None)
286                 else:
287                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
288                         ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
289                         arg_conv = None, arg_conv_name = None)
290             else:
291                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
292                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
293
294     def map_fn(line, re_match, ret_arr_len, c_call_string):
295         out_java.write("\t// " + line)
296         out_java.write("\tpublic static native ")
297         out_c.write("JNIEXPORT ")
298
299         ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
300         ret_info.print_ty()
301         if ret_info.ret_conv is not None:
302             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
303
304         out_java.write(" " + re_match.group(2) + "(")
305         out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
306
307         arg_names = []
308         for idx, arg in enumerate(re_match.group(3).split(',')):
309             if idx != 0:
310                 out_java.write(", ")
311             if arg != "void":
312                 out_c.write(", ")
313             arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
314             if arg_conv_info.c_ty != "void":
315                 arg_conv_info.print_ty()
316                 arg_conv_info.print_name()
317             arg_names.append(arg_conv_info)
318
319         out_java.write(");\n")
320         out_c.write(") {\n")
321
322         for info in arg_names:
323             if info.arg_conv is not None:
324                 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
325
326         if ret_info.ret_conv is not None:
327             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
328         else:
329             out_c.write("\treturn ");
330
331         if c_call_string is None:
332             out_c.write(re_match.group(2) + "(")
333         else:
334             out_c.write(c_call_string)
335         for idx, info in enumerate(arg_names):
336             if info.arg_conv_name is not None:
337                 if idx != 0:
338                     out_c.write(", ")
339                 elif c_call_string is not None:
340                     continue
341                 out_c.write(info.arg_conv_name)
342         out_c.write(")")
343         if ret_info.ret_conv is not None:
344             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
345             out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
346         else:
347             out_c.write(";")
348         out_c.write("\n}\n\n")
349
350     def map_unitary_enum(struct_name, field_lines):
351         with open(sys.argv[3] + "/" + struct_name + ".java", "w") as out_java_enum:
352             out_java_enum.write("package org.ldk.enums;\n\n")
353             unitary_enums.add(struct_name)
354             out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
355             out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
356             ord_v = 0
357             for idx, struct_line in enumerate(field_lines):
358                 if idx == 0:
359                     out_java_enum.write("public enum " + struct_name + " {\n")
360                 elif idx == len(field_lines) - 3:
361                     assert(struct_line.endswith("_Sentinel,"))
362                 elif idx == len(field_lines) - 2:
363                     out_java_enum.write("\t; static native void init();\n")
364                     out_java_enum.write("\tstatic { init(); }\n")
365                     out_java_enum.write("}")
366                     out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
367                 elif idx == len(field_lines) - 1:
368                     assert(struct_line == "")
369                 else:
370                     out_java_enum.write(struct_line + "\n")
371                     out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
372                     ord_v = ord_v + 1
373             out_c.write("\t}\n")
374             out_c.write("\tabort();\n")
375             out_c.write("}\n")
376
377             ord_v = 0
378             out_c.write("static jclass " + struct_name + "_class = NULL;\n")
379             for idx, struct_line in enumerate(field_lines):
380                 if idx > 0 and idx < len(field_lines) - 3:
381                     variant = struct_line.strip().strip(",")
382                     out_c.write("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
383             out_c.write("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
384             out_c.write("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
385             out_c.write("\tDO_ASSERT(" + struct_name + "_class != NULL);\n")
386             for idx, struct_line in enumerate(field_lines):
387                 if idx > 0 and idx < len(field_lines) - 3:
388                     variant = struct_line.strip().strip(",")
389                     out_c.write("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
390                     out_c.write("\tDO_ASSERT(" + struct_name + "_" + variant + " != NULL);\n")
391             out_c.write("}\n")
392             out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
393             out_c.write("\tswitch (val) {\n")
394             for idx, struct_line in enumerate(field_lines):
395                 if idx > 0 and idx < len(field_lines) - 3:
396                     variant = struct_line.strip().strip(",")
397                     out_c.write("\t\tcase " + variant + ":\n")
398                     out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
399                     ord_v = ord_v + 1
400             out_c.write("\t\tdefault: abort();\n")
401             out_c.write("\t}\n")
402             out_c.write("}\n\n")
403
404     def map_complex_enum(struct_name, union_enum_items):
405         tag_field_lines = union_enum_items["field_lines"]
406         init_meth_jty_strs = {}
407         for idx, struct_line in enumerate(tag_field_lines):
408             if idx == 0:
409                 out_java.write("\tpublic static class " + struct_name + " {\n")
410                 out_java.write("\t\tprivate " + struct_name + "() {}\n")
411             elif idx == len(tag_field_lines) - 3:
412                 assert(struct_line.endswith("_Sentinel,"))
413             elif idx == len(tag_field_lines) - 2:
414                 out_java.write("\t\tstatic native void init();\n")
415                 out_java.write("\t}\n")
416             elif idx == len(tag_field_lines) - 1:
417                 assert(struct_line == "")
418             else:
419                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
420                 out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
421                 out_c.write("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
422                 out_c.write("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
423                 init_meth_jty_str = ""
424                 init_meth_params = ""
425                 init_meth_body = ""
426                 if "LDK" + var_name in union_enum_items:
427                     enum_var_lines = union_enum_items["LDK" + var_name]
428                     for idx, field in enumerate(enum_var_lines):
429                         if idx != 0 and idx < len(enum_var_lines) - 2:
430                             field_ty = java_c_types(field.strip(' ;'), None)
431                             out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.var_name + ";\n")
432                             init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
433                             if idx > 1:
434                                 init_meth_params = init_meth_params + ", "
435                             init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.var_name
436                             init_meth_body = init_meth_body + "this." + field_ty.var_name + " = " + field_ty.var_name + "; "
437                     out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
438                     out_java.write(init_meth_body)
439                     out_java.write("}\n")
440                 out_java.write("\t\t}\n")
441                 init_meth_jty_strs[var_name] = init_meth_jty_str
442         out_java.write("\tstatic { " + struct_name + ".init(); }\n")
443         out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
444
445         out_c.write("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
446         for idx, struct_line in enumerate(tag_field_lines):
447             if idx != 0 and idx < len(tag_field_lines) - 3:
448                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
449                 out_c.write("\t" + struct_name + "_" + var_name + "_class =\n")
450                 out_c.write("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
451                 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_class != NULL);\n")
452                 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")
453                 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_meth != NULL);\n")
454         out_c.write("}\n")
455         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")
456         out_c.write("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
457         out_c.write("\tswitch(obj->tag) {\n")
458         for idx, struct_line in enumerate(tag_field_lines):
459             if idx != 0 and idx < len(tag_field_lines) - 3:
460                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
461                 out_c.write("\t\tcase " + struct_name + "_" + var_name + ": {\n")
462                 c_params_text = ""
463                 if "LDK" + var_name in union_enum_items:
464                     enum_var_lines = union_enum_items["LDK" + var_name]
465                     for idx, field in enumerate(enum_var_lines):
466                         if idx != 0 and idx < len(enum_var_lines) - 2:
467                             field_map = map_type(field.strip(' ;'), False, None, False)
468                             if field_map.ret_conv is not None:
469                                 out_c.write("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t").replace("_env", "env"))
470                                 out_c.write("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
471                                 out_c.write(field_map.ret_conv[1] + "\n")
472                                 c_params_text = c_params_text + ", " + field_map.ret_conv_name
473                             else:
474                                 c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
475                 out_c.write("\t\t\treturn (*env)->NewObject(env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
476                 out_c.write("\t\t}\n")
477         out_c.write("\t\tdefault: abort();\n")
478         out_c.write("\t}\n}\n")
479
480     def map_trait(struct_name, field_var_lines, trait_fn_lines):
481         out_c.write("typedef struct " + struct_name + "_JCalls {\n")
482         out_c.write("\tatomic_size_t refcnt;\n")
483         out_c.write("\tJavaVM *vm;\n")
484         out_c.write("\tjobject o;\n")
485         for var_line in field_var_lines:
486             if var_line.group(1) in trait_structs:
487                 out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
488         for fn_line in trait_fn_lines:
489             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
490                 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
491         out_c.write("} " + struct_name + "_JCalls;\n")
492
493         out_java.write("\tpublic interface " + struct_name + " {\n")
494         java_meths = []
495         for fn_line in trait_fn_lines:
496             java_meth_descr = "("
497             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
498                 ret_ty_info = java_c_types(fn_line.group(1), None)
499
500                 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
501                 is_const = fn_line.group(3) is not None
502                 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
503                 if is_const:
504                     out_c.write("const void* this_arg")
505                 else:
506                     out_c.write("void* this_arg")
507
508                 arg_names = []
509                 for idx, arg in enumerate(fn_line.group(4).split(',')):
510                     if arg == "":
511                         continue
512                     if idx >= 2:
513                         out_java.write(", ")
514                     out_c.write(", ")
515                     arg_conv_info = map_type(arg, True, None, False)
516                     out_c.write(arg.strip())
517                     out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
518                     arg_names.append(arg_conv_info)
519                     java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
520                 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
521                 java_meths.append(java_meth_descr)
522
523                 out_java.write(");\n")
524                 out_c.write(") {\n")
525                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
526                 out_c.write("\tJNIEnv *env;\n")
527                 out_c.write("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
528
529                 for arg_info in arg_names:
530                     if arg_info.ret_conv is not None:
531                         out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "env"));
532                         out_c.write(arg_info.arg_name)
533                         out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "env") + "\n")
534
535                 if ret_ty_info.c_ty.endswith("Array"):
536                     assert(ret_ty_info.c_ty == "jbyteArray")
537                     out_c.write("\tjbyteArray jret = (*env)->CallObjectMethod(env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth")
538                 elif not ret_ty_info.passed_as_ptr:
539                     out_c.write("\treturn (*env)->Call" + ret_ty_info.java_ty.title() + "Method(env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth")
540                 else:
541                     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");
542
543                 for arg_info in arg_names:
544                     if arg_info.ret_conv is not None:
545                         out_c.write(", " + arg_info.ret_conv_name)
546                     else:
547                         out_c.write(", " + arg_info.arg_name)
548                 out_c.write(");\n");
549                 if ret_ty_info.c_ty.endswith("Array"):
550                     out_c.write("\tLDKThirtyTwoBytes ret;\n")
551                     out_c.write("\t(*env)->GetByteArrayRegion(env, jret, 0, " + ret_ty_info.arr_len + ", ret.data);\n")
552                     out_c.write("\treturn ret;\n")
553
554                 if ret_ty_info.passed_as_ptr:
555                     out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
556                     out_c.write("\tFREE(ret);\n")
557                     out_c.write("\treturn res;\n")
558                 out_c.write("}\n")
559             elif fn_line.group(2) == "free":
560                 out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
561                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
562                 out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
563                 out_c.write("\t\tJNIEnv *env;\n")
564                 out_c.write("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
565                 out_c.write("\t\t(*env)->DeleteGlobalRef(env, j_calls->o);\n")
566                 out_c.write("\t\tFREE(j_calls);\n")
567                 out_c.write("\t}\n}\n")
568
569         # Write out a clone function whether we need one or not, as we use them in moving to rust
570         out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
571         out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
572         out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
573         for var_line in field_var_lines:
574             if var_line.group(1) in trait_structs:
575                 out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
576         out_c.write("\treturn (void*) this_arg;\n")
577         out_c.write("}\n")
578
579         out_java.write("\t}\n")
580
581         out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
582         out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
583         for var_line in field_var_lines:
584             if var_line.group(1) in trait_structs:
585                 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
586                 out_c.write(", jobject " + var_line.group(2))
587         out_java.write(");\n")
588         out_c.write(") {\n")
589
590         out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
591         out_c.write("\tDO_ASSERT(c != NULL);\n")
592         out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
593         out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
594         out_c.write("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
595         out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
596         for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
597             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
598                 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
599                 out_c.write("\tDO_ASSERT(calls->" + fn_line.group(2) + "_meth != NULL);\n")
600         out_c.write("\n\t" + struct_name + " ret = {\n")
601         out_c.write("\t\t.this_arg = (void*) calls,\n")
602         for fn_line in trait_fn_lines:
603             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
604                 out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
605             elif fn_line.group(2) == "free":
606                 out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
607             else:
608                 out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
609         for var_line in field_var_lines:
610             if var_line.group(1) in trait_structs:
611                 out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
612         out_c.write("\t};\n")
613         for var_line in field_var_lines:
614             if var_line.group(1) in trait_structs:
615                 out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
616         out_c.write("\treturn ret;\n")
617         out_c.write("}\n")
618
619         out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
620         for var_line in field_var_lines:
621             if var_line.group(1) in trait_structs:
622                 out_c.write(", jobject " + var_line.group(2))
623         out_c.write(") {\n")
624         out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
625         out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
626         for var_line in field_var_lines:
627             if var_line.group(1) in trait_structs:
628                 out_c.write(", " + var_line.group(2))
629         out_c.write(");\n")
630         out_c.write("\treturn (long)res_ptr;\n")
631         out_c.write("}\n")
632
633         out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
634         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")
635         out_c.write("\treturn ((" + struct_name + "_JCalls*)val)->o;\n")
636         out_c.write("}\n")
637
638         for fn_line in trait_fn_lines:
639             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
640             is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
641             if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
642                 dummy_line = fn_line.group(1) + struct_name + "_call_" + fn_line.group(2) + " " + struct_name + "* arg" + fn_line.group(4) + "\n"
643                 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")
644
645     out_c.write("""#include \"org_ldk_impl_bindings.h\"
646 #include <rust_types.h>
647 #include <lightning.h>
648 #include <string.h>
649 #include <stdatomic.h>
650 """)
651
652     if sys.argv[4] == "false":
653         out_c.write("#define MALLOC(a, _) malloc(a)\n")
654         out_c.write("#define FREE free\n")
655         out_c.write("#define DO_ASSERT(a) (void)(a)\n")
656     else:
657         out_c.write("""#include <assert.h>
658 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
659
660 #include <threads.h>
661 static mtx_t allocation_mtx;
662
663 void __attribute__((constructor)) init_mtx() {
664         DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
665 }
666
667 typedef struct allocation {
668         struct allocation* next;
669         void* ptr;
670         const char* struct_name;
671 } allocation;
672 static allocation* allocation_ll = NULL;
673
674 static void* MALLOC(size_t len, const char* struct_name) {
675         void* res = malloc(len);
676         allocation* new_alloc = malloc(sizeof(allocation));
677         new_alloc->ptr = res;
678         new_alloc->struct_name = struct_name;
679         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
680         new_alloc->next = allocation_ll;
681         allocation_ll = new_alloc;
682         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
683         return res;
684 }
685
686 static void FREE(void* ptr) {
687         allocation* p = NULL;
688         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
689         allocation* it = allocation_ll;
690         while (it->ptr != ptr) { p = it; it = it->next; }
691         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
692         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
693         DO_ASSERT(it->ptr == ptr);
694         free(it);
695         free(ptr);
696 }
697
698 void __attribute__((destructor)) check_leaks() {
699         for (allocation* a = allocation_ll; a != NULL; a = a->next) { fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr); }
700         DO_ASSERT(allocation_ll == NULL);
701 }
702 """)
703     out_java.write("""package org.ldk.impl;
704 import org.ldk.enums.*;
705
706 public class bindings {
707         public static class VecOrSliceDef {
708                 public long dataptr;
709                 public long datalen;
710                 public long stride;
711                 public VecOrSliceDef(long dataptr, long datalen, long stride) {
712                         this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
713                 }
714         }
715         static {
716                 System.loadLibrary(\"lightningjni\");
717                 init(java.lang.Enum.class, VecOrSliceDef.class);
718         }
719         static native void init(java.lang.Class c, java.lang.Class slicedef);
720
721         public static native boolean deref_bool(long ptr);
722         public static native long deref_long(long ptr);
723         public static native void free_heap_ptr(long ptr);
724         public static native byte[] read_bytes(long ptr, long len);
725         public static native byte[] get_u8_slice_bytes(long slice_ptr);
726         public static native long bytes_to_u8_vec(byte[] bytes);
727         public static native long new_txpointer_copy_data(byte[] txdata);
728         public static native long vec_slice_len(long vec);
729         public static native long new_empty_slice_vec();
730
731 """)
732     out_c.write("""
733 static jmethodID ordinal_meth = NULL;
734 static jmethodID slicedef_meth = NULL;
735 static jclass slicedef_cls = NULL;
736 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
737         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
738         DO_ASSERT(ordinal_meth != NULL);
739         slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
740         DO_ASSERT(slicedef_meth != NULL);
741         slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
742         DO_ASSERT(slicedef_cls != NULL);
743 }
744
745 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
746         return *((bool*)ptr);
747 }
748 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
749         return *((long*)ptr);
750 }
751 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
752         FREE((void*)ptr);
753 }
754 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
755         jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
756         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
757         return ret_arr;
758 }
759 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
760         LDKu8slice *slice = (LDKu8slice*)slice_ptr;
761         jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
762         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
763         return ret_arr;
764 }
765 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
766         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
767         vec->datalen = (*_env)->GetArrayLength(_env, bytes);
768         vec->data = (uint8_t*)malloc(vec->datalen); // May be freed by rust, so don't track allocation
769         (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
770         return (long)vec;
771 }
772 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
773         LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
774         txdata->datalen = (*env)->GetArrayLength(env, bytes);
775         txdata->data = (uint8_t*)malloc(txdata->datalen); // May be freed by rust, so don't track allocation
776         txdata->data_is_owned = true;
777         (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
778         return (long)txdata;
779 }
780 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
781         // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
782         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
783         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
784         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
785         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
786         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
787         return (long)vec->datalen;
788 }
789 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
790         // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
791         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
792         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
793         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
794         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
795         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
796         vec->data = NULL;
797         vec->datalen = 0;
798         return (long)vec;
799 }
800
801 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
802 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
803 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
804 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
805
806 """)
807
808     # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
809     out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
810     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
811     out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)MALLOC(sizeof(LDKSecretKey), \"LDKSecretKey\");\n") # TODO: rm me
812     out_c.write("\treturn (long)key;\n") # TODO: rm me
813     out_c.write("}\n") # TODO: rm me
814
815     in_block_comment = False
816     cur_block_obj = None
817
818     fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
819     fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
820     reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
821     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
822
823     line_indicates_result_regex = re.compile("^   bool result_ok;$")
824     line_indicates_vec_regex = re.compile("^   ([A-Za-z_0-9]*) \*data;$")
825     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
826     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
827     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
828     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
829     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
830     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
831     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
832     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
833     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
834     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
835     struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
836     assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
837
838     result_templ_structs = set()
839     union_enum_items = {}
840     for line in in_h:
841         if in_block_comment:
842             if line.endswith("*/\n"):
843                 in_block_comment = False
844         elif cur_block_obj is not None:
845             cur_block_obj  = cur_block_obj + line
846             if line.startswith("} "):
847                 field_lines = []
848                 struct_name = None
849                 vec_ty = None
850                 obj_lines = cur_block_obj.split("\n")
851                 is_opaque = False
852                 is_result = False
853                 is_unitary_enum = False
854                 is_union_enum = False
855                 is_union = False
856                 is_tuple = False
857                 trait_fn_lines = []
858                 field_var_lines = []
859
860                 for idx, struct_line in enumerate(obj_lines):
861                     if struct_line.strip().startswith("/*"):
862                         in_block_comment = True
863                     if in_block_comment:
864                         if struct_line.endswith("*/"):
865                             in_block_comment = False
866                     else:
867                         struct_name_match = struct_name_regex.match(struct_line)
868                         if struct_name_match is not None:
869                             struct_name = struct_name_match.group(3)
870                             if struct_name_match.group(1) == "enum":
871                                 if not struct_name.endswith("_Tag"):
872                                     is_unitary_enum = True
873                                 else:
874                                     is_union_enum = True
875                             elif struct_name_match.group(1) == "union":
876                                 is_union = True
877                         if line_indicates_opaque_regex.match(struct_line):
878                             is_opaque = True
879                         elif line_indicates_result_regex.match(struct_line):
880                             is_result = True
881                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
882                         if vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
883                             vec_ty = vec_ty_match.group(1)
884                         elif struct_name.startswith("LDKC2TupleTempl_") or struct_name.startswith("LDKC3TupleTempl_"):
885                             is_tuple = True
886                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
887                         if trait_fn_match is not None:
888                             trait_fn_lines.append(trait_fn_match)
889                         field_var_match = line_field_var_regex.match(struct_line)
890                         if field_var_match is not None:
891                             field_var_lines.append(field_var_match)
892                         field_lines.append(struct_line)
893
894                 assert(struct_name is not None)
895                 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))
896                 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))
897                 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))
898                 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))
899                 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))
900                 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))
901                 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))
902
903                 if is_opaque:
904                     opaque_structs.add(struct_name)
905                     out_java.write("\tpublic static native long " + struct_name + "_optional_none();\n")
906                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1optional_1none (JNIEnv * env, jclass _a) {\n")
907                     out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
908                     out_c.write("\tret->inner = NULL;\n")
909                     out_c.write("\treturn (long)ret;\n")
910                     out_c.write("}\n")
911                 elif is_result:
912                     result_templ_structs.add(struct_name)
913                 elif is_tuple:
914                     out_java.write("\tpublic static native long " + struct_name + "_new(")
915                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *_env, jclass _b")
916                     for idx, line in enumerate(field_lines):
917                         if idx != 0 and idx < len(field_lines) - 2:
918                             ty_info = java_c_types(line.strip(';'), None)
919                             if idx != 1:
920                                 out_java.write(", ")
921                             e = chr(ord('a') + idx - 1)
922                             out_java.write(ty_info.java_ty + " " + e)
923                             out_c.write(", " + ty_info.c_ty + " " + e)
924                     out_java.write(");\n")
925                     out_c.write(") {\n")
926                     out_c.write("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
927                     for idx, line in enumerate(field_lines):
928                         if idx != 0 and idx < len(field_lines) - 2:
929                             ty_info = map_type(line.strip(';'), False, None, False)
930                             e = chr(ord('a') + idx - 1)
931                             if ty_info.arg_conv is not None:
932                                 out_c.write("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
933                                 out_c.write("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
934                             else:
935                                 out_c.write("\tret->" + e + " = " + e + ";\n")
936                     out_c.write("\treturn (long)ret;\n")
937                     out_c.write("}\n")
938                 elif vec_ty is not None:
939                     out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
940                     out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
941                     out_c.write("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
942                     out_c.write("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
943                     out_c.write("}\n")
944
945                     ty_info = map_type(vec_ty + " arr_elem", False, None, False)
946                     out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
947                     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")
948                     out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
949                     out_c.write("\tret->datalen = (*env)->GetArrayLength(env, elems);\n")
950                     out_c.write("\tif (ret->datalen == 0) {\n")
951                     out_c.write("\t\tret->data = NULL;\n")
952                     out_c.write("\t} else {\n")
953                     out_c.write("\t\tret->data = malloc(sizeof(" + vec_ty + ") * ret->datalen); // often freed by rust directly\n")
954                     assert len(ty_info.java_fn_ty_arg) == 1 # ie we're a primitive of some form
955                     out_c.write("\t\t" + ty_info.c_ty + " *java_elems = (*env)->GetPrimitiveArrayCritical(env, elems, NULL);\n")
956                     out_c.write("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
957                     if ty_info.arg_conv is not None:
958                         out_c.write("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
959                         out_c.write("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
960                         out_c.write("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
961                     else:
962                         out_c.write("\t\t\tret->data[i] = java_elems[i];\n")
963                     out_c.write("\t\t}\n")
964                     out_c.write("\t\t(*env)->ReleasePrimitiveArrayCritical(env, elems, java_elems, 0);\n")
965                     out_c.write("\t}\n")
966                     out_c.write("\treturn (long)ret;\n")
967                     out_c.write("}\n")
968                 elif is_union_enum:
969                     assert(struct_name.endswith("_Tag"))
970                     struct_name = struct_name[:-4]
971                     union_enum_items[struct_name] = {"field_lines": field_lines}
972                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
973                     enum_var_name = struct_name.split("_")
974                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
975                 elif struct_name in union_enum_items:
976                     map_complex_enum(struct_name, union_enum_items[struct_name])
977                 elif is_unitary_enum:
978                     map_unitary_enum(struct_name, field_lines)
979                 elif len(trait_fn_lines) > 0:
980                     trait_structs.add(struct_name)
981                     map_trait(struct_name, field_var_lines, trait_fn_lines)
982                 cur_block_obj = None
983         else:
984             fn_ptr = fn_ptr_regex.match(line)
985             fn_ret_arr = fn_ret_arr_regex.match(line)
986             reg_fn = reg_fn_regex.match(line)
987             const_val = const_val_regex.match(line)
988
989             if line.startswith("#include <"):
990                 pass
991             elif line.startswith("/*"):
992                 #out_java.write("\t" + line)
993                 if not line.endswith("*/\n"):
994                     in_block_comment = True
995             elif line.startswith("typedef enum "):
996                 cur_block_obj = line
997             elif line.startswith("typedef struct "):
998                 cur_block_obj = line
999             elif line.startswith("typedef union "):
1000                 cur_block_obj = line
1001             elif line.startswith("typedef "):
1002                 alias_match =  struct_alias_regex.match(line)
1003                 if alias_match.group(1) in result_templ_structs:
1004                     out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
1005                     out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
1006                     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")
1007                     out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
1008                     out_c.write("}\n")
1009                     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")
1010                     out_c.write("\tif (((" + alias_match.group(2) + "*)arg)->result_ok) {\n")
1011                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.result;\n")
1012                     out_c.write("\t} else {\n")
1013                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.err;\n")
1014                     out_c.write("\t}\n}\n")
1015                 pass
1016             elif fn_ptr is not None:
1017                 map_fn(line, fn_ptr, None, None)
1018             elif fn_ret_arr is not None:
1019                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1020             elif reg_fn is not None:
1021                 map_fn(line, reg_fn, None, None)
1022             elif const_val_regex is not None:
1023                 # TODO Map const variables
1024                 pass
1025             else:
1026                 assert(line == "\n")
1027
1028     out_java.write("}\n")