Reorg a bit and let us call trait methods from Java
[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     unitary_enums = set()
50
51     var_is_arr_regex = re.compile("\(\*([A-za-z_]*)\)\[([0-9]*)\]")
52     var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
53     def java_c_types(fn_arg, ret_arr_len):
54         fn_arg = fn_arg.strip()
55         if fn_arg.startswith("MUST_USE_RES "):
56             fn_arg = fn_arg[13:]
57         is_const = False
58         if fn_arg.startswith("const "):
59             fn_arg = fn_arg[6:]
60             is_const = True
61
62         is_ptr = False
63         take_by_ptr = False
64         rust_obj = None
65         if fn_arg.startswith("void"):
66             java_ty = "void"
67             c_ty = "void"
68             fn_ty_arg = "V"
69             fn_arg = fn_arg[4:].strip()
70         elif fn_arg.startswith("bool"):
71             java_ty = "boolean"
72             c_ty = "jboolean"
73             fn_ty_arg = "Z"
74             fn_arg = fn_arg[4:].strip()
75         elif fn_arg.startswith("uint8_t"):
76             java_ty = "byte"
77             c_ty = "jbyte"
78             fn_ty_arg = "B"
79             fn_arg = fn_arg[7:].strip()
80         elif fn_arg.startswith("uint16_t"):
81             java_ty = "short"
82             c_ty = "jshort"
83             fn_ty_arg = "S"
84             fn_arg = fn_arg[8:].strip()
85         elif fn_arg.startswith("uint32_t"):
86             java_ty = "int"
87             c_ty = "jint"
88             fn_ty_arg = "I"
89             fn_arg = fn_arg[8:].strip()
90         elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
91             java_ty = "long"
92             c_ty = "jlong"
93             fn_ty_arg = "J"
94             if fn_arg.startswith("uint64_t"):
95                 fn_arg = fn_arg[8:].strip()
96             else:
97                 fn_arg = fn_arg[9:].strip()
98         elif is_const and fn_arg.startswith("char *"):
99             java_ty = "String"
100             c_ty = "const char*"
101             fn_ty_arg = "Ljava/lang/String;"
102             fn_arg = fn_arg[6:].strip()
103         else:
104             ma = var_ty_regex.match(fn_arg)
105             if ma.group(1).strip() in unitary_enums:
106                 java_ty = ma.group(1).strip()
107                 c_ty = "jclass"
108                 fn_ty_arg = "Lorg/ldk/impl/bindings$" + ma.group(1).strip() + ";"
109                 fn_arg = ma.group(2).strip()
110                 rust_obj = ma.group(1).strip()
111                 take_by_ptr = True
112             else:
113                 java_ty = "long"
114                 c_ty = "jlong"
115                 fn_ty_arg = "J"
116                 fn_arg = ma.group(2).strip()
117                 rust_obj = ma.group(1).strip()
118                 take_by_ptr = True
119
120         if fn_arg.startswith(" *") or fn_arg.startswith("*"):
121             fn_arg = fn_arg.replace("*", "").strip()
122             is_ptr = True
123             c_ty = "jlong"
124             java_ty = "long"
125             fn_ty_arg = "J"
126
127         var_is_arr = var_is_arr_regex.match(fn_arg)
128         if var_is_arr is not None or ret_arr_len is not None:
129             assert(not take_by_ptr)
130             assert(not is_ptr)
131             java_ty = java_ty + "[]"
132             c_ty = c_ty + "Array"
133             if var_is_arr is not None:
134                 return TypeInfo(rust_obj=None, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
135                     passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2))
136         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,
137             is_ptr=is_ptr, var_name=fn_arg, arr_len=None)
138
139     def map_type(fn_arg, print_void, ret_arr_len, is_free):
140         ty_info = java_c_types(fn_arg, ret_arr_len)
141
142         if ty_info.c_ty == "void":
143             if not print_void:
144                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
145                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
146
147         if ty_info.c_ty.endswith("Array"):
148             arr_len = ty_info.arr_len
149             if arr_len is not None:
150                 arr_name = ty_info.var_name
151             else:
152                 arr_name = "ret"
153                 arr_len = ret_arr_len
154             assert(ty_info.c_ty == "jbyteArray")
155             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
156                 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n" +
157                     "(*_env)->GetByteArrayRegion (_env, """ + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" +
158                     "unsigned char (*""" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;",
159                 arg_conv_name = arr_name + "_ref",
160                 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
161                     "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", *",
162                     ");"),
163                 ret_conv_name = arr_name + "_arr")
164         elif ty_info.var_name != "":
165             # If we have a parameter name, print it (noting that it may indicate its a pointer)
166             if ty_info.rust_obj is not None:
167                 assert(ty_info.passed_as_ptr)
168                 if not ty_info.is_ptr:
169                     if ty_info.rust_obj in unitary_enums:
170                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
171                             arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
172                             arg_conv_name = ty_info.var_name + "_conv",
173                             ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
174                             ret_conv_name = ty_info.var_name + "_conv")
175                     base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
176                     if ty_info.rust_obj in trait_structs:
177                         if not is_free:
178                             base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
179                             base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
180                             base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
181                         else:
182                             base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
183                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
184                             arg_conv = base_conv,
185                             arg_conv_name = ty_info.var_name + "_conv",
186                             ret_conv = None, ret_conv_name = None)
187                     base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
188                     if ty_info.rust_obj in opaque_structs:
189                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
190                             arg_conv = base_conv + "\n" + ty_info.var_name + "_conv.is_owned = true;",
191                             arg_conv_name = ty_info.var_name + "_conv",
192                             ret_conv = None, ret_conv_name = None)
193
194                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
195                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
196                         ret_conv = None, ret_conv_name = None)
197                 else:
198                     assert(not is_free)
199                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
200                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
201                         arg_conv_name = ty_info.var_name + "_conv",
202                         ret_conv = None, ret_conv_name = None)
203             elif ty_info.is_ptr:
204                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
205                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
206             elif ty_info.java_ty == "String":
207                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
208                     arg_conv = None, arg_conv_name = None,
209                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
210             else:
211                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
212                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
213         elif not print_void:
214             # We don't have a parameter name, and want one, just call it arg
215             if ty_info.rust_obj is not None:
216                 assert(not is_free or ty_info.rust_obj not in opaque_structs);
217                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
218                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
219                     arg_conv_name = "arg_conv",
220                     ret_conv = None, ret_conv_name = None)
221             else:
222                 assert(not is_free)
223                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
224                     arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
225         else:
226             # We don't have a parameter name, and don't want one (cause we're returning)
227             if ty_info.rust_obj is not None:
228                 if not ty_info.is_ptr:
229                     if ty_info.rust_obj in unitary_enums:
230                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
231                             arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
232                             arg_conv_name = "ret",
233                             ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
234                     if ty_info.rust_obj in opaque_structs:
235                         # If we're returning a newly-allocated struct, we don't want Rust to ever
236                         # free, instead relying on the Java GC to lose the ref. We undo this in
237                         # any _free function.
238                         # To avoid any issues, we first assert that the incoming object is non-ref.
239                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
240                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";\nassert(ret->is_owned);\nret->is_owned = false;"),
241                             ret_conv_name = "(long)ret",
242                             arg_conv = None, arg_conv_name = None)
243                     else:
244                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
245                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
246                             ret_conv_name = "(long)ret",
247                             arg_conv = None, arg_conv_name = None)
248                 else:
249                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
250                         ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
251                         arg_conv = None, arg_conv_name = None)
252             else:
253                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
254                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
255
256     def map_fn(line, re_match, ret_arr_len, c_call_string):
257         out_java.write("\t// " + line)
258         out_java.write("\tpublic static native ")
259         out_c.write("JNIEXPORT ")
260
261         ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
262         ret_info.print_ty()
263         if ret_info.ret_conv is not None:
264             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
265
266         out_java.write(" " + re_match.group(2) + "(")
267         out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
268
269         arg_names = []
270         for idx, arg in enumerate(re_match.group(3).split(',')):
271             if idx != 0:
272                 out_java.write(", ")
273             if arg != "void":
274                 out_c.write(", ")
275             arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
276             if arg_conv_info.c_ty != "void":
277                 arg_conv_info.print_ty()
278                 arg_conv_info.print_name()
279             arg_names.append(arg_conv_info)
280
281         out_java.write(");\n")
282         out_c.write(") {\n")
283
284         for info in arg_names:
285             if info.arg_conv is not None:
286                 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
287
288         if ret_info.ret_conv is not None:
289             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
290         else:
291             out_c.write("\treturn ");
292
293         if c_call_string is None:
294             out_c.write(re_match.group(2) + "(")
295         else:
296             out_c.write(c_call_string)
297         for idx, info in enumerate(arg_names):
298             if info.arg_conv_name is not None:
299                 if idx != 0:
300                     out_c.write(", ")
301                 elif c_call_string is not None:
302                     continue
303                 out_c.write(info.arg_conv_name)
304         out_c.write(")")
305         if ret_info.ret_conv is not None:
306             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
307             out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
308         else:
309             out_c.write(";")
310         out_c.write("\n}\n\n")
311
312     def map_trait(struct_name, field_var_lines, trait_fn_lines):
313         out_c.write("typedef struct " + struct_name + "_JCalls {\n")
314         out_c.write("\tatomic_size_t refcnt;\n")
315         out_c.write("\tJNIEnv *env;\n")
316         out_c.write("\tjobject o;\n")
317         for var_line in field_var_lines:
318             if var_line.group(1) in trait_structs:
319                 out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
320         for fn_line in trait_fn_lines:
321             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
322                 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
323         out_c.write("} " + struct_name + "_JCalls;\n")
324
325         out_java.write("\tpublic interface " + struct_name + " {\n")
326         java_meths = []
327         for fn_line in trait_fn_lines:
328             java_meth_descr = "("
329             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
330                 ret_ty_info = java_c_types(fn_line.group(1), None)
331
332                 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
333                 is_const = fn_line.group(3) is not None
334                 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
335                 if is_const:
336                     out_c.write("const void* this_arg")
337                 else:
338                     out_c.write("void* this_arg")
339
340                 arg_names = []
341                 for idx, arg in enumerate(fn_line.group(4).split(',')):
342                     if arg == "":
343                         continue
344                     if idx >= 2:
345                         out_java.write(", ")
346                     out_c.write(", ")
347                     arg_conv_info = map_type(arg, True, None, False)
348                     out_c.write(arg.strip())
349                     out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
350                     arg_names.append(arg_conv_info)
351                     java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
352                 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
353                 java_meths.append(java_meth_descr)
354
355                 out_java.write(");\n")
356                 out_c.write(") {\n")
357                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
358
359                 for arg_info in arg_names:
360                     if arg_info.ret_conv is not None:
361                         out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "j_calls->env"));
362                         out_c.write(arg_info.arg_name)
363                         out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "j_calls->env") + "\n")
364
365                 if not ret_ty_info.passed_as_ptr:
366                     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")
367                 else:
368                     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");
369
370                 for arg_info in arg_names:
371                     if arg_info.ret_conv is not None:
372                         out_c.write(", " + arg_info.ret_conv_name)
373                     else:
374                         out_c.write(", " + arg_info.arg_name)
375                 out_c.write(");\n");
376
377                 if ret_ty_info.passed_as_ptr:
378                     out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
379                     out_c.write("\tFREE(ret);\n")
380                     out_c.write("\treturn res;\n")
381                 out_c.write("}\n")
382             elif fn_line.group(2) == "free":
383                 out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
384                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
385                 out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
386                 out_c.write("\t\t(*j_calls->env)->DeleteGlobalRef(j_calls->env, j_calls->o);\n")
387                 out_c.write("\t\tFREE(j_calls);\n")
388                 out_c.write("\t}\n}\n")
389
390         # Write out a clone function whether we need one or not, as we use them in moving to rust
391         out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
392         out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
393         out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
394         for var_line in field_var_lines:
395             if var_line.group(1) in trait_structs:
396                 out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
397         out_c.write("\treturn (void*) this_arg;\n")
398         out_c.write("}\n")
399
400         out_java.write("\t}\n")
401
402         out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
403         out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
404         for var_line in field_var_lines:
405             if var_line.group(1) in trait_structs:
406                 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
407                 out_c.write(", jobject " + var_line.group(2))
408         out_java.write(");\n")
409         out_c.write(") {\n")
410
411         out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
412         out_c.write("\tassert(c != NULL);\n")
413         out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
414         out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
415         out_c.write("\tcalls->env = env;\n")
416         out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
417         for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
418             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
419                 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
420                 out_c.write("\tassert(calls->" + fn_line.group(2) + "_meth != NULL);\n")
421         out_c.write("\n\t" + struct_name + " ret = {\n")
422         out_c.write("\t\t.this_arg = (void*) calls,\n")
423         for fn_line in trait_fn_lines:
424             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
425                 out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
426             elif fn_line.group(2) == "free":
427                 out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
428             else:
429                 out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
430         for var_line in field_var_lines:
431             if var_line.group(1) in trait_structs:
432                 out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
433         out_c.write("\t};\n")
434         for var_line in field_var_lines:
435             if var_line.group(1) in trait_structs:
436                 out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
437         out_c.write("\treturn ret;\n")
438         out_c.write("}\n")
439
440         out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
441         for var_line in field_var_lines:
442             if var_line.group(1) in trait_structs:
443                 out_c.write(", jobject " + var_line.group(2))
444         out_c.write(") {\n")
445         out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
446         out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
447         for var_line in field_var_lines:
448             if var_line.group(1) in trait_structs:
449                 out_c.write(", " + var_line.group(2))
450         out_c.write(");\n")
451         out_c.write("\treturn (long)res_ptr;\n")
452         out_c.write("}\n")
453
454         out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
455         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")
456         out_c.write("\treturn ((" + struct_name + "_JCalls*)val)->o;\n")
457         out_c.write("}\n")
458
459         for fn_line in trait_fn_lines:
460             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
461             is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
462             if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
463                 dummy_line = fn_line.group(1) + struct_name + "_call_" + fn_line.group(2) + " " + struct_name + "* arg" + fn_line.group(4) + "\n"
464                 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")
465
466     out_java.write("""package org.ldk.impl;
467
468 public class bindings {
469         static {
470                 System.loadLibrary(\"lightningjni\");
471                 init(java.lang.Enum.class);
472         }
473 """)
474     out_c.write("""#include \"org_ldk_impl_bindings.h\"
475 #include <rust_types.h>
476 #include <lightning.h>
477 #include <assert.h>
478 #include <string.h>
479 #include <stdatomic.h>
480 """)
481
482     if sys.argv[4] == "false":
483         out_c.write("#define MALLOC(a, _) malloc(a)\n")
484         out_c.write("#define FREE free\n")
485     else:
486         out_c.write("""
487 #include <threads.h>
488 static mtx_t allocation_mtx;
489
490 void __attribute__((constructor)) init_mtx() {
491         assert(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
492 }
493
494 typedef struct allocation {
495         struct allocation* next;
496         void* ptr;
497         const char* struct_name;
498 } allocation;
499 static allocation* allocation_ll = NULL;
500
501 void* MALLOC(size_t len, const char* struct_name) {
502         void* res = malloc(len);
503         allocation* new_alloc = malloc(sizeof(allocation));
504         new_alloc->ptr = res;
505         new_alloc->struct_name = struct_name;
506         assert(mtx_lock(&allocation_mtx) == thrd_success);
507         new_alloc->next = allocation_ll;
508         allocation_ll = new_alloc;
509         assert(mtx_unlock(&allocation_mtx) == thrd_success);
510         return res;
511 }
512
513 void FREE(void* ptr) {
514         allocation* p = NULL;
515         assert(mtx_lock(&allocation_mtx) == thrd_success);
516         allocation* it = allocation_ll;
517         while (it->ptr != ptr) { p = it; it = it->next; }
518         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
519         assert(mtx_unlock(&allocation_mtx) == thrd_success);
520         assert(it->ptr == ptr);
521         free(it);
522         free(ptr);
523 }
524
525 void __attribute__((destructor)) check_leaks() {
526         for (allocation* a = allocation_ll; a != NULL; a = a->next) { fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr); }
527         assert(allocation_ll == NULL);
528 }
529 """)
530
531     out_java.write("""
532         static native void init(java.lang.Class c);
533
534         public static native boolean deref_bool(long ptr);
535         public static native long deref_long(long ptr);
536         public static native void free_heap_ptr(long ptr);
537         public static native long u8_vec_to_heap_slice(long vec);
538         public static native long u8_vec_len(long vec);
539
540 """)
541     out_c.write("""
542 jmethodID ordinal_meth = NULL;
543 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class) {
544         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
545         assert(ordinal_meth != NULL);
546 }
547
548 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
549         return *((bool*)ptr);
550 }
551 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
552         return *((long*)ptr);
553 }
554 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
555         FREE((void*)ptr);
556 }
557 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_u8_1vec_1to_1heap_1slice (JNIEnv * env, jclass _a, jlong ptr) {
558         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
559         LDKu8slice *slice = (LDKu8slice*)MALLOC(sizeof(LDKu8slice), "u8slice");
560         slice->data = vec->data;
561         slice->datalen = vec->datalen;
562         return (long)slice;
563 }
564 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_u8_1vec_1len (JNIEnv * env, jclass _a, jlong ptr) {
565         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
566         return (long)vec->datalen;
567 }
568
569 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
570 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
571 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
572 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
573
574 """)
575
576     # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
577     out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
578     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
579     out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)MALLOC(sizeof(LDKSecretKey), \"LDKSecretKey\");\n") # TODO: rm me
580     out_c.write("\treturn (long)key;\n") # TODO: rm me
581     out_c.write("}\n") # TODO: rm me
582
583     in_block_comment = False
584     cur_block_obj = None
585
586     fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
587     fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
588     reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
589     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
590
591     line_indicates_result_regex = re.compile("^   bool result_ok;$")
592     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
593     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
594     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
595     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
596     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
597     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
598     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
599     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
600     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
601     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
602     struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
603     assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
604
605     result_templ_structs = set()
606     for line in in_h:
607         if in_block_comment:
608             #out_java.write("\t" + line)
609             if line.endswith("*/\n"):
610                 in_block_comment = False
611         elif cur_block_obj is not None:
612             cur_block_obj  = cur_block_obj + line
613             if line.startswith("} "):
614                 field_lines = []
615                 struct_name = None
616                 obj_lines = cur_block_obj.split("\n")
617                 is_opaque = False
618                 is_result = False
619                 is_unitary_enum = False
620                 is_union_enum = False
621                 is_union = False
622                 trait_fn_lines = []
623                 field_var_lines = []
624
625                 for idx, struct_line in enumerate(obj_lines):
626                     if struct_line.strip().startswith("/*"):
627                         in_block_comment = True
628                     if in_block_comment:
629                         if struct_line.endswith("*/"):
630                             in_block_comment = False
631                     else:
632                         struct_name_match = struct_name_regex.match(struct_line)
633                         if struct_name_match is not None:
634                             struct_name = struct_name_match.group(3)
635                             if struct_name_match.group(1) == "enum":
636                                 if not struct_name.endswith("_Tag"):
637                                     is_unitary_enum = True
638                                 else:
639                                     is_union_enum = True
640                             elif struct_name_match.group(1) == "union":
641                                 is_union = True
642                         if line_indicates_opaque_regex.match(struct_line):
643                             is_opaque = True
644                         elif line_indicates_result_regex.match(struct_line):
645                             is_result = True
646                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
647                         if trait_fn_match is not None:
648                             trait_fn_lines.append(trait_fn_match)
649                         field_var_match = line_field_var_regex.match(struct_line)
650                         if field_var_match is not None:
651                             field_var_lines.append(field_var_match)
652                         field_lines.append(struct_line)
653
654                 assert(struct_name is not None)
655                 assert(len(trait_fn_lines) == 0 or not (is_opaque or is_unitary_enum or is_union_enum or is_union))
656                 assert(not is_opaque or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_union))
657                 assert(not is_unitary_enum or not (len(trait_fn_lines) != 0 or is_opaque or is_union_enum or is_union))
658                 assert(not is_union_enum or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_opaque or is_union))
659                 assert(not is_union or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque))
660                 if is_opaque:
661                     opaque_structs.add(struct_name)
662                 elif is_result:
663                     result_templ_structs.add(struct_name)
664                 elif is_unitary_enum:
665                     unitary_enums.add(struct_name)
666                     out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
667                     out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
668                     ord_v = 0
669                     for idx, struct_line in enumerate(field_lines):
670                         if idx == 0:
671                             out_java.write("\tpublic enum " + struct_name + " {\n")
672                         elif idx == len(field_lines) - 3:
673                             assert(struct_line.endswith("_Sentinel,"))
674                         elif idx == len(field_lines) - 2:
675                             out_java.write("\t}\n")
676                         elif idx == len(field_lines) - 1:
677                             assert(struct_line == "")
678                         else:
679                             out_java.write("\t" + struct_line + "\n")
680                             out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
681                             ord_v = ord_v + 1
682                     out_c.write("\t}\n")
683                     out_c.write("\tassert(false);\n")
684                     out_c.write("}\n")
685
686                     ord_v = 0
687                     out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
688                     out_c.write("\t// TODO: This is pretty inefficient, we really need to cache the field IDs and class\n")
689                     out_c.write("\tjclass enum_class = (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + ";\");\n")
690                     out_c.write("\tassert(enum_class != NULL);\n")
691                     out_c.write("\tswitch (val) {\n")
692                     for idx, struct_line in enumerate(field_lines):
693                         if idx > 0 and idx < len(field_lines) - 3:
694                             variant = struct_line.strip().strip(",")
695                             out_c.write("\t\tcase " + variant + ": {\n")
696                             out_c.write("\t\t\tjfieldID field = (*env)->GetStaticFieldID(env, enum_class, \"" + variant + "\", \"Lorg/ldk/impl/bindings$" + struct_name + ";\");\n")
697                             out_c.write("\t\t\tassert(field != NULL);\n")
698                             out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, enum_class, field);\n")
699                             out_c.write("\t\t}\n")
700                             ord_v = ord_v + 1
701                     out_c.write("\t\tdefault: assert(false);\n")
702                     out_c.write("\t}\n")
703                     out_c.write("}\n\n")
704                 elif len(trait_fn_lines) > 0:
705                     trait_structs.add(struct_name)
706                     map_trait(struct_name, field_var_lines, trait_fn_lines)
707                 cur_block_obj = None
708         else:
709             fn_ptr = fn_ptr_regex.match(line)
710             fn_ret_arr = fn_ret_arr_regex.match(line)
711             reg_fn = reg_fn_regex.match(line)
712             const_val = const_val_regex.match(line)
713
714             if line.startswith("#include <"):
715                 pass
716             elif line.startswith("/*"):
717                 #out_java.write("\t" + line)
718                 if not line.endswith("*/\n"):
719                     in_block_comment = True
720             elif line.startswith("typedef enum "):
721                 cur_block_obj = line
722             elif line.startswith("typedef struct "):
723                 cur_block_obj = line
724             elif line.startswith("typedef union "):
725                 cur_block_obj = line
726             elif line.startswith("typedef "):
727                 alias_match =  struct_alias_regex.match(line)
728                 if alias_match.group(1) in result_templ_structs:
729                     out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
730                     out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
731                     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")
732                     out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
733                     out_c.write("}\n")
734                     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")
735                     out_c.write("\tif (((" + alias_match.group(2) + "*)arg)->result_ok) {\n")
736                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.result;\n")
737                     out_c.write("\t} else {\n")
738                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.err;\n")
739                     out_c.write("\t}\n}\n")
740                 pass
741             elif fn_ptr is not None:
742                 map_fn(line, fn_ptr, None, None)
743             elif fn_ret_arr is not None:
744                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
745             elif reg_fn is not None:
746                 map_fn(line, reg_fn, None, None)
747             elif const_val_regex is not None:
748                 # TODO Map const variables
749                 pass
750             else:
751                 assert(line == "\n")
752
753     out_java.write("}\n")