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