Drop the _call insertion
[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/ /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, arr_access):
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         self.arr_access = arr_access
20
21 class ConvInfo:
22     def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, arg_conv_cleanup, ret_conv, ret_conv_name):
23         assert(ty_info.c_ty is not None)
24         assert(ty_info.java_ty is not None)
25         assert(arg_name is not None)
26         self.passed_as_ptr = ty_info.passed_as_ptr
27         self.rust_obj = ty_info.rust_obj
28         self.c_ty = ty_info.c_ty
29         self.java_ty = ty_info.java_ty
30         self.java_fn_ty_arg = ty_info.java_fn_ty_arg
31         self.arg_name = arg_name
32         self.arg_conv = arg_conv
33         self.arg_conv_name = arg_conv_name
34         self.arg_conv_cleanup = arg_conv_cleanup
35         self.ret_conv = ret_conv
36         self.ret_conv_name = ret_conv_name
37
38     def print_ty(self):
39         out_c.write(self.c_ty)
40         out_java.write(self.java_ty)
41
42     def print_name(self):
43         if self.arg_name != "":
44             out_java.write(" " + self.arg_name)
45             out_c.write(" " + self.arg_name)
46         else:
47             out_java.write(" arg")
48             out_c.write(" arg")
49 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
50 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
51 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
52 clone_fns = set()
53 with open(sys.argv[1]) as in_h:
54     for line in in_h:
55         reg_fn = reg_fn_regex.match(line)
56         if reg_fn is not None:
57             if reg_fn.group(2).endswith("_clone"):
58                 clone_fns.add(reg_fn.group(2))
59             continue
60         arr_fn = fn_ret_arr_regex.match(line)
61         if arr_fn is not None:
62             if arr_fn.group(2).endswith("_clone"):
63                 clone_fns.add(arr_fn.group(2))
64             continue
65
66 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[4], "w") as out_c:
67     opaque_structs = set()
68     trait_structs = set()
69     unitary_enums = set()
70
71     def camel_to_snake(s):
72         # Convert camel case to snake case, in a way that appears to match cbindgen
73         con = "_"
74         ret = ""
75         lastchar = ""
76         lastund = False
77         for char in s:
78             if lastchar.isupper():
79                 if not char.isupper() and not lastund:
80                     ret = ret + "_"
81                     lastund = True
82                 else:
83                     lastund = False
84                 ret = ret + lastchar.lower()
85             else:
86                 ret = ret + lastchar
87                 if char.isupper() and not lastund:
88                     ret = ret + "_"
89                     lastund = True
90                 else:
91                     lastund = False
92             lastchar = char
93             if char.isnumeric():
94                 lastund = True
95         return (ret + lastchar.lower()).strip("_")
96
97     var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([a-z0-9]*)\]")
98     var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
99     def java_c_types(fn_arg, ret_arr_len):
100         fn_arg = fn_arg.strip()
101         if fn_arg.startswith("MUST_USE_RES "):
102             fn_arg = fn_arg[13:]
103         is_const = False
104         if fn_arg.startswith("const "):
105             fn_arg = fn_arg[6:]
106             is_const = True
107
108         is_ptr = False
109         take_by_ptr = False
110         rust_obj = None
111         arr_access = None
112         if fn_arg.startswith("LDKThirtyTwoBytes"):
113             fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
114             assert var_is_arr_regex.match(fn_arg[8:])
115             rust_obj = "LDKThirtyTwoBytes"
116             arr_access = "data"
117         if fn_arg.startswith("LDKPublicKey"):
118             fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
119             assert var_is_arr_regex.match(fn_arg[8:])
120             rust_obj = "LDKPublicKey"
121             arr_access = "compressed_form"
122         if fn_arg.startswith("LDKSecretKey"):
123             fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
124             assert var_is_arr_regex.match(fn_arg[8:])
125             rust_obj = "LDKSecretKey"
126             arr_access = "bytes"
127         if fn_arg.startswith("LDKSignature"):
128             fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
129             assert var_is_arr_regex.match(fn_arg[8:])
130             rust_obj = "LDKSignature"
131             arr_access = "compact_form"
132         if fn_arg.startswith("LDKThreeBytes"):
133             fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
134             assert var_is_arr_regex.match(fn_arg[8:])
135             rust_obj = "LDKThreeBytes"
136             arr_access = "data"
137         if fn_arg.startswith("LDKu8slice"):
138             fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
139             assert var_is_arr_regex.match(fn_arg[8:])
140             rust_obj = "LDKu8slice"
141             arr_access = "data"
142
143         if fn_arg.startswith("void"):
144             java_ty = "void"
145             c_ty = "void"
146             fn_ty_arg = "V"
147             fn_arg = fn_arg[4:].strip()
148         elif fn_arg.startswith("bool"):
149             java_ty = "boolean"
150             c_ty = "jboolean"
151             fn_ty_arg = "Z"
152             fn_arg = fn_arg[4:].strip()
153         elif fn_arg.startswith("uint8_t"):
154             java_ty = "byte"
155             c_ty = "jbyte"
156             fn_ty_arg = "B"
157             fn_arg = fn_arg[7:].strip()
158         elif fn_arg.startswith("uint16_t"):
159             java_ty = "short"
160             c_ty = "jshort"
161             fn_ty_arg = "S"
162             fn_arg = fn_arg[8:].strip()
163         elif fn_arg.startswith("uint32_t"):
164             java_ty = "int"
165             c_ty = "jint"
166             fn_ty_arg = "I"
167             fn_arg = fn_arg[8:].strip()
168         elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
169             java_ty = "long"
170             c_ty = "jlong"
171             fn_ty_arg = "J"
172             if fn_arg.startswith("uint64_t"):
173                 fn_arg = fn_arg[8:].strip()
174             else:
175                 fn_arg = fn_arg[9:].strip()
176         elif is_const and fn_arg.startswith("char *"):
177             java_ty = "String"
178             c_ty = "const char*"
179             fn_ty_arg = "Ljava/lang/String;"
180             fn_arg = fn_arg[6:].strip()
181         else:
182             ma = var_ty_regex.match(fn_arg)
183             if ma.group(1).strip() in unitary_enums:
184                 java_ty = ma.group(1).strip()
185                 c_ty = "jclass"
186                 fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
187                 fn_arg = ma.group(2).strip()
188                 rust_obj = ma.group(1).strip()
189                 take_by_ptr = True
190             else:
191                 java_ty = "long"
192                 c_ty = "jlong"
193                 fn_ty_arg = "J"
194                 fn_arg = ma.group(2).strip()
195                 rust_obj = ma.group(1).strip()
196                 take_by_ptr = True
197
198         if fn_arg.startswith(" *") or fn_arg.startswith("*"):
199             fn_arg = fn_arg.replace("*", "").strip()
200             is_ptr = True
201             c_ty = "jlong"
202             java_ty = "long"
203             fn_ty_arg = "J"
204
205         var_is_arr = var_is_arr_regex.match(fn_arg)
206         if var_is_arr is not None or ret_arr_len is not None:
207             assert(not take_by_ptr)
208             assert(not is_ptr)
209             java_ty = java_ty + "[]"
210             c_ty = c_ty + "Array"
211             if var_is_arr is not None:
212                 if var_is_arr.group(1) == "":
213                     return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
214                         passed_as_ptr=False, is_ptr=False, var_name="arg", arr_len=var_is_arr.group(2), arr_access=arr_access)
215                 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
216                     passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2), arr_access=arr_access)
217         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,
218             is_ptr=is_ptr, var_name=fn_arg, arr_len=None, arr_access=None)
219
220     def map_type(fn_arg, print_void, ret_arr_len, is_free):
221         ty_info = java_c_types(fn_arg, ret_arr_len)
222
223         if ty_info.c_ty == "void":
224             if not print_void:
225                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
226                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
227                     ret_conv = None, ret_conv_name = None)
228
229         if ty_info.c_ty.endswith("Array"):
230             arr_len = ty_info.arr_len
231             if arr_len is not None:
232                 arr_name = ty_info.var_name
233             else:
234                 arr_name = "ret"
235                 arr_len = ret_arr_len
236             assert(ty_info.c_ty == "jbyteArray")
237             ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", ", "")
238             arg_conv_cleanup = None
239             if not arr_len.isdigit():
240                 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
241                 arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = (*_env)->GetByteArrayElements (_env, " + arr_name + ", NULL);\n"
242                 arg_conv = arg_conv + arr_name + "_ref." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");"
243                 arg_conv_cleanup = "(*_env)->ReleaseByteArrayElements(_env, " + arr_name + ", (int8_t*)" + arr_name + "_ref." + ty_info.arr_access + ", 0);"
244                 arr_access = "." + ty_info.arr_access
245                 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
246                 ret_conv = (ret_conv[0], ";\njbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_name + "_var." + arr_len + ");\n")
247                 ret_conv = (ret_conv[0], ret_conv[1] + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_name + "_var." + arr_len + ", " + arr_name + "_var." + ty_info.arr_access + ");")
248             elif ty_info.rust_obj is not None:
249                 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
250                 arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
251                 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
252                 ret_conv = (ret_conv[0], "." + ty_info.arr_access + ");")
253             else:
254                 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n"
255                 arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
256                 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
257                 ret_conv = (ret_conv[0] + "*", ");")
258             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
259                 arg_conv = arg_conv, arg_conv_name = arr_name + "_ref", arg_conv_cleanup = arg_conv_cleanup,
260                 ret_conv = ret_conv, ret_conv_name = arr_name + "_arr")
261         elif ty_info.var_name != "":
262             # If we have a parameter name, print it (noting that it may indicate its a pointer)
263             if ty_info.rust_obj is not None:
264                 assert(ty_info.passed_as_ptr)
265                 opaque_arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv;\n"
266                 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
267                 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
268                 if not ty_info.is_ptr and not is_free:
269                     if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
270                         # TODO: This is a bit too naive, even with the checks above, we really need to know if rust wants a ref or not, not just if its pass as a ptr.
271                         opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
272                         opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&" + ty_info.var_name + "_conv);"
273                     elif ty_info.passed_as_ptr:
274                         opaque_arg_conv = opaque_arg_conv + "\n// Warning: we may need a move here but can't clone!"
275                 if not ty_info.is_ptr:
276                     if ty_info.rust_obj in unitary_enums:
277                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
278                             arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
279                             arg_conv_name = ty_info.var_name + "_conv",
280                             arg_conv_cleanup = None,
281                             ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
282                             ret_conv_name = ty_info.var_name + "_conv")
283                     if ty_info.rust_obj in opaque_structs:
284                         ret_conv_suf = ";\nCHECK((((long)" + ty_info.var_name + "_var.inner) & 1) == 0); // We rely on a free low bit, malloc guarantees this.\n"
285                         ret_conv_suf = ret_conv_suf + "CHECK((((long)&" + ty_info.var_name + "_var) & 1) == 0); // We rely on a free low bit, pointer alignment guarantees this.\n"
286                         ret_conv_suf = ret_conv_suf + "long " + ty_info.var_name + "_ref;\n"
287                         ret_conv_suf = ret_conv_suf + "if (" + ty_info.var_name + "_var.is_owned) {\n"
288                         ret_conv_suf = ret_conv_suf + "\t" + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner | 1;\n"
289                         ret_conv_suf = ret_conv_suf + "} else {\n"
290                         ret_conv_suf = ret_conv_suf + "\t" + ty_info.var_name + "_ref = (long)&" + ty_info.var_name + "_var;\n"
291                         ret_conv_suf = ret_conv_suf + "}"
292                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
293                             arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
294                             ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", ret_conv_suf),
295                             ret_conv_name = ty_info.var_name + "_ref")
296                     base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
297                     if ty_info.rust_obj in trait_structs:
298                         if not is_free:
299                             base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
300                             base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
301                             base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
302                         else:
303                             base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
304                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
305                             arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
306                             ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE")
307                     if ty_info.rust_obj != "LDKu8slice":
308                         # Don't bother free'ing slices passed in - Rust doesn't auto-free the
309                         # underlying unlike Vecs, and it gives Java more freedom.
310                         base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
311                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
312                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
313                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref")
314                 else:
315                     assert(not is_free)
316                     if ty_info.rust_obj in opaque_structs:
317                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
318                             arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv", arg_conv_cleanup = None,
319                             ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
320                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
321                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
322                         arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
323                         ret_conv = None, ret_conv_name = None) # its a pointer, no conv needed
324             elif ty_info.is_ptr:
325                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
326                     arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None, ret_conv = None, ret_conv_name = None)
327             elif ty_info.java_ty == "String":
328                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
329                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
330                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
331             else:
332                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
333                     arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None, ret_conv = None, ret_conv_name = None)
334         elif not print_void:
335             # We don't have a parameter name, and want one, just call it arg
336             if ty_info.rust_obj is not None:
337                 assert(not is_free or ty_info.rust_obj not in opaque_structs);
338                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
339                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
340                     arg_conv_name = "arg_conv", arg_conv_cleanup = None,
341                     ret_conv = None, ret_conv_name = None)
342             else:
343                 assert(not is_free)
344                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
345                     arg_conv = None, arg_conv_name = "arg", arg_conv_cleanup = None, ret_conv = None, ret_conv_name = None)
346         else:
347             # We don't have a parameter name, and don't want one (cause we're returning)
348             if ty_info.rust_obj is not None:
349                 if not ty_info.is_ptr:
350                     if ty_info.rust_obj in unitary_enums:
351                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
352                             arg_conv = ty_info.rust_obj + " ret = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
353                             arg_conv_name = "ret", arg_conv_cleanup = None,
354                             ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret")
355                     if ty_info.rust_obj in opaque_structs:
356                         # If we're returning a newly-allocated struct, we don't want Rust to ever
357                         # free, instead relying on the Java GC to lose the ref. We undo this in
358                         # any _free function.
359                         # To avoid any issues, we first assert that the incoming object is non-ref.
360                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
361                             ret_conv = (ty_info.rust_obj + " ret = ", ";"),
362                             ret_conv_name = "((long)ret.inner) | (ret.is_owned ? 1 : 0)",
363                             arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None)
364                     else:
365                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
366                             ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
367                             ret_conv_name = "(long)ret",
368                             arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None)
369                 else:
370                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
371                         ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
372                         arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None)
373             else:
374                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
375                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None, ret_conv = None, ret_conv_name = None)
376
377     def map_fn(line, re_match, ret_arr_len, c_call_string):
378         out_java.write("\t// " + line)
379         out_java.write("\tpublic static native ")
380         out_c.write("JNIEXPORT ")
381
382         is_free = re_match.group(2).endswith("_free")
383         struct_meth = re_match.group(2).split("_")[0]
384
385         ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
386         ret_info.print_ty()
387
388         if ret_info.ret_conv is not None:
389             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
390
391         out_java.write(" " + re_match.group(2) + "(")
392         out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
393
394         arg_names = []
395         takes_self = False
396         args_known = not ret_info.passed_as_ptr or ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs
397         for idx, arg in enumerate(re_match.group(3).split(',')):
398             if idx != 0:
399                 out_java.write(", ")
400             if arg != "void":
401                 out_c.write(", ")
402             arg_conv_info = map_type(arg, False, None, is_free)
403             if arg_conv_info.c_ty != "void":
404                 arg_conv_info.print_ty()
405                 arg_conv_info.print_name()
406             if arg_conv_info.arg_name == "this_arg":
407                 takes_self = True
408             if arg_conv_info.passed_as_ptr and not arg_conv_info.rust_obj in opaque_structs:
409                 if not arg_conv_info.rust_obj in trait_structs and not arg_conv_info.rust_obj in unitary_enums:
410                     print(re_match.group(2) + " bad - " + arg_conv_info.rust_obj)
411                     args_known = False
412             if arg_conv_info.arg_conv is not None and "Warning" in arg_conv_info.arg_conv:
413                 args_known = False
414             arg_names.append(arg_conv_info)
415
416         out_java_struct = None
417         if ("LDK" + struct_meth in opaque_structs or "LDK" + struct_meth in trait_structs) and not is_free:
418             out_java_struct = open(sys.argv[3] + "/structs/" + struct_meth + ".java", "a")
419             if not args_known:
420                 out_java_struct.write("\t// Skipped " + re_match.group(2) + "\n")
421                 out_java_struct.close()
422                 out_java_struct = None
423             else:
424                 out_java_struct.write("\tpublic ")
425                 meth_n = re_match.group(2)[len(struct_meth) + 1:]
426                 if ret_info.rust_obj == "LDK" + struct_meth:
427                     out_java_struct.write(struct_meth + "(")
428                 elif ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs:
429                     out_java_struct.write(ret_info.rust_obj.replace("LDK", "") + " " + meth_n + "(")
430                 else:
431                     out_java_struct.write(ret_info.java_ty + " " + meth_n + "(")
432                 for idx, arg in enumerate(arg_names):
433                     if idx != 0:
434                         if not takes_self or idx > 1:
435                             out_java_struct.write(", ")
436                     if arg.java_ty != "void" and arg.arg_name != "this_arg":
437                         if arg.passed_as_ptr:
438                             if arg.rust_obj in opaque_structs or arg.rust_obj in trait_structs:
439                                 out_java_struct.write(arg.rust_obj.replace("LDK", "") + " " + arg.arg_name)
440                             else:
441                                 out_java_struct.write(arg.rust_obj + " " + arg.arg_name)
442                         else:
443                             out_java_struct.write(arg.java_ty + " " + arg.arg_name)
444
445
446         out_java.write(");\n")
447         out_c.write(") {\n")
448         if out_java_struct is not None:
449             out_java_struct.write(") {\n")
450
451         for info in arg_names:
452             if info.arg_conv is not None:
453                 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
454
455         if ret_info.ret_conv is not None:
456             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'))
457         elif ret_info.c_ty != "void":
458             out_c.write("\t" + ret_info.c_ty + " ret_val = ")
459         else:
460             out_c.write("\t")
461
462         if c_call_string is None:
463             out_c.write(re_match.group(2) + "(")
464         else:
465             out_c.write(c_call_string)
466         for idx, info in enumerate(arg_names):
467             if info.arg_conv_name is not None:
468                 if idx != 0:
469                     out_c.write(", ")
470                 elif c_call_string is not None:
471                     continue
472                 out_c.write(info.arg_conv_name)
473         out_c.write(")")
474         if ret_info.ret_conv is not None:
475             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
476         else:
477             out_c.write(";")
478         for info in arg_names:
479             if info.arg_conv_cleanup is not None:
480                 out_c.write("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
481         if ret_info.ret_conv is not None:
482             out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
483         elif ret_info.c_ty != "void":
484             out_c.write("\n\treturn ret_val;")
485         out_c.write("\n}\n\n")
486         if out_java_struct is not None:
487             out_java_struct.write("\t\t")
488             if ret_info.rust_obj == "LDK" + struct_meth:
489                 out_java_struct.write("super(")
490             elif ret_info.java_ty != "void" and not ret_info.passed_as_ptr:
491                 out_java_struct.write(ret_info.java_ty + " ret = ")
492             elif ret_info.java_ty != "void":
493                 out_java_struct.write(ret_info.rust_obj.replace("LDK", "") + " ret = ")
494                 if ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs:
495                     out_java_struct.write("new " + ret_info.rust_obj.replace("LDK", "") + "(null, ")
496             out_java_struct.write("bindings." + re_match.group(2) + "(")
497             for idx, info in enumerate(arg_names):
498                 if idx != 0:
499                     out_java_struct.write(", ")
500                 if info.arg_name == "this_arg":
501                     out_java_struct.write("this.ptr")
502                 elif info.passed_as_ptr and info.rust_obj in opaque_structs:
503                     out_java_struct.write(info.arg_name + " == null ? 0 : " + info.arg_name + ".ptr & ~1")
504                 elif info.passed_as_ptr and info.rust_obj in trait_structs:
505                     out_java_struct.write(info.arg_name + " == null ? 0 : " + info.arg_name + ".ptr")
506                 else:
507                     out_java_struct.write(info.arg_name)
508             out_java_struct.write(")")
509             if ret_info.rust_obj == "LDK" + struct_meth:
510                 out_java_struct.write(");\n")
511             elif ret_info.rust_obj in opaque_structs:
512                 out_java_struct.write(");\n")
513             elif ret_info.rust_obj in trait_structs:
514                 out_java_struct.write(");\n\t\tret.ptrs_to.add(this);\n")
515             else:
516                 out_java_struct.write(";\n")
517
518             for info in arg_names:
519                 if info.arg_name == "this_arg":
520                     pass
521                 elif info.passed_as_ptr and (info.rust_obj in opaque_structs or info.rust_obj in trait_structs):
522                     out_java_struct.write("\t\tthis.ptrs_to.add(" + info.arg_name + ");\n")
523
524             if ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
525                 out_java_struct.write("\t\treturn ret;\n")
526             out_java_struct.write("\t}\n\n")
527             out_java_struct.close()
528
529     def map_unitary_enum(struct_name, field_lines):
530         with open(sys.argv[3] + "/enums/" + struct_name + ".java", "w") as out_java_enum:
531             out_java_enum.write("package org.ldk.enums;\n\n")
532             unitary_enums.add(struct_name)
533             out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
534             out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
535             ord_v = 0
536             for idx, struct_line in enumerate(field_lines):
537                 if idx == 0:
538                     out_java_enum.write("public enum " + struct_name + " {\n")
539                 elif idx == len(field_lines) - 3:
540                     assert(struct_line.endswith("_Sentinel,"))
541                 elif idx == len(field_lines) - 2:
542                     out_java_enum.write("\t; static native void init();\n")
543                     out_java_enum.write("\tstatic { init(); }\n")
544                     out_java_enum.write("}")
545                     out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
546                 elif idx == len(field_lines) - 1:
547                     assert(struct_line == "")
548                 else:
549                     out_java_enum.write(struct_line + "\n")
550                     out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
551                     ord_v = ord_v + 1
552             out_c.write("\t}\n")
553             out_c.write("\tabort();\n")
554             out_c.write("}\n")
555
556             ord_v = 0
557             out_c.write("static jclass " + struct_name + "_class = NULL;\n")
558             for idx, struct_line in enumerate(field_lines):
559                 if idx > 0 and idx < len(field_lines) - 3:
560                     variant = struct_line.strip().strip(",")
561                     out_c.write("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
562             out_c.write("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
563             out_c.write("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
564             out_c.write("\tCHECK(" + struct_name + "_class != NULL);\n")
565             for idx, struct_line in enumerate(field_lines):
566                 if idx > 0 and idx < len(field_lines) - 3:
567                     variant = struct_line.strip().strip(",")
568                     out_c.write("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
569                     out_c.write("\tCHECK(" + struct_name + "_" + variant + " != NULL);\n")
570             out_c.write("}\n")
571             out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
572             out_c.write("\tswitch (val) {\n")
573             for idx, struct_line in enumerate(field_lines):
574                 if idx > 0 and idx < len(field_lines) - 3:
575                     variant = struct_line.strip().strip(",")
576                     out_c.write("\t\tcase " + variant + ":\n")
577                     out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
578                     ord_v = ord_v + 1
579             out_c.write("\t\tdefault: abort();\n")
580             out_c.write("\t}\n")
581             out_c.write("}\n\n")
582
583     def map_complex_enum(struct_name, union_enum_items):
584         tag_field_lines = union_enum_items["field_lines"]
585         init_meth_jty_strs = {}
586         for idx, struct_line in enumerate(tag_field_lines):
587             if idx == 0:
588                 out_java.write("\tpublic static class " + struct_name + " {\n")
589                 out_java.write("\t\tprivate " + struct_name + "() {}\n")
590             elif idx == len(tag_field_lines) - 3:
591                 assert(struct_line.endswith("_Sentinel,"))
592             elif idx == len(tag_field_lines) - 2:
593                 out_java.write("\t\tstatic native void init();\n")
594                 out_java.write("\t}\n")
595             elif idx == len(tag_field_lines) - 1:
596                 assert(struct_line == "")
597             else:
598                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
599                 out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
600                 out_c.write("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
601                 out_c.write("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
602                 init_meth_jty_str = ""
603                 init_meth_params = ""
604                 init_meth_body = ""
605                 if "LDK" + var_name in union_enum_items:
606                     enum_var_lines = union_enum_items["LDK" + var_name]
607                     for idx, field in enumerate(enum_var_lines):
608                         if idx != 0 and idx < len(enum_var_lines) - 2:
609                             field_ty = java_c_types(field.strip(' ;'), None)
610                             out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.var_name + ";\n")
611                             init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
612                             if idx > 1:
613                                 init_meth_params = init_meth_params + ", "
614                             init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.var_name
615                             init_meth_body = init_meth_body + "this." + field_ty.var_name + " = " + field_ty.var_name + "; "
616                     out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
617                     out_java.write(init_meth_body)
618                     out_java.write("}\n")
619                 out_java.write("\t\t}\n")
620                 init_meth_jty_strs[var_name] = init_meth_jty_str
621         out_java.write("\tstatic { " + struct_name + ".init(); }\n")
622         out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
623
624         out_c.write("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
625         for idx, struct_line in enumerate(tag_field_lines):
626             if idx != 0 and idx < len(tag_field_lines) - 3:
627                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
628                 out_c.write("\t" + struct_name + "_" + var_name + "_class =\n")
629                 out_c.write("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
630                 out_c.write("\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n")
631                 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")
632                 out_c.write("\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n")
633         out_c.write("}\n")
634         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")
635         out_c.write("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
636         out_c.write("\tswitch(obj->tag) {\n")
637         for idx, struct_line in enumerate(tag_field_lines):
638             if idx != 0 and idx < len(tag_field_lines) - 3:
639                 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
640                 out_c.write("\t\tcase " + struct_name + "_" + var_name + ": {\n")
641                 c_params_text = ""
642                 if "LDK" + var_name in union_enum_items:
643                     enum_var_lines = union_enum_items["LDK" + var_name]
644                     for idx, field in enumerate(enum_var_lines):
645                         if idx != 0 and idx < len(enum_var_lines) - 2:
646                             field_map = map_type(field.strip(' ;'), False, None, False)
647                             if field_map.ret_conv is not None:
648                                 out_c.write("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t").replace("_env", "env"))
649                                 out_c.write("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
650                                 out_c.write(field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
651                                 c_params_text = c_params_text + ", " + field_map.ret_conv_name
652                             else:
653                                 c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
654                 out_c.write("\t\t\treturn (*env)->NewObject(env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
655                 out_c.write("\t\t}\n")
656         out_c.write("\t\tdefault: abort();\n")
657         out_c.write("\t}\n}\n")
658
659     def map_trait(struct_name, field_var_lines, trait_fn_lines):
660         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_trait:
661             out_c.write("typedef struct " + struct_name + "_JCalls {\n")
662             out_c.write("\tatomic_size_t refcnt;\n")
663             out_c.write("\tJavaVM *vm;\n")
664             out_c.write("\tjweak o;\n")
665             for var_line in field_var_lines:
666                 if var_line.group(1) in trait_structs:
667                     out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
668             for fn_line in trait_fn_lines:
669                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
670                     out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
671             out_c.write("} " + struct_name + "_JCalls;\n")
672
673             out_java_trait.write("package org.ldk.structs;\n\n")
674             out_java_trait.write("import org.ldk.impl.bindings;\n\n")
675             out_java_trait.write("import org.ldk.enums.*;\n\n")
676             out_java_trait.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
677             out_java_trait.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
678             out_java_trait.write("\tpublic " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg")
679             for var_line in field_var_lines:
680                 if var_line.group(1) in trait_structs:
681                     out_java_trait.write(", bindings." + var_line.group(1) + " " + var_line.group(2))
682             out_java_trait.write(") {\n")
683             out_java_trait.write("\t\tsuper(bindings." + struct_name + "_new(arg")
684             for var_line in field_var_lines:
685                 if var_line.group(1) in trait_structs:
686                     out_java_trait.write(", " + var_line.group(2))
687             out_java_trait.write("));\n")
688             out_java_trait.write("\t\tthis.ptrs_to.add(arg);\n")
689             out_java_trait.write("\t}\n")
690             out_java_trait.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
691             out_java_trait.write("\tprotected void finalize() throws Throwable {\n")
692             out_java_trait.write("\t\tbindings." + struct_name.replace("LDK","") + "_free(ptr); super.finalize();\n")
693             out_java_trait.write("\t}\n\n")
694
695             out_java.write("\tpublic interface " + struct_name + " {\n")
696             java_meths = []
697             for fn_line in trait_fn_lines:
698                 java_meth_descr = "("
699                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
700                     ret_ty_info = java_c_types(fn_line.group(1), None)
701
702                     out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
703                     is_const = fn_line.group(3) is not None
704                     out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
705                     if is_const:
706                         out_c.write("const void* this_arg")
707                     else:
708                         out_c.write("void* this_arg")
709
710                     arg_names = []
711                     for idx, arg in enumerate(fn_line.group(4).split(',')):
712                         if arg == "":
713                             continue
714                         if idx >= 2:
715                             out_java.write(", ")
716                         out_c.write(", ")
717                         arg_conv_info = map_type(arg, True, None, False)
718                         out_c.write(arg.strip())
719                         out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
720                         arg_names.append(arg_conv_info)
721                         java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
722                     java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
723                     java_meths.append(java_meth_descr)
724
725                     out_java.write(");\n")
726                     out_c.write(") {\n")
727                     out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
728                     out_c.write("\tJNIEnv *env;\n")
729                     out_c.write("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
730
731                     for arg_info in arg_names:
732                         if arg_info.ret_conv is not None:
733                             out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "env"));
734                             out_c.write(arg_info.arg_name)
735                             out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "env") + "\n")
736
737                     out_c.write("\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tCHECK(obj != NULL);\n")
738                     if ret_ty_info.c_ty.endswith("Array"):
739                         assert(ret_ty_info.c_ty == "jbyteArray")
740                         out_c.write("\tjbyteArray jret = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.group(2) + "_meth")
741                     elif not ret_ty_info.passed_as_ptr:
742                         out_c.write("\treturn (*env)->Call" + ret_ty_info.java_ty.title() + "Method(env, obj, j_calls->" + fn_line.group(2) + "_meth")
743                     else:
744                         out_c.write("\t" + fn_line.group(1).strip() + "* ret = (" + fn_line.group(1).strip() + "*)(*env)->CallLongMethod(env, obj, j_calls->" + fn_line.group(2) + "_meth");
745
746                     for arg_info in arg_names:
747                         if arg_info.ret_conv is not None:
748                             out_c.write(", " + arg_info.ret_conv_name)
749                         else:
750                             out_c.write(", " + arg_info.arg_name)
751                     out_c.write(");\n");
752                     if ret_ty_info.c_ty.endswith("Array"):
753                         out_c.write("\t" + ret_ty_info.rust_obj + " ret;\n")
754                         out_c.write("\tCHECK((*env)->GetArrayLength(env, jret) == " + ret_ty_info.arr_len + ");\n")
755                         out_c.write("\t(*env)->GetByteArrayRegion(env, jret, 0, " + ret_ty_info.arr_len + ", ret." + ret_ty_info.arr_access + ");\n")
756                         out_c.write("\treturn ret;\n")
757
758                     if ret_ty_info.passed_as_ptr:
759                         out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
760                         out_c.write("\tFREE(ret);\n")
761                         out_c.write("\treturn res;\n")
762                     out_c.write("}\n")
763                 elif fn_line.group(2) == "free":
764                     out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
765                     out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
766                     out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
767                     out_c.write("\t\tJNIEnv *env;\n")
768                     out_c.write("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
769                     out_c.write("\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n")
770                     out_c.write("\t\tFREE(j_calls);\n")
771                     out_c.write("\t}\n}\n")
772
773             # Write out a clone function whether we need one or not, as we use them in moving to rust
774             out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
775             out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
776             out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
777             for var_line in field_var_lines:
778                 if var_line.group(1) in trait_structs:
779                     out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
780             out_c.write("\treturn (void*) this_arg;\n")
781             out_c.write("}\n")
782
783             out_java.write("\t}\n")
784
785             out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
786             out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
787             for var_line in field_var_lines:
788                 if var_line.group(1) in trait_structs:
789                     out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
790                     out_c.write(", jobject " + var_line.group(2))
791             out_java.write(");\n")
792             out_c.write(") {\n")
793
794             out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
795             out_c.write("\tCHECK(c != NULL);\n")
796             out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
797             out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
798             out_c.write("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
799             out_c.write("\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n")
800             for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
801                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
802                     out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
803                     out_c.write("\tCHECK(calls->" + fn_line.group(2) + "_meth != NULL);\n")
804             out_c.write("\n\t" + struct_name + " ret = {\n")
805             out_c.write("\t\t.this_arg = (void*) calls,\n")
806             for fn_line in trait_fn_lines:
807                 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
808                     out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
809                 elif fn_line.group(2) == "free":
810                     out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
811                 else:
812                     clone_fns.add(struct_name + "_clone")
813                     out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
814             for var_line in field_var_lines:
815                 if var_line.group(1) in trait_structs:
816                     out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
817             out_c.write("\t};\n")
818             for var_line in field_var_lines:
819                 if var_line.group(1) in trait_structs:
820                     out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
821             out_c.write("\treturn ret;\n")
822             out_c.write("}\n")
823
824             out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
825             for var_line in field_var_lines:
826                 if var_line.group(1) in trait_structs:
827                     out_c.write(", jobject " + var_line.group(2))
828             out_c.write(") {\n")
829             out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
830             out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
831             for var_line in field_var_lines:
832                 if var_line.group(1) in trait_structs:
833                     out_c.write(", " + var_line.group(2))
834             out_c.write(");\n")
835             out_c.write("\treturn (long)res_ptr;\n")
836             out_c.write("}\n")
837
838             out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
839             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")
840             out_c.write("\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n")
841             out_c.write("\tCHECK(ret != NULL);\n")
842             out_c.write("\treturn ret;\n")
843             out_c.write("}\n")
844
845         for fn_line in trait_fn_lines:
846             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
847             is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
848             if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
849                 dummy_line = fn_line.group(1) + struct_name.replace("LDK", "") + "_" + fn_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
850                 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(this_arg_conv->" + fn_line.group(2) + ")(this_arg_conv->this_arg")
851
852     out_c.write("""#include \"org_ldk_impl_bindings.h\"
853 #include <rust_types.h>
854 #include <lightning.h>
855 #include <string.h>
856 #include <stdatomic.h>
857 """)
858
859     if sys.argv[4] == "false":
860         out_c.write("#define MALLOC(a, _) malloc(a)\n")
861         out_c.write("#define FREE free\n")
862         out_c.write("#define DO_ASSERT(a) (void)(a)\n")
863         out_c.write("#define CHECK(a)\n")
864     else:
865         out_c.write("""#include <assert.h>
866 // Always run a, then assert it is true:
867 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
868 // Assert a is true or do nothing
869 #define CHECK(a) DO_ASSERT(a)
870
871 // Running a leak check across all the allocations and frees of the JDK is a mess,
872 // so instead we implement our own naive leak checker here, relying on the -wrap
873 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
874 // and free'd in Rust or C across the generated bindings shared library.
875 #include <threads.h>
876 #include <execinfo.h>
877 #include <unistd.h>
878 static mtx_t allocation_mtx;
879
880 void __attribute__((constructor)) init_mtx() {
881         DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
882 }
883
884 #define BT_MAX 128
885 typedef struct allocation {
886         struct allocation* next;
887         void* ptr;
888         const char* struct_name;
889         void* bt[BT_MAX];
890         int bt_len;
891 } allocation;
892 static allocation* allocation_ll = NULL;
893
894 void* __real_malloc(size_t len);
895 void* __real_calloc(size_t nmemb, size_t len);
896 static void new_allocation(void* res, const char* struct_name) {
897         allocation* new_alloc = __real_malloc(sizeof(allocation));
898         new_alloc->ptr = res;
899         new_alloc->struct_name = struct_name;
900         new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
901         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
902         new_alloc->next = allocation_ll;
903         allocation_ll = new_alloc;
904         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
905 }
906 static void* MALLOC(size_t len, const char* struct_name) {
907         void* res = __real_malloc(len);
908         new_allocation(res, struct_name);
909         return res;
910 }
911 void __real_free(void* ptr);
912 static void alloc_freed(void* ptr) {
913         allocation* p = NULL;
914         DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
915         allocation* it = allocation_ll;
916         while (it->ptr != ptr) { p = it; it = it->next; }
917         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
918         DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
919         DO_ASSERT(it->ptr == ptr);
920         __real_free(it);
921 }
922 static void FREE(void* ptr) {
923         alloc_freed(ptr);
924         __real_free(ptr);
925 }
926
927 void* __wrap_malloc(size_t len) {
928         void* res = __real_malloc(len);
929         new_allocation(res, "malloc call");
930         return res;
931 }
932 void* __wrap_calloc(size_t nmemb, size_t len) {
933         void* res = __real_calloc(nmemb, len);
934         new_allocation(res, "calloc call");
935         return res;
936 }
937 void __wrap_free(void* ptr) {
938         alloc_freed(ptr);
939         __real_free(ptr);
940 }
941
942 void* __real_realloc(void* ptr, size_t newlen);
943 void* __wrap_realloc(void* ptr, size_t len) {
944         alloc_freed(ptr);
945         void* res = __real_realloc(ptr, len);
946         new_allocation(res, "realloc call");
947         return res;
948 }
949 void __wrap_reallocarray(void* ptr, size_t new_sz) {
950         // Rust doesn't seem to use reallocarray currently
951         assert(false);
952 }
953
954 void __attribute__((destructor)) check_leaks() {
955         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
956                 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
957                 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
958                 fprintf(stderr, "\\n\\n");
959         }
960         DO_ASSERT(allocation_ll == NULL);
961 }
962 """)
963     out_java.write("""package org.ldk.impl;
964 import org.ldk.enums.*;
965
966 public class bindings {
967         public static class VecOrSliceDef {
968                 public long dataptr;
969                 public long datalen;
970                 public long stride;
971                 public VecOrSliceDef(long dataptr, long datalen, long stride) {
972                         this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
973                 }
974         }
975         static {
976                 System.loadLibrary(\"lightningjni\");
977                 init(java.lang.Enum.class, VecOrSliceDef.class);
978         }
979         static native void init(java.lang.Class c, java.lang.Class slicedef);
980
981         public static native boolean deref_bool(long ptr);
982         public static native long deref_long(long ptr);
983         public static native void free_heap_ptr(long ptr);
984         public static native byte[] read_bytes(long ptr, long len);
985         public static native byte[] get_u8_slice_bytes(long slice_ptr);
986         public static native long bytes_to_u8_vec(byte[] bytes);
987         public static native long new_txpointer_copy_data(byte[] txdata);
988         public static native long vec_slice_len(long vec);
989         public static native long new_empty_slice_vec();
990
991 """)
992     out_c.write("""
993 static jmethodID ordinal_meth = NULL;
994 static jmethodID slicedef_meth = NULL;
995 static jclass slicedef_cls = NULL;
996 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
997         ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
998         CHECK(ordinal_meth != NULL);
999         slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
1000         CHECK(slicedef_meth != NULL);
1001         slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
1002         CHECK(slicedef_cls != NULL);
1003 }
1004
1005 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
1006         return *((bool*)ptr);
1007 }
1008 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
1009         return *((long*)ptr);
1010 }
1011 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
1012         FREE((void*)ptr);
1013 }
1014 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
1015         jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
1016         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
1017         return ret_arr;
1018 }
1019 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
1020         LDKu8slice *slice = (LDKu8slice*)slice_ptr;
1021         jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
1022         (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
1023         return ret_arr;
1024 }
1025 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
1026         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
1027         vec->datalen = (*_env)->GetArrayLength(_env, bytes);
1028         vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
1029         (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
1030         return (long)vec;
1031 }
1032 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
1033         LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
1034         txdata->datalen = (*env)->GetArrayLength(env, bytes);
1035         txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
1036         txdata->data_is_owned = true;
1037         (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
1038         return (long)txdata;
1039 }
1040 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
1041         // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
1042         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
1043         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
1044         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
1045         _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
1046         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
1047         return (long)vec->datalen;
1048 }
1049 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
1050         // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
1051         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
1052         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
1053         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
1054         _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
1055         LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
1056         vec->data = NULL;
1057         vec->datalen = 0;
1058         return (long)vec;
1059 }
1060
1061 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
1062 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
1063 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
1064 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
1065
1066 """)
1067
1068     with open(sys.argv[3] + "/structs/CommonBase.java", "a") as out_java_struct:
1069         out_java_struct.write("""package org.ldk.structs;
1070 import java.util.LinkedList;
1071 class CommonBase {
1072         final long ptr;
1073         LinkedList<Object> ptrs_to = new LinkedList();
1074         protected CommonBase(long ptr) { this.ptr = ptr; }
1075         public long _test_only_get_ptr() { return this.ptr; }
1076 }
1077 """)
1078
1079     in_block_comment = False
1080     cur_block_obj = None
1081
1082     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1083
1084     line_indicates_result_regex = re.compile("^   (LDKCResultPtr_[A-Za-z_0-9]*) contents;$")
1085     line_indicates_vec_regex = re.compile("^   ([A-Za-z_0-9]*) \*data;$")
1086     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
1087     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
1088     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
1089     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
1090     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
1091     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1092     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
1093     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
1094     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
1095     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
1096     struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
1097     assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
1098
1099     result_templ_structs = set()
1100     union_enum_items = {}
1101     result_ptr_struct_items = {}
1102     for line in in_h:
1103         if in_block_comment:
1104             if line.endswith("*/\n"):
1105                 in_block_comment = False
1106         elif cur_block_obj is not None:
1107             cur_block_obj  = cur_block_obj + line
1108             if line.startswith("} "):
1109                 field_lines = []
1110                 struct_name = None
1111                 vec_ty = None
1112                 obj_lines = cur_block_obj.split("\n")
1113                 is_opaque = False
1114                 result_contents = None
1115                 is_unitary_enum = False
1116                 is_union_enum = False
1117                 is_union = False
1118                 is_tuple = False
1119                 trait_fn_lines = []
1120                 field_var_lines = []
1121
1122                 for idx, struct_line in enumerate(obj_lines):
1123                     if struct_line.strip().startswith("/*"):
1124                         in_block_comment = True
1125                     if in_block_comment:
1126                         if struct_line.endswith("*/"):
1127                             in_block_comment = False
1128                     else:
1129                         struct_name_match = struct_name_regex.match(struct_line)
1130                         if struct_name_match is not None:
1131                             struct_name = struct_name_match.group(3)
1132                             if struct_name_match.group(1) == "enum":
1133                                 if not struct_name.endswith("_Tag"):
1134                                     is_unitary_enum = True
1135                                 else:
1136                                     is_union_enum = True
1137                             elif struct_name_match.group(1) == "union":
1138                                 is_union = True
1139                         if line_indicates_opaque_regex.match(struct_line):
1140                             is_opaque = True
1141                         result_match = line_indicates_result_regex.match(struct_line)
1142                         if result_match is not None:
1143                             result_contents = result_match.group(1)
1144                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
1145                         if vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
1146                             vec_ty = vec_ty_match.group(1)
1147                         elif struct_name.startswith("LDKC2TupleTempl_") or struct_name.startswith("LDKC3TupleTempl_"):
1148                             is_tuple = True
1149                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
1150                         if trait_fn_match is not None:
1151                             trait_fn_lines.append(trait_fn_match)
1152                         field_var_match = line_field_var_regex.match(struct_line)
1153                         if field_var_match is not None:
1154                             field_var_lines.append(field_var_match)
1155                         field_lines.append(struct_line)
1156
1157                 assert(struct_name is not None)
1158                 assert(len(trait_fn_lines) == 0 or not (is_opaque or is_unitary_enum or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
1159                 assert(not is_opaque or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
1160                 assert(not is_unitary_enum or not (len(trait_fn_lines) != 0 or is_opaque or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
1161                 assert(not is_union_enum or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_opaque or is_union or result_contents is not None or vec_ty is not None))
1162                 assert(not is_union or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or result_contents is not None or vec_ty is not None))
1163                 assert(result_contents is None 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))
1164                 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 result_contents is not None))
1165
1166                 if is_opaque:
1167                     opaque_structs.add(struct_name)
1168                     with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_struct:
1169                         out_java_struct.write("package org.ldk.structs;\n\n")
1170                         out_java_struct.write("import org.ldk.impl.bindings;\n")
1171                         out_java_struct.write("import org.ldk.enums.*;\n\n")
1172                         out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
1173                         out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
1174                         out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1175                         out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1176                         out_java_struct.write("\t\tbindings." + struct_name.replace("LDK","") + "_free(ptr); super.finalize();\n")
1177                         out_java_struct.write("\t}\n\n")
1178                 elif result_contents is not None:
1179                     result_templ_structs.add(struct_name)
1180                     assert result_contents in result_ptr_struct_items
1181                 elif struct_name.startswith("LDKCResultPtr_"):
1182                     for line in field_lines:
1183                         if line.endswith("*result;"):
1184                             res_ty = line[:-8].strip()
1185                         elif line.endswith("*err;"):
1186                             err_ty = line[:-5].strip()
1187                     result_ptr_struct_items[struct_name] = (res_ty, err_ty)
1188                 elif is_tuple:
1189                     out_java.write("\tpublic static native long " + struct_name + "_new(")
1190                     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *_env, jclass _b")
1191                     for idx, line in enumerate(field_lines):
1192                         if idx != 0 and idx < len(field_lines) - 2:
1193                             ty_info = java_c_types(line.strip(';'), None)
1194                             if idx != 1:
1195                                 out_java.write(", ")
1196                             e = chr(ord('a') + idx - 1)
1197                             out_java.write(ty_info.java_ty + " " + e)
1198                             out_c.write(", " + ty_info.c_ty + " " + e)
1199                     out_java.write(");\n")
1200                     out_c.write(") {\n")
1201                     out_c.write("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1202                     for idx, line in enumerate(field_lines):
1203                         if idx != 0 and idx < len(field_lines) - 2:
1204                             ty_info = map_type(line.strip(';'), False, None, False)
1205                             e = chr(ord('a') + idx - 1)
1206                             if ty_info.arg_conv is not None:
1207                                 out_c.write("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
1208                                 out_c.write("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
1209                             else:
1210                                 out_c.write("\tret->" + e + " = " + e + ";\n")
1211                             assert ty_info.arg_conv_cleanup is None
1212                     out_c.write("\treturn (long)ret;\n")
1213                     out_c.write("}\n")
1214                 elif vec_ty is not None:
1215                     if vec_ty in opaque_structs:
1216                         out_java.write("\tpublic static native long[] " + struct_name + "_arr_info(long vec_ptr);\n")
1217                         out_c.write("JNIEXPORT jlongArray JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1218                     else:
1219                         out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
1220                         out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1221                     out_c.write("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
1222                     if vec_ty in opaque_structs:
1223                         out_c.write("\tjlongArray ret = (*env)->NewLongArray(env, vec->datalen);\n")
1224                         out_c.write("\tjlong *ret_elems = (*env)->GetPrimitiveArrayCritical(env, ret, NULL);\n")
1225                         out_c.write("\tfor (size_t i = 0; i < vec->datalen; i++) {\n")
1226                         out_c.write("\t\tCHECK((((long)vec->data[i].inner) & 1) == 0);\n")
1227                         out_c.write("\t\tret_elems[i] = (long)vec->data[i].inner | (vec->data[i].is_owned ? 1 : 0);\n")
1228                         out_c.write("\t}\n")
1229                         out_c.write("\t(*env)->ReleasePrimitiveArrayCritical(env, ret, ret_elems, 0);\n")
1230                         out_c.write("\treturn ret;\n")
1231                     else:
1232                         out_c.write("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
1233                     out_c.write("}\n")
1234
1235                     ty_info = map_type(vec_ty + " arr_elem", False, None, False)
1236                     if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
1237                         out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
1238                         out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *env, jclass _b, j" + ty_info.java_ty + "Array elems){\n")
1239                         out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1240                         out_c.write("\tret->datalen = (*env)->GetArrayLength(env, elems);\n")
1241                         out_c.write("\tif (ret->datalen == 0) {\n")
1242                         out_c.write("\t\tret->data = NULL;\n")
1243                         out_c.write("\t} else {\n")
1244                         out_c.write("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1245                         out_c.write("\t\t" + ty_info.c_ty + " *java_elems = (*env)->GetPrimitiveArrayCritical(env, elems, NULL);\n")
1246                         out_c.write("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1247                         if ty_info.arg_conv is not None:
1248                             out_c.write("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1249                             out_c.write("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1250                             out_c.write("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1251                             assert ty_info.arg_conv_cleanup is None
1252                         else:
1253                             out_c.write("\t\t\tret->data[i] = java_elems[i];\n")
1254                         out_c.write("\t\t}\n")
1255                         out_c.write("\t\t(*env)->ReleasePrimitiveArrayCritical(env, elems, java_elems, 0);\n")
1256                         out_c.write("\t}\n")
1257                         out_c.write("\treturn (long)ret;\n")
1258                         out_c.write("}\n")
1259                 elif is_union_enum:
1260                     assert(struct_name.endswith("_Tag"))
1261                     struct_name = struct_name[:-4]
1262                     union_enum_items[struct_name] = {"field_lines": field_lines}
1263                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
1264                     enum_var_name = struct_name.split("_")
1265                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
1266                 elif struct_name in union_enum_items:
1267                     map_complex_enum(struct_name, union_enum_items[struct_name])
1268                 elif is_unitary_enum:
1269                     map_unitary_enum(struct_name, field_lines)
1270                 elif len(trait_fn_lines) > 0:
1271                     trait_structs.add(struct_name)
1272                     map_trait(struct_name, field_var_lines, trait_fn_lines)
1273                 cur_block_obj = None
1274         else:
1275             fn_ptr = fn_ptr_regex.match(line)
1276             fn_ret_arr = fn_ret_arr_regex.match(line)
1277             reg_fn = reg_fn_regex.match(line)
1278             const_val = const_val_regex.match(line)
1279
1280             if line.startswith("#include <"):
1281                 pass
1282             elif line.startswith("/*"):
1283                 #out_java.write("\t" + line)
1284                 if not line.endswith("*/\n"):
1285                     in_block_comment = True
1286             elif line.startswith("typedef enum "):
1287                 cur_block_obj = line
1288             elif line.startswith("typedef struct "):
1289                 cur_block_obj = line
1290             elif line.startswith("typedef union "):
1291                 cur_block_obj = line
1292             elif line.startswith("typedef "):
1293                 alias_match =  struct_alias_regex.match(line)
1294                 if alias_match.group(1) in result_templ_structs:
1295                     out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
1296                     out_java.write("\tpublic static native long " + alias_match.group(2) + "_get_inner(long arg);\n")
1297                     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")
1298                     out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
1299                     out_c.write("}\n")
1300                     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")
1301                     contents_ty = alias_match.group(1).replace("LDKCResultTempl", "LDKCResultPtr")
1302                     res_ty, err_ty = result_ptr_struct_items[contents_ty]
1303                     out_c.write("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
1304                     out_c.write("\tif (val->result_ok) {\n")
1305                     if res_ty not in opaque_structs:
1306                         out_c.write("\t\treturn (long)val->contents.result;\n")
1307                     else:
1308                         out_c.write("\t\treturn (long)(val->contents.result->inner) | (val->contents.result->is_owned ? 1 : 0);\n")
1309                     out_c.write("\t} else {\n")
1310                     if err_ty not in opaque_structs:
1311                         out_c.write("\t\treturn (long)val->contents.err;\n")
1312                     else:
1313                         out_c.write("\t\treturn (long)(val->contents.err->inner) | (val->contents.err->is_owned ? 1 : 0);\n")
1314                     out_c.write("\t}\n}\n")
1315                 pass
1316             elif fn_ptr is not None:
1317                 map_fn(line, fn_ptr, None, None)
1318             elif fn_ret_arr is not None:
1319                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1320             elif reg_fn is not None:
1321                 map_fn(line, reg_fn, None, None)
1322             elif const_val_regex is not None:
1323                 # TODO Map const variables
1324                 pass
1325             else:
1326                 assert(line == "\n")
1327
1328     out_java.write("}\n")
1329     for struct_name in opaque_structs:
1330         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1331             out_java_struct.write("}\n")
1332     for struct_name in trait_structs:
1333         with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1334             out_java_struct.write("}\n")