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