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