Move trait mapping to an fn
[ldk-java] / genbindings.py
1 #!/usr/bin/env python3
2 import sys, re
3
4 if len(sys.argv) != 5:
5     print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /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[3], "w") as out_c:
47     opaque_structs = set()
48     trait_structs = set()
49
50     var_is_arr_regex = re.compile("\(\*([A-za-z_]*)\)\[([0-9]*)\]")
51     var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
52     def java_c_types(fn_arg, ret_arr_len):
53         fn_arg = fn_arg.strip()
54         if fn_arg.startswith("MUST_USE_RES "):
55             fn_arg = fn_arg[13:]
56         is_const = False
57         if fn_arg.startswith("const "):
58             fn_arg = fn_arg[6:]
59             is_const = True
60
61         is_ptr = False
62         take_by_ptr = False
63         rust_obj = None
64         if fn_arg.startswith("void"):
65             java_ty = "void"
66             c_ty = "void"
67             fn_ty_arg = "V"
68             fn_arg = fn_arg[4:].strip()
69         elif fn_arg.startswith("bool"):
70             java_ty = "boolean"
71             c_ty = "jboolean"
72             fn_ty_arg = "Z"
73             fn_arg = fn_arg[4:].strip()
74         elif fn_arg.startswith("uint8_t"):
75             java_ty = "byte"
76             c_ty = "jbyte"
77             fn_ty_arg = "B"
78             fn_arg = fn_arg[7:].strip()
79         elif fn_arg.startswith("uint16_t"):
80             java_ty = "short"
81             c_ty = "jshort"
82             fn_ty_arg = "S"
83             fn_arg = fn_arg[8:].strip()
84         elif fn_arg.startswith("uint32_t"):
85             java_ty = "int"
86             c_ty = "jint"
87             fn_ty_arg = "I"
88             fn_arg = fn_arg[8:].strip()
89         elif fn_arg.startswith("uint64_t"):
90             java_ty = "long"
91             c_ty = "jlong"
92             fn_ty_arg = "J"
93             fn_arg = fn_arg[8:].strip()
94         elif is_const and fn_arg.startswith("char *"):
95             java_ty = "String"
96             c_ty = "const char*"
97             fn_ty_arg = "Ljava/lang/String;"
98             fn_arg = fn_arg[6:].strip()
99         else:
100             ma = var_ty_regex.match(fn_arg)
101             java_ty = "long"
102             c_ty = "jlong"
103             fn_ty_arg = "J"
104             fn_arg = ma.group(2).strip()
105             rust_obj = ma.group(1).strip()
106             take_by_ptr = True
107
108         if fn_arg.startswith(" *") or fn_arg.startswith("*"):
109             fn_arg = fn_arg.replace("*", "").strip()
110             is_ptr = True
111             c_ty = "jlong"
112             java_ty = "long"
113
114         var_is_arr = var_is_arr_regex.match(fn_arg)
115         if var_is_arr is not None or ret_arr_len is not None:
116             assert(not take_by_ptr)
117             assert(not is_ptr)
118             java_ty = java_ty + "[]"
119             c_ty = c_ty + "Array"
120             if var_is_arr is not None:
121                 return TypeInfo(rust_obj=None, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
122                     passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2))
123         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,
124             is_ptr=is_ptr, var_name=fn_arg, arr_len=None)
125
126     def map_type(fn_arg, print_void, ret_arr_len, is_free):
127         ty_info = java_c_types(fn_arg, ret_arr_len)
128
129         if ty_info.c_ty == "void":
130             if not print_void:
131                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
132                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
133
134         if ty_info.c_ty.endswith("Array"):
135             arr_len = ty_info.arr_len
136             if arr_len is not None:
137                 arr_name = ty_info.var_name
138             else:
139                 arr_name = "ret"
140                 arr_len = ret_arr_len
141             assert(ty_info.c_ty == "jbyteArray")
142             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
143                 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n" +
144                     "(*_env)->GetByteArrayRegion (_env, """ + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" +
145                     "unsigned char (*""" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;",
146                 arg_conv_name = arr_name + "_ref",
147                 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
148                     "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", *",
149                     ");"),
150                 ret_conv_name = arr_name + "_arr")
151         elif ty_info.var_name != "":
152             # If we have a parameter name, print it (noting that it may indicate its a pointer)
153             if ty_info.rust_obj is not None:
154                 assert(ty_info.passed_as_ptr)
155                 if not ty_info.is_ptr:
156                     base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
157                     if ty_info.rust_obj in trait_structs:
158                         if not is_free:
159                             base_conv = base_conv + "\n" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);"
160                         else:
161                             base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
162                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
163                             arg_conv = base_conv,
164                             arg_conv_name = ty_info.var_name + "_conv",
165                             ret_conv = None, ret_conv_name = None)
166                     base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
167                     if ty_info.rust_obj in opaque_structs:
168                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
169                             arg_conv = base_conv + "\n" + ty_info.var_name + "_conv._underlying_ref = false;",
170                             arg_conv_name = ty_info.var_name + "_conv",
171                             ret_conv = None, ret_conv_name = None)
172
173                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
174                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
175                         ret_conv = None, ret_conv_name = None)
176                 else:
177                     assert(not is_free)
178                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
179                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
180                         arg_conv_name = ty_info.var_name + "_conv",
181                         ret_conv = None, ret_conv_name = None)
182             elif ty_info.is_ptr:
183                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
184                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
185             elif ty_info.java_ty == "String":
186                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
187                     arg_conv = None, arg_conv_name = None,
188                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
189             else:
190                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
191                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
192         elif not print_void:
193             # We don't have a parameter name, and want one, just call it arg
194             if ty_info.rust_obj is not None:
195                 assert(not is_free or ty_info.rust_obj not in opaque_structs);
196                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
197                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
198                     arg_conv_name = "arg_conv",
199                     ret_conv = None, ret_conv_name = None)
200             else:
201                 assert(not is_free)
202                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
203                     arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
204         else:
205             # We don't have a parameter name, and don't want one (cause we're returning)
206             if ty_info.rust_obj is not None:
207                 if not ty_info.is_ptr:
208                     if ty_info.rust_obj in opaque_structs:
209                         # If we're returning a newly-allocated struct, we don't want Rust to ever
210                         # free, instead relying on the Java GC to lose the ref. We undo this in
211                         # any _free function.
212                         # To avoid any issues, we first assert that the incoming object is non-ref.
213                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
214                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";\nassert(!ret->_underlying_ref);\nret->_underlying_ref = true;"),
215                             ret_conv_name = "(long)ret",
216                             arg_conv = None, arg_conv_name = None)
217                     else:
218                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
219                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
220                             ret_conv_name = "(long)ret",
221                             arg_conv = None, arg_conv_name = None)
222                 else:
223                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
224                         ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
225                         arg_conv = None, arg_conv_name = None)
226             else:
227                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
228                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
229
230     def map_fn(re_match, ret_arr_len):
231         out_java.write("\t/// " + line)
232         out_java.write("\tpublic static native ")
233         out_c.write("JNIEXPORT ")
234
235         ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
236         ret_info.print_ty()
237         if ret_info.ret_conv is not None:
238             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
239
240         out_java.write(" " + re_match.group(2) + "(")
241         out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
242
243         arg_names = []
244         for idx, arg in enumerate(re_match.group(3).split(',')):
245             if idx != 0:
246                 out_java.write(", ")
247             if arg != "void":
248                 out_c.write(", ")
249             arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
250             if arg_conv_info.c_ty != "void":
251                 arg_conv_info.print_ty()
252                 arg_conv_info.print_name()
253             arg_names.append(arg_conv_info)
254
255         out_java.write(");\n")
256         out_c.write(") {\n")
257
258         for info in arg_names:
259             if info.arg_conv is not None:
260                 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
261
262         if ret_info.ret_conv is not None:
263             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
264         else:
265             out_c.write("\treturn ");
266
267         out_c.write(re_match.group(2) + "(")
268         for idx, info in enumerate(arg_names):
269             if info.arg_conv_name is not None:
270                 if idx != 0:
271                     out_c.write(", ")
272                 out_c.write(info.arg_conv_name)
273         out_c.write(")")
274         if ret_info.ret_conv is not None:
275             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
276             out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
277         else:
278             out_c.write(";")
279         out_c.write("\n}\n\n")
280
281     def map_trait(struct_name, field_var_lines, trait_fn_lines):
282         out_c.write("typedef struct " + struct_name + "_JCalls {\n")
283         out_c.write("\tatomic_size_t refcnt;\n")
284         out_c.write("\tJNIEnv *env;\n")
285         out_c.write("\tjobject o;\n")
286         for var_line in field_var_lines:
287             if var_line.group(1) in trait_structs:
288                 out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
289         for fn_line in trait_fn_lines:
290             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
291                 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
292         out_c.write("} " + struct_name + "_JCalls;\n")
293
294         out_java.write("\tpublic interface " + struct_name + " {\n")
295         java_meths = []
296         for fn_line in trait_fn_lines:
297             java_meth_descr = "("
298             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
299                 ret_ty_info = java_c_types(fn_line.group(1), None)
300
301                 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
302                 is_const = fn_line.group(3) is not None
303                 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
304                 if is_const:
305                     out_c.write("const void* this_arg")
306                 else:
307                     out_c.write("void* this_arg")
308
309                 arg_names = []
310                 for idx, arg in enumerate(fn_line.group(4).split(',')):
311                     if arg == "":
312                         continue
313                     if idx >= 2:
314                         out_java.write(", ")
315                     out_c.write(", ")
316                     arg_conv_info = map_type(arg, True, None, False)
317                     out_c.write(arg.strip())
318                     out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
319                     arg_names.append(arg_conv_info)
320                     java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
321                 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
322                 java_meths.append(java_meth_descr)
323
324                 out_java.write(");\n")
325                 out_c.write(") {\n")
326                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
327
328                 for arg_info in arg_names:
329                     if arg_info.ret_conv is not None:
330                         out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "j_calls->env"));
331                         out_c.write(arg_info.arg_name)
332                         out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "j_calls->env") + "\n")
333
334                 if not ret_ty_info.passed_as_ptr:
335                     out_c.write("\treturn (*j_calls->env)->Call" + ret_ty_info.java_ty.title() + "Method(j_calls->env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth")
336                 else:
337                     out_c.write("\t" + fn_line.group(1).strip() + "* ret = (" + fn_line.group(1).strip() + "*)(*j_calls->env)->CallLongMethod(j_calls->env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth");
338
339                 for arg_info in arg_names:
340                     if arg_info.ret_conv is not None:
341                         out_c.write(", " + arg_info.ret_conv_name)
342                     else:
343                         out_c.write(", " + arg_info.arg_name)
344                 out_c.write(");\n");
345
346                 if ret_ty_info.passed_as_ptr:
347                     out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
348                     out_c.write("\tFREE(ret);\n")
349                     out_c.write("\treturn res;\n")
350                 out_c.write("}\n")
351             elif fn_line.group(2) == "free":
352                 out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
353                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
354                 out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
355                 out_c.write("\t\t(*j_calls->env)->DeleteGlobalRef(j_calls->env, j_calls->o);\n")
356                 out_c.write("\t\tFREE(j_calls);\n")
357                 out_c.write("\t}\n}\n")
358
359         # Write out a clone function whether we need one or not, as we use them in moving to rust
360         out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
361         out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
362         out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
363         for var_line in field_var_lines:
364             if var_line.group(1) in trait_structs:
365                 out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
366         out_c.write("\treturn (void*) this_arg;\n")
367         out_c.write("}\n")
368
369         out_java.write("\t}\n")
370
371         out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
372         out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
373         for var_line in field_var_lines:
374             if var_line.group(1) in trait_structs:
375                 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
376                 out_c.write(", jobject " + var_line.group(2))
377         out_java.write(");\n")
378         out_c.write(") {\n")
379
380         out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
381         out_c.write("\tassert(c != NULL);\n")
382         out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
383         out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
384         out_c.write("\tcalls->env = env;\n")
385         out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
386         for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
387             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
388                 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
389                 out_c.write("\tassert(calls->" + fn_line.group(2) + "_meth != NULL);\n")
390         out_c.write("\n\t" + struct_name + " ret = {\n")
391         out_c.write("\t\t.this_arg = (void*) calls,\n")
392         for fn_line in trait_fn_lines:
393             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
394                 out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
395             elif fn_line.group(2) == "free":
396                 out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
397             else:
398                 out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
399         for var_line in field_var_lines:
400             if var_line.group(1) in trait_structs:
401                 out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
402         out_c.write("\t};\n")
403         for var_line in field_var_lines:
404             if var_line.group(1) in trait_structs:
405                 out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
406         out_c.write("\treturn ret;\n")
407         out_c.write("}\n")
408
409         out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
410         for var_line in field_var_lines:
411             if var_line.group(1) in trait_structs:
412                 out_c.write(", jobject " + var_line.group(2))
413         out_c.write(") {\n")
414         out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
415         out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
416         for var_line in field_var_lines:
417             if var_line.group(1) in trait_structs:
418                 out_c.write(", " + var_line.group(2))
419         out_c.write(");\n")
420         out_c.write("\treturn (long)res_ptr;\n")
421         out_c.write("}\n")
422
423
424
425     out_java.write("""package org.ldk.impl;
426
427 public class bindings {
428         static {
429                 System.loadLibrary(\"lightningjni\");
430         }
431
432 """)
433     out_c.write("#include \"org_ldk_impl_bindings.h\"\n")
434     out_c.write("#include <rust_types.h>\n")
435     out_c.write("#include <lightning.h>\n")
436     out_c.write("#include <assert.h>\n")
437     out_c.write("#include <string.h>\n")
438     out_c.write("#include <stdatomic.h>\n\n")
439     if sys.argv[4] == "false":
440         out_c.write("#define MALLOC(a, _) malloc(a)\n")
441         out_c.write("#define FREE free\n\n")
442     else:
443         out_c.write("#include <threads.h>\n")
444         out_c.write("static mtx_t allocation_mtx;\n\n")
445         out_c.write("void __attribute__((constructor)) init_mtx() {\n")
446         out_c.write("\tassert(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);\n")
447         out_c.write("}\n\n")
448         out_c.write("typedef struct allocation {\n")
449         out_c.write("\tstruct allocation* next;\n")
450         out_c.write("\tvoid* ptr;\n")
451         out_c.write("\tconst char* struct_name;\n")
452         out_c.write("} allocation;\n")
453         out_c.write("static allocation* allocation_ll = NULL;\n\n")
454         out_c.write("void* MALLOC(size_t len, const char* struct_name) {\n")
455         out_c.write("\tvoid* res = malloc(len);\n")
456         out_c.write("\tallocation* new_alloc = malloc(sizeof(allocation));\n")
457         out_c.write("\tnew_alloc->ptr = res;\n")
458         out_c.write("\tnew_alloc->struct_name = struct_name;\n")
459         out_c.write("\tassert(mtx_lock(&allocation_mtx) == thrd_success);\n")
460         out_c.write("\tnew_alloc->next = allocation_ll;\n")
461         out_c.write("\tallocation_ll = new_alloc;\n")
462         out_c.write("\tassert(mtx_unlock(&allocation_mtx) == thrd_success);\n")
463         out_c.write("\treturn res;\n")
464         out_c.write("}\n\n")
465         out_c.write("void FREE(void* ptr) {\n")
466         out_c.write("\tallocation* p = NULL;\n")
467         out_c.write("\tassert(mtx_lock(&allocation_mtx) == thrd_success);\n")
468         out_c.write("\tallocation* it = allocation_ll;\n")
469         out_c.write("\twhile (it->ptr != ptr) { p = it; it = it->next; }\n")
470         out_c.write("\tif (p) { p->next = it->next; } else { allocation_ll = it->next; }\n")
471         out_c.write("\tassert(mtx_unlock(&allocation_mtx) == thrd_success);\n")
472         out_c.write("\tassert(it->ptr == ptr);\n")
473         out_c.write("\tfree(it);\n")
474         out_c.write("\tfree(ptr);\n")
475         out_c.write("}\n\n")
476         out_c.write("void __attribute__((destructor)) check_leaks() {\n")
477         out_c.write("\tfor (allocation* a = allocation_ll; a != NULL; a = a->next) { fprintf(stderr, \"%s %p remains\\n\", a->struct_name, a->ptr); }\n")
478         out_c.write("\tassert(allocation_ll == NULL);\n")
479         out_c.write("}\n\n")
480
481     # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
482     out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
483     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
484     out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)MALLOC(sizeof(LDKSecretKey), \"LDKSecretKey\");\n") # TODO: rm me
485     out_c.write("\treturn (long)key;\n") # TODO: rm me
486     out_c.write("}\n") # TODO: rm me
487
488     in_block_comment = False
489     in_block_enum = False
490     cur_block_struct = None
491     in_block_union = False
492
493     fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
494     fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
495     reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
496     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
497
498     line_indicates_opaque_regex = re.compile("^   bool _underlying_ref;$")
499     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
500     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
501     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
502     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
503     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
504     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
505     struct_name_regex = re.compile("^typedef (struct|enum) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
506     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
507     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
508
509     for line in in_h:
510         if in_block_comment:
511             #out_java.write("\t" + line)
512             if line.endswith("*/\n"):
513                 in_block_comment = False
514         elif cur_block_struct is not None:
515             cur_block_struct  = cur_block_struct + line
516             if line.startswith("} "):
517                 field_lines = []
518                 struct_name = None
519                 struct_lines = cur_block_struct.split("\n")
520                 is_opaque = False
521                 trait_fn_lines = []
522                 field_var_lines = []
523
524                 for idx, struct_line in enumerate(struct_lines):
525                     if struct_line.strip().startswith("/*"):
526                         in_block_comment = True
527                     if in_block_comment:
528                         if struct_line.endswith("*/"):
529                             in_block_comment = False
530                     else:
531                         struct_name_match = struct_name_regex.match(struct_line)
532                         if struct_name_match is not None:
533                             struct_name = struct_name_match.group(2)
534                         if line_indicates_opaque_regex.match(struct_line):
535                             is_opaque = True
536                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
537                         if trait_fn_match is not None:
538                             trait_fn_lines.append(trait_fn_match)
539                         field_var_match = line_field_var_regex.match(struct_line)
540                         if field_var_match is not None:
541                             field_var_lines.append(field_var_match)
542                         field_lines.append(struct_line)
543
544                 assert(struct_name is not None)
545                 assert(len(trait_fn_lines) == 0 or not is_opaque)
546                 if is_opaque:
547                     opaque_structs.add(struct_name)
548                 if len(trait_fn_lines) > 0:
549                     trait_structs.add(struct_name)
550                     map_trait(struct_name, field_var_lines, trait_fn_lines)
551                     #out_java.write("/* " + "\n".join(field_lines) + "*/\n")
552                 cur_block_struct = None
553         elif in_block_union:
554             if line.startswith("} "):
555                 in_block_union = False
556         elif in_block_enum:
557             if line.startswith("} "):
558                 in_block_enum = False
559         else:
560             fn_ptr = fn_ptr_regex.match(line)
561             fn_ret_arr = fn_ret_arr_regex.match(line)
562             reg_fn = reg_fn_regex.match(line)
563             const_val = const_val_regex.match(line)
564
565             if line.startswith("#include <"):
566                 pass
567             elif line.startswith("/*"):
568                 #out_java.write("\t" + line)
569                 if not line.endswith("*/\n"):
570                     in_block_comment = True
571             elif line.startswith("typedef enum "):
572                 in_block_enum = True
573             elif line.startswith("typedef struct "):
574                 cur_block_struct = line
575             elif line.startswith("typedef union "):
576                 in_block_union = True
577             elif line.startswith("typedef "):
578                 pass
579             elif fn_ptr is not None:
580                 map_fn(fn_ptr, None)
581             elif fn_ret_arr is not None:
582                 map_fn(fn_ret_arr, fn_ret_arr.group(4))
583             elif reg_fn is not None:
584                 map_fn(reg_fn, None)
585             elif const_val_regex is not None:
586                 # TODO Map const variables
587                 pass
588             else:
589                 assert(line == "\n")
590
591     out_java.write("}\n")