Move enum mapping to functions
[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 - we often pass them Rust -> Rust
224                         base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
225                     if ty_info.rust_obj in opaque_structs:
226                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
227                             arg_conv = base_conv + "\n" + ty_info.var_name + "_conv.is_owned = true;",
228                             arg_conv_name = ty_info.var_name + "_conv",
229                             ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
230
231                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
232                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
233                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
234                 else:
235                     assert(not is_free)
236                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
237                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
238                         arg_conv_name = ty_info.var_name + "_conv",
239                         ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
240             elif ty_info.is_ptr:
241                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
242                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
243             elif ty_info.java_ty == "String":
244                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
245                     arg_conv = None, arg_conv_name = None,
246                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
247             else:
248                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
249                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
250         elif not print_void:
251             # We don't have a parameter name, and want one, just call it arg
252             if ty_info.rust_obj is not None:
253                 assert(not is_free or ty_info.rust_obj not in opaque_structs);
254                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
255                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
256                     arg_conv_name = "arg_conv",
257                     ret_conv = None, ret_conv_name = None)
258             else:
259                 assert(not is_free)
260                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
261                     arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
262         else:
263             # We don't have a parameter name, and don't want one (cause we're returning)
264             if ty_info.rust_obj is not None:
265                 if not ty_info.is_ptr:
266                     if ty_info.rust_obj in unitary_enums:
267                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
268                             arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
269                             arg_conv_name = "ret",
270                             ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
271                     if ty_info.rust_obj in opaque_structs:
272                         # If we're returning a newly-allocated struct, we don't want Rust to ever
273                         # free, instead relying on the Java GC to lose the ref. We undo this in
274                         # any _free function.
275                         # To avoid any issues, we first assert that the incoming object is non-ref.
276                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
277                             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;"),
278                             ret_conv_name = "(long)ret",
279                             arg_conv = None, arg_conv_name = None)
280                     else:
281                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
282                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
283                             ret_conv_name = "(long)ret",
284                             arg_conv = None, arg_conv_name = None)
285                 else:
286                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
287                         ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
288                         arg_conv = None, arg_conv_name = None)
289             else:
290                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
291                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
292
293     def map_fn(line, re_match, ret_arr_len, c_call_string):
294         out_java.write("\t// " + line)
295         out_java.write("\tpublic static native ")
296         out_c.write("JNIEXPORT ")
297
298         ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
299         ret_info.print_ty()
300         if ret_info.ret_conv is not None:
301             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
302
303         out_java.write(" " + re_match.group(2) + "(")
304         out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
305
306         arg_names = []
307         for idx, arg in enumerate(re_match.group(3).split(',')):
308             if idx != 0:
309                 out_java.write(", ")
310             if arg != "void":
311                 out_c.write(", ")
312             arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
313             if arg_conv_info.c_ty != "void":
314                 arg_conv_info.print_ty()
315                 arg_conv_info.print_name()
316             arg_names.append(arg_conv_info)
317
318         out_java.write(");\n")
319         out_c.write(") {\n")
320
321         for info in arg_names:
322             if info.arg_conv is not None:
323                 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
324
325         if ret_info.ret_conv is not None:
326             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
327         else:
328             out_c.write("\treturn ");
329
330         if c_call_string is None:
331             out_c.write(re_match.group(2) + "(")
332         else:
333             out_c.write(c_call_string)
334         for idx, info in enumerate(arg_names):
335             if info.arg_conv_name is not None:
336                 if idx != 0:
337                     out_c.write(", ")
338                 elif c_call_string is not None:
339                     continue
340                 out_c.write(info.arg_conv_name)
341         out_c.write(")")
342         if ret_info.ret_conv is not None:
343             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
344             out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
345         else:
346             out_c.write(";")
347         out_c.write("\n}\n\n")
348
349     def map_unitary_enum(struct_name, field_lines):
350         with open(sys.argv[3] + "/" + struct_name + ".java", "w") as out_java_enum:
351             out_java_enum.write("package org.ldk.enums;\n\n")
352             unitary_enums.add(struct_name)
353             out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
354             out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
355             ord_v = 0
356             for idx, struct_line in enumerate(field_lines):
357                 if idx == 0:
358                     out_java_enum.write("public enum " + struct_name + " {\n")
359                 elif idx == len(field_lines) - 3:
360                     assert(struct_line.endswith("_Sentinel,"))
361                 elif idx == len(field_lines) - 2:
362                     out_java_enum.write("\t; static native void init();\n")
363                     out_java_enum.write("\tstatic { init(); }\n")
364                     out_java_enum.write("}")
365                     out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
366                 elif idx == len(field_lines) - 1:
367                     assert(struct_line == "")
368                 else:
369                     out_java_enum.write(struct_line + "\n")
370                     out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
371                     ord_v = ord_v + 1
372             out_c.write("\t}\n")
373             out_c.write("\tabort();\n")
374             out_c.write("}\n")
375
376             ord_v = 0
377             out_c.write("static jclass " + struct_name + "_class = NULL;\n")
378             for idx, struct_line in enumerate(field_lines):
379                 if idx > 0 and idx < len(field_lines) - 3:
380                     variant = struct_line.strip().strip(",")
381                     out_c.write("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
382             out_c.write("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
383             out_c.write("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
384             out_c.write("\tDO_ASSERT(" + struct_name + "_class != NULL);\n")
385             for idx, struct_line in enumerate(field_lines):
386                 if idx > 0 and idx < len(field_lines) - 3:
387                     variant = struct_line.strip().strip(",")
388                     out_c.write("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
389                     out_c.write("\tDO_ASSERT(" + struct_name + "_" + variant + " != NULL);\n")
390             out_c.write("}\n")
391             out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
392             out_c.write("\tswitch (val) {\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("\t\tcase " + variant + ":\n")
397                     out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
398                     ord_v = ord_v + 1
399             out_c.write("\t\tdefault: abort();\n")
400             out_c.write("\t}\n")
401             out_c.write("}\n\n")
402
403     def map_complex_enum(struct_name, union_enum_items):
404         tag_field_lines = union_enum_items["field_lines"]
405         init_meth_jty_strs = {}
406         for idx, struct_line in enumerate(tag_field_lines):
407             if idx == 0:
408                 out_java.write("\tpublic static class " + struct_name + " {\n")
409                 out_java.write("\t\tprivate " + struct_name + "() {}\n")
410             elif idx == len(tag_field_lines) - 3:
411                 assert(struct_line.endswith("_Sentinel,"))
412             elif idx == len(tag_field_lines) - 2:
413                 out_java.write("\t\tstatic native void init();\n")
414                 out_java.write("\t}\n")
415             elif idx == len(tag_field_lines) - 1:
416                 assert(struct_line == "")
417             else:
418                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
419                 out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
420                 out_c.write("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
421                 out_c.write("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
422                 init_meth_jty_str = ""
423                 init_meth_params = ""
424                 init_meth_body = ""
425                 if "LDK" + var_name in union_enum_items:
426                     enum_var_lines = union_enum_items["LDK" + var_name]
427                     for idx, field in enumerate(enum_var_lines):
428                         if idx != 0 and idx < len(enum_var_lines) - 2:
429                             field_ty = java_c_types(field.strip(' ;'), None)
430                             out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.var_name + ";\n")
431                             init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
432                             if idx > 1:
433                                 init_meth_params = init_meth_params + ", "
434                             init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.var_name
435                             init_meth_body = init_meth_body + "this." + field_ty.var_name + " = " + field_ty.var_name + "; "
436                     out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
437                     out_java.write(init_meth_body)
438                     out_java.write("}\n")
439                 out_java.write("\t\t}\n")
440                 init_meth_jty_strs[var_name] = init_meth_jty_str
441         out_java.write("\tstatic { " + struct_name + ".init(); }\n")
442         out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
443
444         out_c.write("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
445         for idx, struct_line in enumerate(tag_field_lines):
446             if idx != 0 and idx < len(tag_field_lines) - 3:
447                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
448                 out_c.write("\t" + struct_name + "_" + var_name + "_class =\n")
449                 out_c.write("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
450                 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_class != NULL);\n")
451                 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")
452                 out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_meth != NULL);\n")
453         out_c.write("}\n")
454         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")
455         out_c.write("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
456         out_c.write("\tswitch(obj->tag) {\n")
457         for idx, struct_line in enumerate(tag_field_lines):
458             if idx != 0 and idx < len(tag_field_lines) - 3:
459                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
460                 out_c.write("\t\tcase " + struct_name + "_" + var_name + ": {\n")
461                 c_params_text = ""
462                 if "LDK" + var_name in union_enum_items:
463                     enum_var_lines = union_enum_items["LDK" + var_name]
464                     for idx, field in enumerate(enum_var_lines):
465                         if idx != 0 and idx < len(enum_var_lines) - 2:
466                             field_map = map_type(field.strip(' ;'), False, None, False)
467                             if field_map.ret_conv is not None:
468                                 out_c.write("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t").replace("_env", "env"))
469                                 out_c.write("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
470                                 out_c.write(field_map.ret_conv[1] + "\n")
471                                 c_params_text = c_params_text + ", " + field_map.ret_conv_name
472                             else:
473                                 c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
474                 out_c.write("\t\t\treturn (*env)->NewObject(env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
475                 out_c.write("\t\t}\n")
476         out_c.write("\t\tdefault: abort();\n")
477         out_c.write("\t}\n}\n")
478
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 vec_slice_len(long vec);
728         public static native long new_empty_slice_vec();
729
730 """)
731     out_c.write("""
732 static jmethodID ordinal_meth = NULL;
733 static jmethodID slicedef_meth = NULL;
734 static jclass slicedef_cls = NULL;
735 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
736         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
737         DO_ASSERT(ordinal_meth != NULL);
738         slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
739         DO_ASSERT(slicedef_meth != NULL);
740         slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
741         DO_ASSERT(slicedef_cls != NULL);
742 }
743
744 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
745         return *((bool*)ptr);
746 }
747 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
748         return *((long*)ptr);
749 }
750 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
751         FREE((void*)ptr);
752 }
753 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
754         jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
755         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
756         return ret_arr;
757 }
758 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
759         LDKu8slice *slice = (LDKu8slice*)slice_ptr;
760         jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
761         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
762         return ret_arr;
763 }
764 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
765         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
766         vec->datalen = (*_env)->GetArrayLength(_env, bytes);
767         vec->data = (uint8_t*)malloc(vec->datalen); // May be freed by rust, so don't track allocation
768         (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
769         return (long)vec;
770 }
771 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
772         // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
773         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
774         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
775         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
776         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
777         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
778         return (long)vec->datalen;
779 }
780 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
781         // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
782         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
783         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
784         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
785         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
786         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
787         vec->data = NULL;
788         vec->datalen = 0;
789         return (long)vec;
790 }
791
792 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
793 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
794 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
795 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
796
797 """)
798
799     # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
800     out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
801     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
802     out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)MALLOC(sizeof(LDKSecretKey), \"LDKSecretKey\");\n") # TODO: rm me
803     out_c.write("\treturn (long)key;\n") # TODO: rm me
804     out_c.write("}\n") # TODO: rm me
805
806     in_block_comment = False
807     cur_block_obj = None
808
809     fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
810     fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
811     reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
812     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
813
814     line_indicates_result_regex = re.compile("^   bool result_ok;$")
815     line_indicates_vec_regex = re.compile("^   ([A-Za-z_0-9]*) \*data;$")
816     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
817     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
818     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
819     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
820     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
821     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
822     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
823     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
824     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
825     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
826     struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
827     assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
828
829     result_templ_structs = set()
830     union_enum_items = {}
831     for line in in_h:
832         if in_block_comment:
833             #out_java.write("\t" + line)
834             if line.endswith("*/\n"):
835                 in_block_comment = False
836         elif cur_block_obj is not None:
837             cur_block_obj  = cur_block_obj + line
838             if line.startswith("} "):
839                 field_lines = []
840                 struct_name = None
841                 vec_ty = None
842                 obj_lines = cur_block_obj.split("\n")
843                 is_opaque = False
844                 is_result = False
845                 is_unitary_enum = False
846                 is_union_enum = False
847                 is_union = False
848                 trait_fn_lines = []
849                 field_var_lines = []
850
851                 for idx, struct_line in enumerate(obj_lines):
852                     if struct_line.strip().startswith("/*"):
853                         in_block_comment = True
854                     if in_block_comment:
855                         if struct_line.endswith("*/"):
856                             in_block_comment = False
857                     else:
858                         struct_name_match = struct_name_regex.match(struct_line)
859                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
860                         if struct_name_match is not None:
861                             struct_name = struct_name_match.group(3)
862                             if struct_name_match.group(1) == "enum":
863                                 if not struct_name.endswith("_Tag"):
864                                     is_unitary_enum = True
865                                 else:
866                                     is_union_enum = True
867                             elif struct_name_match.group(1) == "union":
868                                 is_union = True
869                         if line_indicates_opaque_regex.match(struct_line):
870                             is_opaque = True
871                         elif line_indicates_result_regex.match(struct_line):
872                             is_result = True
873                         elif vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
874                             vec_ty = vec_ty_match.group(1)
875                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
876                         if trait_fn_match is not None:
877                             trait_fn_lines.append(trait_fn_match)
878                         field_var_match = line_field_var_regex.match(struct_line)
879                         if field_var_match is not None:
880                             field_var_lines.append(field_var_match)
881                         field_lines.append(struct_line)
882
883                 assert(struct_name is not None)
884                 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))
885                 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))
886                 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))
887                 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))
888                 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))
889                 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))
890                 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))
891
892                 if is_opaque:
893                     opaque_structs.add(struct_name)
894                     out_java.write("\tpublic static native long " + struct_name + "_optional_none();\n")
895                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1optional_1none (JNIEnv * env, jclass _a) {\n")
896                     out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
897                     out_c.write("\tret->inner = NULL;\n")
898                     out_c.write("\treturn (long)ret;\n")
899                     out_c.write("}\n")
900                 elif is_result:
901                     result_templ_structs.add(struct_name)
902                 elif vec_ty is not None:
903                     out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
904                     out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
905                     out_c.write("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
906                     out_c.write("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
907                     out_c.write("}\n")
908                 elif is_union_enum:
909                     assert(struct_name.endswith("_Tag"))
910                     struct_name = struct_name[:-4]
911                     union_enum_items[struct_name] = {"field_lines": field_lines}
912                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
913                     enum_var_name = struct_name.split("_")
914                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
915                 elif struct_name in union_enum_items:
916                     map_complex_enum(struct_name, union_enum_items[struct_name])
917                 elif is_unitary_enum:
918                     map_unitary_enum(struct_name, field_lines)
919                 elif len(trait_fn_lines) > 0:
920                     trait_structs.add(struct_name)
921                     map_trait(struct_name, field_var_lines, trait_fn_lines)
922                 cur_block_obj = None
923         else:
924             fn_ptr = fn_ptr_regex.match(line)
925             fn_ret_arr = fn_ret_arr_regex.match(line)
926             reg_fn = reg_fn_regex.match(line)
927             const_val = const_val_regex.match(line)
928
929             if line.startswith("#include <"):
930                 pass
931             elif line.startswith("/*"):
932                 #out_java.write("\t" + line)
933                 if not line.endswith("*/\n"):
934                     in_block_comment = True
935             elif line.startswith("typedef enum "):
936                 cur_block_obj = line
937             elif line.startswith("typedef struct "):
938                 cur_block_obj = line
939             elif line.startswith("typedef union "):
940                 cur_block_obj = line
941             elif line.startswith("typedef "):
942                 alias_match =  struct_alias_regex.match(line)
943                 if alias_match.group(1) in result_templ_structs:
944                     out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
945                     out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
946                     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")
947                     out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
948                     out_c.write("}\n")
949                     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")
950                     out_c.write("\tif (((" + alias_match.group(2) + "*)arg)->result_ok) {\n")
951                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.result;\n")
952                     out_c.write("\t} else {\n")
953                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.err;\n")
954                     out_c.write("\t}\n}\n")
955                 pass
956             elif fn_ptr is not None:
957                 map_fn(line, fn_ptr, None, None)
958             elif fn_ret_arr is not None:
959                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
960             elif reg_fn is not None:
961                 map_fn(line, reg_fn, None, None)
962             elif const_val_regex is not None:
963                 # TODO Map const variables
964                 pass
965             else:
966                 assert(line == "\n")
967
968     out_java.write("}\n")