Convert LDKThirtyTwoBytes to byte[32] instead of taking a ptr
[ldk-java] / genbindings.py
1 #!/usr/bin/env python3
2 import sys, re
3
4 if len(sys.argv) != 6:
5     print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /path/to/bindings/enums/ /path/to/bindings/output.c debug")
6     print("debug should be true or false and indicates whether to track allocations and ensure we don't leak")
7     sys.exit(1)
8
9 class TypeInfo:
10     def __init__(self, rust_obj, java_ty, java_fn_ty_arg, c_ty, passed_as_ptr, is_ptr, var_name, arr_len):
11         self.rust_obj = rust_obj
12         self.java_ty = java_ty
13         self.java_fn_ty_arg = java_fn_ty_arg
14         self.c_ty = c_ty
15         self.passed_as_ptr = passed_as_ptr
16         self.is_ptr = is_ptr
17         self.var_name = var_name
18         self.arr_len = arr_len
19
20 class ConvInfo:
21     def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, ret_conv, ret_conv_name):
22         assert(ty_info.c_ty is not None)
23         assert(ty_info.java_ty is not None)
24         assert(arg_name is not None)
25         self.c_ty = ty_info.c_ty
26         self.java_ty = ty_info.java_ty
27         self.java_fn_ty_arg = ty_info.java_fn_ty_arg
28         self.arg_name = arg_name
29         self.arg_conv = arg_conv
30         self.arg_conv_name = arg_conv_name
31         self.ret_conv = ret_conv
32         self.ret_conv_name = ret_conv_name
33
34     def print_ty(self):
35         out_c.write(self.c_ty)
36         out_java.write(self.java_ty)
37
38     def print_name(self):
39         if self.arg_name != "":
40             out_java.write(" " + self.arg_name)
41             out_c.write(" " + self.arg_name)
42         else:
43             out_java.write(" arg")
44             out_c.write(" arg")
45
46 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[4], "w") as out_c:
47     opaque_structs = set()
48     trait_structs = set()
49     unitary_enums = set()
50
51     def camel_to_snake(s):
52         # Convert camel case to snake case, in a way that appears to match cbindgen
53         con = "_"
54         ret = ""
55         lastchar = ""
56         lastund = False
57         for char in s:
58             if lastchar.isupper():
59                 if not char.isupper() and not lastund:
60                     ret = ret + "_"
61                     lastund = True
62                 else:
63                     lastund = False
64                 ret = ret + lastchar.lower()
65             else:
66                 ret = ret + lastchar
67                 if char.isupper() and not lastund:
68                     ret = ret + "_"
69                     lastund = True
70                 else:
71                     lastund = False
72             lastchar = char
73             if char.isnumeric():
74                 lastund = True
75         return (ret + lastchar.lower()).strip("_")
76
77     var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([0-9]*)\]")
78     var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
79     def java_c_types(fn_arg, ret_arr_len):
80         fn_arg = fn_arg.strip()
81         if fn_arg.startswith("MUST_USE_RES "):
82             fn_arg = fn_arg[13:]
83         is_const = False
84         if fn_arg.startswith("const "):
85             fn_arg = fn_arg[6:]
86             is_const = True
87
88         is_ptr = False
89         take_by_ptr = False
90         rust_obj = None
91         if fn_arg.startswith("LDKThirtyTwoBytes"):
92             fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
93             assert var_is_arr_regex.match(fn_arg[8:])
94             rust_obj = "LDKThirtyTwoBytes"
95
96         if fn_arg.startswith("void"):
97             java_ty = "void"
98             c_ty = "void"
99             fn_ty_arg = "V"
100             fn_arg = fn_arg[4:].strip()
101         elif fn_arg.startswith("bool"):
102             java_ty = "boolean"
103             c_ty = "jboolean"
104             fn_ty_arg = "Z"
105             fn_arg = fn_arg[4:].strip()
106         elif fn_arg.startswith("uint8_t"):
107             java_ty = "byte"
108             c_ty = "jbyte"
109             fn_ty_arg = "B"
110             fn_arg = fn_arg[7:].strip()
111         elif fn_arg.startswith("uint16_t"):
112             java_ty = "short"
113             c_ty = "jshort"
114             fn_ty_arg = "S"
115             fn_arg = fn_arg[8:].strip()
116         elif fn_arg.startswith("uint32_t"):
117             java_ty = "int"
118             c_ty = "jint"
119             fn_ty_arg = "I"
120             fn_arg = fn_arg[8:].strip()
121         elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
122             java_ty = "long"
123             c_ty = "jlong"
124             fn_ty_arg = "J"
125             if fn_arg.startswith("uint64_t"):
126                 fn_arg = fn_arg[8:].strip()
127             else:
128                 fn_arg = fn_arg[9:].strip()
129         elif is_const and fn_arg.startswith("char *"):
130             java_ty = "String"
131             c_ty = "const char*"
132             fn_ty_arg = "Ljava/lang/String;"
133             fn_arg = fn_arg[6:].strip()
134         else:
135             ma = var_ty_regex.match(fn_arg)
136             if ma.group(1).strip() in unitary_enums:
137                 java_ty = ma.group(1).strip()
138                 c_ty = "jclass"
139                 fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
140                 fn_arg = ma.group(2).strip()
141                 rust_obj = ma.group(1).strip()
142                 take_by_ptr = True
143             else:
144                 java_ty = "long"
145                 c_ty = "jlong"
146                 fn_ty_arg = "J"
147                 fn_arg = ma.group(2).strip()
148                 rust_obj = ma.group(1).strip()
149                 take_by_ptr = True
150
151         if fn_arg.startswith(" *") or fn_arg.startswith("*"):
152             fn_arg = fn_arg.replace("*", "").strip()
153             is_ptr = True
154             c_ty = "jlong"
155             java_ty = "long"
156             fn_ty_arg = "J"
157
158         var_is_arr = var_is_arr_regex.match(fn_arg)
159         if var_is_arr is not None or ret_arr_len is not None:
160             assert(not take_by_ptr)
161             assert(not is_ptr)
162             java_ty = java_ty + "[]"
163             c_ty = c_ty + "Array"
164             if var_is_arr is not None:
165                 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
166                     passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2))
167         return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg=fn_ty_arg, c_ty=c_ty, passed_as_ptr=is_ptr or take_by_ptr,
168             is_ptr=is_ptr, var_name=fn_arg, arr_len=None)
169
170     def map_type(fn_arg, print_void, ret_arr_len, is_free):
171         ty_info = java_c_types(fn_arg, ret_arr_len)
172
173         if ty_info.c_ty == "void":
174             if not print_void:
175                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
176                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
177
178         if ty_info.c_ty.endswith("Array"):
179             arr_len = ty_info.arr_len
180             if arr_len is not None:
181                 arr_name = ty_info.var_name
182             else:
183                 arr_name = "ret"
184                 arr_len = ret_arr_len
185             assert(ty_info.c_ty == "jbyteArray")
186             if ty_info.rust_obj is not None:
187                 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n" + "(*_env)->GetByteArrayRegion (_env, """ + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref.data);"
188                 arr_access = ("", ".data")
189             else:
190                 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n" + "(*_env)->GetByteArrayRegion (_env, """ + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" + "unsigned char (*""" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
191                 arr_access = ("*", "")
192             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
193                 arg_conv = arg_conv,
194                 arg_conv_name = arr_name + "_ref",
195                 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
196                     "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", " + arr_access[0],
197                     arr_access[1] + ");"),
198                 ret_conv_name = arr_name + "_arr")
199         elif ty_info.var_name != "":
200             # If we have a parameter name, print it (noting that it may indicate its a pointer)
201             if ty_info.rust_obj is not None:
202                 assert(ty_info.passed_as_ptr)
203                 if not ty_info.is_ptr:
204                     if ty_info.rust_obj in unitary_enums:
205                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
206                             arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
207                             arg_conv_name = ty_info.var_name + "_conv",
208                             ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
209                             ret_conv_name = ty_info.var_name + "_conv")
210                     base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
211                     if ty_info.rust_obj in trait_structs:
212                         if not is_free:
213                             base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
214                             base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
215                             base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
216                         else:
217                             base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
218                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
219                             arg_conv = base_conv,
220                             arg_conv_name = ty_info.var_name + "_conv",
221                             ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE")
222                     if ty_info.rust_obj != "LDKu8slice":
223                         # Don't bother free'ing slices passed in - we often pass them Rust -> Rust
224                         base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
225                     if ty_info.rust_obj in opaque_structs:
226                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
227                             arg_conv = base_conv + "\n" + ty_info.var_name + "_conv.is_owned = true;",
228                             arg_conv_name = ty_info.var_name + "_conv",
229                             ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
230
231                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
232                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
233                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
234                 else:
235                     assert(not is_free)
236                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
237                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
238                         arg_conv_name = ty_info.var_name + "_conv",
239                         ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
240             elif ty_info.is_ptr:
241                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
242                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
243             elif ty_info.java_ty == "String":
244                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
245                     arg_conv = None, arg_conv_name = None,
246                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
247             else:
248                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
249                     arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
250         elif not print_void:
251             # We don't have a parameter name, and want one, just call it arg
252             if ty_info.rust_obj is not None:
253                 assert(not is_free or ty_info.rust_obj not in opaque_structs);
254                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
255                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
256                     arg_conv_name = "arg_conv",
257                     ret_conv = None, ret_conv_name = None)
258             else:
259                 assert(not is_free)
260                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
261                     arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
262         else:
263             # We don't have a parameter name, and don't want one (cause we're returning)
264             if ty_info.rust_obj is not None:
265                 if not ty_info.is_ptr:
266                     if ty_info.rust_obj in unitary_enums:
267                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
268                             arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
269                             arg_conv_name = "ret",
270                             ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
271                     if ty_info.rust_obj in opaque_structs:
272                         # If we're returning a newly-allocated struct, we don't want Rust to ever
273                         # free, instead relying on the Java GC to lose the ref. We undo this in
274                         # any _free function.
275                         # To avoid any issues, we first assert that the incoming object is non-ref.
276                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
277                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";\nDO_ASSERT(ret->is_owned);\nret->is_owned = false;"),
278                             ret_conv_name = "(long)ret",
279                             arg_conv = None, arg_conv_name = None)
280                     else:
281                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
282                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
283                             ret_conv_name = "(long)ret",
284                             arg_conv = None, arg_conv_name = None)
285                 else:
286                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
287                         ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
288                         arg_conv = None, arg_conv_name = None)
289             else:
290                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
291                     arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
292
293     def map_fn(line, re_match, ret_arr_len, c_call_string):
294         out_java.write("\t// " + line)
295         out_java.write("\tpublic static native ")
296         out_c.write("JNIEXPORT ")
297
298         ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
299         ret_info.print_ty()
300         if ret_info.ret_conv is not None:
301             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
302
303         out_java.write(" " + re_match.group(2) + "(")
304         out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
305
306         arg_names = []
307         for idx, arg in enumerate(re_match.group(3).split(',')):
308             if idx != 0:
309                 out_java.write(", ")
310             if arg != "void":
311                 out_c.write(", ")
312             arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
313             if arg_conv_info.c_ty != "void":
314                 arg_conv_info.print_ty()
315                 arg_conv_info.print_name()
316             arg_names.append(arg_conv_info)
317
318         out_java.write(");\n")
319         out_c.write(") {\n")
320
321         for info in arg_names:
322             if info.arg_conv is not None:
323                 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
324
325         if ret_info.ret_conv is not None:
326             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
327         else:
328             out_c.write("\treturn ");
329
330         if c_call_string is None:
331             out_c.write(re_match.group(2) + "(")
332         else:
333             out_c.write(c_call_string)
334         for idx, info in enumerate(arg_names):
335             if info.arg_conv_name is not None:
336                 if idx != 0:
337                     out_c.write(", ")
338                 elif c_call_string is not None:
339                     continue
340                 out_c.write(info.arg_conv_name)
341         out_c.write(")")
342         if ret_info.ret_conv is not None:
343             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
344             out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
345         else:
346             out_c.write(";")
347         out_c.write("\n}\n\n")
348
349     def map_trait(struct_name, field_var_lines, trait_fn_lines):
350         out_c.write("typedef struct " + struct_name + "_JCalls {\n")
351         out_c.write("\tatomic_size_t refcnt;\n")
352         out_c.write("\tJavaVM *vm;\n")
353         out_c.write("\tjobject o;\n")
354         for var_line in field_var_lines:
355             if var_line.group(1) in trait_structs:
356                 out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
357         for fn_line in trait_fn_lines:
358             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
359                 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
360         out_c.write("} " + struct_name + "_JCalls;\n")
361
362         out_java.write("\tpublic interface " + struct_name + " {\n")
363         java_meths = []
364         for fn_line in trait_fn_lines:
365             java_meth_descr = "("
366             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
367                 ret_ty_info = java_c_types(fn_line.group(1), None)
368
369                 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
370                 is_const = fn_line.group(3) is not None
371                 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
372                 if is_const:
373                     out_c.write("const void* this_arg")
374                 else:
375                     out_c.write("void* this_arg")
376
377                 arg_names = []
378                 for idx, arg in enumerate(fn_line.group(4).split(',')):
379                     if arg == "":
380                         continue
381                     if idx >= 2:
382                         out_java.write(", ")
383                     out_c.write(", ")
384                     arg_conv_info = map_type(arg, True, None, False)
385                     out_c.write(arg.strip())
386                     out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
387                     arg_names.append(arg_conv_info)
388                     java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
389                 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
390                 java_meths.append(java_meth_descr)
391
392                 out_java.write(");\n")
393                 out_c.write(") {\n")
394                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
395                 out_c.write("\tJNIEnv *env;\n")
396                 out_c.write("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
397
398                 for arg_info in arg_names:
399                     if arg_info.ret_conv is not None:
400                         out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "env"));
401                         out_c.write(arg_info.arg_name)
402                         out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "env") + "\n")
403
404                 if ret_ty_info.c_ty.endswith("Array"):
405                     assert(ret_ty_info.c_ty == "jbyteArray")
406                     out_c.write("\tjbyteArray jret = (*env)->CallObjectMethod(env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth")
407                 elif not ret_ty_info.passed_as_ptr:
408                     out_c.write("\treturn (*env)->Call" + ret_ty_info.java_ty.title() + "Method(env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth")
409                 else:
410                     out_c.write("\t" + fn_line.group(1).strip() + "* ret = (" + fn_line.group(1).strip() + "*)(*env)->CallLongMethod(env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth");
411
412                 for arg_info in arg_names:
413                     if arg_info.ret_conv is not None:
414                         out_c.write(", " + arg_info.ret_conv_name)
415                     else:
416                         out_c.write(", " + arg_info.arg_name)
417                 out_c.write(");\n");
418                 if ret_ty_info.c_ty.endswith("Array"):
419                     out_c.write("\tLDKThirtyTwoBytes ret;\n")
420                     out_c.write("\t(*env)->GetByteArrayRegion(env, jret, 0, " + ret_ty_info.arr_len + ", ret.data);\n")
421                     out_c.write("\treturn ret;\n")
422
423                 if ret_ty_info.passed_as_ptr:
424                     out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
425                     out_c.write("\tFREE(ret);\n")
426                     out_c.write("\treturn res;\n")
427                 out_c.write("}\n")
428             elif fn_line.group(2) == "free":
429                 out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
430                 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
431                 out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
432                 out_c.write("\t\tJNIEnv *env;\n")
433                 out_c.write("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
434                 out_c.write("\t\t(*env)->DeleteGlobalRef(env, j_calls->o);\n")
435                 out_c.write("\t\tFREE(j_calls);\n")
436                 out_c.write("\t}\n}\n")
437
438         # Write out a clone function whether we need one or not, as we use them in moving to rust
439         out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
440         out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
441         out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
442         for var_line in field_var_lines:
443             if var_line.group(1) in trait_structs:
444                 out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
445         out_c.write("\treturn (void*) this_arg;\n")
446         out_c.write("}\n")
447
448         out_java.write("\t}\n")
449
450         out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
451         out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
452         for var_line in field_var_lines:
453             if var_line.group(1) in trait_structs:
454                 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
455                 out_c.write(", jobject " + var_line.group(2))
456         out_java.write(");\n")
457         out_c.write(") {\n")
458
459         out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
460         out_c.write("\tDO_ASSERT(c != NULL);\n")
461         out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
462         out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
463         out_c.write("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
464         out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
465         for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
466             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
467                 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
468                 out_c.write("\tDO_ASSERT(calls->" + fn_line.group(2) + "_meth != NULL);\n")
469         out_c.write("\n\t" + struct_name + " ret = {\n")
470         out_c.write("\t\t.this_arg = (void*) calls,\n")
471         for fn_line in trait_fn_lines:
472             if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
473                 out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
474             elif fn_line.group(2) == "free":
475                 out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
476             else:
477                 out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
478         for var_line in field_var_lines:
479             if var_line.group(1) in trait_structs:
480                 out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
481         out_c.write("\t};\n")
482         for var_line in field_var_lines:
483             if var_line.group(1) in trait_structs:
484                 out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
485         out_c.write("\treturn ret;\n")
486         out_c.write("}\n")
487
488         out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
489         for var_line in field_var_lines:
490             if var_line.group(1) in trait_structs:
491                 out_c.write(", jobject " + var_line.group(2))
492         out_c.write(") {\n")
493         out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
494         out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
495         for var_line in field_var_lines:
496             if var_line.group(1) in trait_structs:
497                 out_c.write(", " + var_line.group(2))
498         out_c.write(");\n")
499         out_c.write("\treturn (long)res_ptr;\n")
500         out_c.write("}\n")
501
502         out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
503         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")
504         out_c.write("\treturn ((" + struct_name + "_JCalls*)val)->o;\n")
505         out_c.write("}\n")
506
507         for fn_line in trait_fn_lines:
508             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
509             is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
510             if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
511                 dummy_line = fn_line.group(1) + struct_name + "_call_" + fn_line.group(2) + " " + struct_name + "* arg" + fn_line.group(4) + "\n"
512                 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")
513
514     out_c.write("""#include \"org_ldk_impl_bindings.h\"
515 #include <rust_types.h>
516 #include <lightning.h>
517 #include <string.h>
518 #include <stdatomic.h>
519 """)
520
521     if sys.argv[4] == "false":
522         out_c.write("#define MALLOC(a, _) malloc(a)\n")
523         out_c.write("#define FREE free\n")
524         out_c.write("#define DO_ASSERT(a) (void)(a)\n")
525     else:
526         out_c.write("""#include <assert.h>
527 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
528
529 #include <threads.h>
530 static mtx_t allocation_mtx;
531
532 void __attribute__((constructor)) init_mtx() {
533         DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
534 }
535
536 typedef struct allocation {
537         struct allocation* next;
538         void* ptr;
539         const char* struct_name;
540 } allocation;
541 static allocation* allocation_ll = NULL;
542
543 static void* MALLOC(size_t len, const char* struct_name) {
544         void* res = malloc(len);
545         allocation* new_alloc = malloc(sizeof(allocation));
546         new_alloc->ptr = res;
547         new_alloc->struct_name = struct_name;
548         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
549         new_alloc->next = allocation_ll;
550         allocation_ll = new_alloc;
551         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
552         return res;
553 }
554
555 static void FREE(void* ptr) {
556         allocation* p = NULL;
557         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
558         allocation* it = allocation_ll;
559         while (it->ptr != ptr) { p = it; it = it->next; }
560         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
561         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
562         DO_ASSERT(it->ptr == ptr);
563         free(it);
564         free(ptr);
565 }
566
567 void __attribute__((destructor)) check_leaks() {
568         for (allocation* a = allocation_ll; a != NULL; a = a->next) { fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr); }
569         DO_ASSERT(allocation_ll == NULL);
570 }
571 """)
572     out_java.write("""package org.ldk.impl;
573 import org.ldk.enums.*;
574
575 public class bindings {
576         public static class VecOrSliceDef {
577                 public long dataptr;
578                 public long datalen;
579                 public long stride;
580                 public VecOrSliceDef(long dataptr, long datalen, long stride) {
581                         this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
582                 }
583         }
584         static {
585                 System.loadLibrary(\"lightningjni\");
586                 init(java.lang.Enum.class, VecOrSliceDef.class);
587         }
588         static native void init(java.lang.Class c, java.lang.Class slicedef);
589
590         public static native boolean deref_bool(long ptr);
591         public static native long deref_long(long ptr);
592         public static native void free_heap_ptr(long ptr);
593         public static native byte[] read_bytes(long ptr, long len);
594         public static native byte[] get_u8_slice_bytes(long slice_ptr);
595         public static native long bytes_to_u8_vec(byte[] bytes);
596         public static native long vec_slice_len(long vec);
597         public static native long new_empty_slice_vec();
598
599 """)
600     out_c.write("""
601 static jmethodID ordinal_meth = NULL;
602 static jmethodID slicedef_meth = NULL;
603 static jclass slicedef_cls = NULL;
604 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
605         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
606         DO_ASSERT(ordinal_meth != NULL);
607         slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
608         DO_ASSERT(slicedef_meth != NULL);
609         slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
610         DO_ASSERT(slicedef_cls != NULL);
611 }
612
613 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
614         return *((bool*)ptr);
615 }
616 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
617         return *((long*)ptr);
618 }
619 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
620         FREE((void*)ptr);
621 }
622 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
623         jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
624         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
625         return ret_arr;
626 }
627 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
628         LDKu8slice *slice = (LDKu8slice*)slice_ptr;
629         jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
630         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
631         return ret_arr;
632 }
633 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
634         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
635         vec->datalen = (*_env)->GetArrayLength(_env, bytes);
636         vec->data = (uint8_t*)malloc(vec->datalen); // May be freed by rust, so don't track allocation
637         (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
638         return (long)vec;
639 }
640 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
641         // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
642         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
643         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
644         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
645         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
646         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
647         return (long)vec->datalen;
648 }
649 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
650         // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
651         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
652         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
653         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
654         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
655         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
656         vec->data = NULL;
657         vec->datalen = 0;
658         return (long)vec;
659 }
660
661 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
662 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
663 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
664 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
665
666 """)
667
668     # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
669     out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
670     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
671     out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)MALLOC(sizeof(LDKSecretKey), \"LDKSecretKey\");\n") # TODO: rm me
672     out_c.write("\treturn (long)key;\n") # TODO: rm me
673     out_c.write("}\n") # TODO: rm me
674
675     in_block_comment = False
676     cur_block_obj = None
677
678     fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
679     fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
680     reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
681     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
682
683     line_indicates_result_regex = re.compile("^   bool result_ok;$")
684     line_indicates_vec_regex = re.compile("^   ([A-Za-z_0-9]*) \*data;$")
685     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
686     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
687     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
688     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
689     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
690     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
691     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
692     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
693     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
694     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
695     struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
696     assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
697
698     result_templ_structs = set()
699     union_enum_items = {}
700     for line in in_h:
701         if in_block_comment:
702             #out_java.write("\t" + line)
703             if line.endswith("*/\n"):
704                 in_block_comment = False
705         elif cur_block_obj is not None:
706             cur_block_obj  = cur_block_obj + line
707             if line.startswith("} "):
708                 field_lines = []
709                 struct_name = None
710                 vec_ty = None
711                 obj_lines = cur_block_obj.split("\n")
712                 is_opaque = False
713                 is_result = False
714                 is_unitary_enum = False
715                 is_union_enum = False
716                 is_union = False
717                 trait_fn_lines = []
718                 field_var_lines = []
719
720                 for idx, struct_line in enumerate(obj_lines):
721                     if struct_line.strip().startswith("/*"):
722                         in_block_comment = True
723                     if in_block_comment:
724                         if struct_line.endswith("*/"):
725                             in_block_comment = False
726                     else:
727                         struct_name_match = struct_name_regex.match(struct_line)
728                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
729                         if struct_name_match is not None:
730                             struct_name = struct_name_match.group(3)
731                             if struct_name_match.group(1) == "enum":
732                                 if not struct_name.endswith("_Tag"):
733                                     is_unitary_enum = True
734                                 else:
735                                     is_union_enum = True
736                             elif struct_name_match.group(1) == "union":
737                                 is_union = True
738                         if line_indicates_opaque_regex.match(struct_line):
739                             is_opaque = True
740                         elif line_indicates_result_regex.match(struct_line):
741                             is_result = True
742                         elif vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
743                             vec_ty = vec_ty_match.group(1)
744                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
745                         if trait_fn_match is not None:
746                             trait_fn_lines.append(trait_fn_match)
747                         field_var_match = line_field_var_regex.match(struct_line)
748                         if field_var_match is not None:
749                             field_var_lines.append(field_var_match)
750                         field_lines.append(struct_line)
751
752                 assert(struct_name is not None)
753                 assert(len(trait_fn_lines) == 0 or not (is_opaque or is_unitary_enum or is_union_enum or is_union or is_result or vec_ty is not None))
754                 assert(not is_opaque or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_union or is_result or vec_ty is not None))
755                 assert(not is_unitary_enum or not (len(trait_fn_lines) != 0 or is_opaque or is_union_enum or is_union or is_result or vec_ty is not None))
756                 assert(not is_union_enum or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_opaque or is_union or is_result or vec_ty is not None))
757                 assert(not is_union or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_result or vec_ty is not None))
758                 assert(not is_result or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or vec_ty is not None))
759                 assert(vec_ty is None or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or is_result))
760
761                 if is_opaque:
762                     opaque_structs.add(struct_name)
763                     out_java.write("\tpublic static native long " + struct_name + "_optional_none();\n")
764                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1optional_1none (JNIEnv * env, jclass _a) {\n")
765                     out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
766                     out_c.write("\tret->inner = NULL;\n")
767                     out_c.write("\treturn (long)ret;\n")
768                     out_c.write("}\n")
769                 elif is_result:
770                     result_templ_structs.add(struct_name)
771                 elif vec_ty is not None:
772                     out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
773                     out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
774                     out_c.write("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
775                     out_c.write("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
776                     out_c.write("}\n")
777                 elif is_union_enum:
778                     assert(struct_name.endswith("_Tag"))
779                     struct_name = struct_name[:-4]
780                     union_enum_items[struct_name] = {"field_lines": field_lines}
781                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
782                     enum_var_name = struct_name.split("_")
783                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
784                 elif struct_name in union_enum_items:
785                     tag_field_lines = union_enum_items[struct_name]["field_lines"]
786                     init_meth_jty_strs = {}
787                     for idx, struct_line in enumerate(tag_field_lines):
788                         if idx == 0:
789                             out_java.write("\tpublic static class " + struct_name + " {\n")
790                             out_java.write("\t\tprivate " + struct_name + "() {}\n")
791                         elif idx == len(tag_field_lines) - 3:
792                             assert(struct_line.endswith("_Sentinel,"))
793                         elif idx == len(tag_field_lines) - 2:
794                             out_java.write("\t\tstatic native void init();\n")
795                             out_java.write("\t}\n")
796                         elif idx == len(tag_field_lines) - 1:
797                             assert(struct_line == "")
798                         else:
799                             var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
800                             out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
801                             out_c.write("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
802                             out_c.write("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
803                             init_meth_jty_str = ""
804                             init_meth_params = ""
805                             init_meth_body = ""
806                             if "LDK" + var_name in union_enum_items[struct_name]:
807                                 enum_var_lines = union_enum_items[struct_name]["LDK" + var_name]
808                                 for idx, field in enumerate(enum_var_lines):
809                                     if idx != 0 and idx < len(enum_var_lines) - 2:
810                                         field_ty = java_c_types(field.strip(' ;'), None)
811                                         out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.var_name + ";\n")
812                                         init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
813                                         if idx > 1:
814                                             init_meth_params = init_meth_params + ", "
815                                         init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.var_name
816                                         init_meth_body = init_meth_body + "this." + field_ty.var_name + " = " + field_ty.var_name + "; "
817                                 out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
818                                 out_java.write(init_meth_body)
819                                 out_java.write("}\n")
820                             out_java.write("\t\t}\n")
821                             init_meth_jty_strs[var_name] = init_meth_jty_str
822                     out_java.write("\tstatic { " + struct_name + ".init(); }\n")
823                     out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
824
825                     out_c.write("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
826                     for idx, struct_line in enumerate(tag_field_lines):
827                         if idx != 0 and idx < len(tag_field_lines) - 3:
828                             var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
829                             out_c.write("\t" + struct_name + "_" + var_name + "_class =\n")
830                             out_c.write("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
831                             out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_class != NULL);\n")
832                             out_c.write("\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n")
833                             out_c.write("\tDO_ASSERT(" + struct_name + "_" + var_name + "_meth != NULL);\n")
834                     out_c.write("}\n")
835                     out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (JNIEnv * env, jclass _c, jlong ptr) {\n")
836                     out_c.write("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
837                     out_c.write("\tswitch(obj->tag) {\n")
838                     for idx, struct_line in enumerate(tag_field_lines):
839                         if idx != 0 and idx < len(tag_field_lines) - 3:
840                             var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
841                             out_c.write("\t\tcase " + struct_name + "_" + var_name + ": {\n")
842                             c_params_text = ""
843                             if "LDK" + var_name in union_enum_items[struct_name]:
844                                 enum_var_lines = union_enum_items[struct_name]["LDK" + var_name]
845                                 for idx, field in enumerate(enum_var_lines):
846                                     if idx != 0 and idx < len(enum_var_lines) - 2:
847                                         field_map = map_type(field.strip(' ;'), False, None, False)
848                                         if field_map.ret_conv is not None:
849                                             out_c.write("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t").replace("_env", "env"))
850                                             out_c.write("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
851                                             out_c.write(field_map.ret_conv[1] + "\n")
852                                             c_params_text = c_params_text + ", " + field_map.ret_conv_name
853                                         else:
854                                             c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
855                             out_c.write("\t\t\treturn (*env)->NewObject(env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
856                             out_c.write("\t\t}\n")
857                     out_c.write("\t\tdefault: abort();\n")
858                     out_c.write("\t}\n}\n")
859                 elif is_unitary_enum:
860                     with open(sys.argv[3] + "/" + struct_name + ".java", "w") as out_java_enum:
861                         out_java_enum.write("package org.ldk.enums;\n\n")
862                         unitary_enums.add(struct_name)
863                         out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
864                         out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
865                         ord_v = 0
866                         for idx, struct_line in enumerate(field_lines):
867                             if idx == 0:
868                                 out_java_enum.write("public enum " + struct_name + " {\n")
869                             elif idx == len(field_lines) - 3:
870                                 assert(struct_line.endswith("_Sentinel,"))
871                             elif idx == len(field_lines) - 2:
872                                 out_java_enum.write("\t; static native void init();\n")
873                                 out_java_enum.write("\tstatic { init(); }\n")
874                                 out_java_enum.write("}")
875                                 out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
876                             elif idx == len(field_lines) - 1:
877                                 assert(struct_line == "")
878                             else:
879                                 out_java_enum.write(struct_line + "\n")
880                                 out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
881                                 ord_v = ord_v + 1
882                         out_c.write("\t}\n")
883                         out_c.write("\tabort();\n")
884                         out_c.write("}\n")
885
886                         ord_v = 0
887                         out_c.write("static jclass " + struct_name + "_class = NULL;\n")
888                         for idx, struct_line in enumerate(field_lines):
889                             if idx > 0 and idx < len(field_lines) - 3:
890                                 variant = struct_line.strip().strip(",")
891                                 out_c.write("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
892                         out_c.write("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
893                         out_c.write("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
894                         out_c.write("\tDO_ASSERT(" + struct_name + "_class != NULL);\n")
895                         for idx, struct_line in enumerate(field_lines):
896                             if idx > 0 and idx < len(field_lines) - 3:
897                                 variant = struct_line.strip().strip(",")
898                                 out_c.write("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
899                                 out_c.write("\tDO_ASSERT(" + struct_name + "_" + variant + " != NULL);\n")
900                         out_c.write("}\n")
901                         out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
902                         out_c.write("\tswitch (val) {\n")
903                         for idx, struct_line in enumerate(field_lines):
904                             if idx > 0 and idx < len(field_lines) - 3:
905                                 variant = struct_line.strip().strip(",")
906                                 out_c.write("\t\tcase " + variant + ":\n")
907                                 out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
908                                 ord_v = ord_v + 1
909                         out_c.write("\t\tdefault: abort();\n")
910                         out_c.write("\t}\n")
911                         out_c.write("}\n\n")
912                 elif len(trait_fn_lines) > 0:
913                     trait_structs.add(struct_name)
914                     map_trait(struct_name, field_var_lines, trait_fn_lines)
915                 cur_block_obj = None
916         else:
917             fn_ptr = fn_ptr_regex.match(line)
918             fn_ret_arr = fn_ret_arr_regex.match(line)
919             reg_fn = reg_fn_regex.match(line)
920             const_val = const_val_regex.match(line)
921
922             if line.startswith("#include <"):
923                 pass
924             elif line.startswith("/*"):
925                 #out_java.write("\t" + line)
926                 if not line.endswith("*/\n"):
927                     in_block_comment = True
928             elif line.startswith("typedef enum "):
929                 cur_block_obj = line
930             elif line.startswith("typedef struct "):
931                 cur_block_obj = line
932             elif line.startswith("typedef union "):
933                 cur_block_obj = line
934             elif line.startswith("typedef "):
935                 alias_match =  struct_alias_regex.match(line)
936                 if alias_match.group(1) in result_templ_structs:
937                     out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
938                     out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
939                     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")
940                     out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
941                     out_c.write("}\n")
942                     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")
943                     out_c.write("\tif (((" + alias_match.group(2) + "*)arg)->result_ok) {\n")
944                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.result;\n")
945                     out_c.write("\t} else {\n")
946                     out_c.write("\t\treturn (long)((" + alias_match.group(2) + "*)arg)->contents.err;\n")
947                     out_c.write("\t}\n}\n")
948                 pass
949             elif fn_ptr is not None:
950                 map_fn(line, fn_ptr, None, None)
951             elif fn_ret_arr is not None:
952                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
953             elif reg_fn is not None:
954                 map_fn(line, reg_fn, None, None)
955             elif const_val_regex is not None:
956                 # TODO Map const variables
957                 pass
958             else:
959                 assert(line == "\n")
960
961     out_java.write("}\n")