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