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