initiate language-dependent type mappings from C
[ldk-java] / genbindings.py
1 #!/usr/bin/env python3
2 import sys, re
3
4 if len(sys.argv) != 7:
5     print("USAGE: /path/to/lightning.h /path/to/bindings/output /path/to/bindings/ /path/to/bindings/output.c debug lang")
6     sys.exit(1)
7
8 if sys.argv[5] == "false":
9     DEBUG = False
10 elif sys.argv[5] == "true":
11     DEBUG = True
12 else:
13     print("debug should be true or false and indicates whether to track allocations and ensure we don't leak")
14     sys.exit(1)
15
16 if sys.argv[6] == "java":
17     from java_strings import Consts
18 elif sys.argv[6] == "typescript":
19     from typescript_strings import Consts
20 else:
21     print("Only java or typescript can be set for lang")
22     sys.exit(1)
23 consts = Consts(DEBUG)
24
25 from bindingstypes import *
26
27 c_file = ""
28 def write_c(s):
29     global c_file
30     c_file += s
31
32 def camel_to_snake(s):
33     # Convert camel case to snake case, in a way that appears to match cbindgen
34     con = "_"
35     ret = ""
36     lastchar = ""
37     lastund = False
38     for char in s:
39         if lastchar.isupper():
40             if not char.isupper() and not lastund:
41                 ret = ret + "_"
42                 lastund = True
43             else:
44                 lastund = False
45             ret = ret + lastchar.lower()
46         else:
47             ret = ret + lastchar
48             if char.isupper() and not lastund:
49                 ret = ret + "_"
50                 lastund = True
51             else:
52                 lastund = False
53         lastchar = char
54         if char.isnumeric():
55             lastund = True
56     return (ret + lastchar.lower()).strip("_")
57
58 unitary_enums = set()
59 complex_enums = set()
60 opaque_structs = set()
61 trait_structs = set()
62 result_types = set()
63 tuple_types = {}
64
65 var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([a-z0-9]*)\]")
66 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
67 java_c_types_none_allowed = True # Unset when we do the real pass that populates the above sets
68 def java_c_types(fn_arg, ret_arr_len):
69     fn_arg = fn_arg.strip()
70     if fn_arg.startswith("MUST_USE_RES "):
71         fn_arg = fn_arg[13:]
72     is_const = False
73     if fn_arg.startswith("const "):
74         fn_arg = fn_arg[6:]
75         is_const = True
76     if fn_arg.startswith("struct "):
77         fn_arg = fn_arg[7:]
78     if fn_arg.startswith("enum "):
79         fn_arg = fn_arg[5:]
80     fn_arg = fn_arg.replace("NONNULL_PTR", "")
81
82     is_ptr = False
83     take_by_ptr = False
84     rust_obj = None
85     arr_access = None
86     java_hu_ty = None
87     if fn_arg.startswith("LDKThirtyTwoBytes"):
88         fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
89         assert var_is_arr_regex.match(fn_arg[8:])
90         rust_obj = "LDKThirtyTwoBytes"
91         arr_access = "data"
92     elif fn_arg.startswith("LDKPublicKey"):
93         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
94         assert var_is_arr_regex.match(fn_arg[8:])
95         rust_obj = "LDKPublicKey"
96         arr_access = "compressed_form"
97     elif fn_arg.startswith("LDKSecretKey"):
98         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
99         assert var_is_arr_regex.match(fn_arg[8:])
100         rust_obj = "LDKSecretKey"
101         arr_access = "bytes"
102     elif fn_arg.startswith("LDKSignature"):
103         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
104         assert var_is_arr_regex.match(fn_arg[8:])
105         rust_obj = "LDKSignature"
106         arr_access = "compact_form"
107     elif fn_arg.startswith("LDKThreeBytes"):
108         fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
109         assert var_is_arr_regex.match(fn_arg[8:])
110         rust_obj = "LDKThreeBytes"
111         arr_access = "data"
112     elif fn_arg.startswith("LDKFourBytes"):
113         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[4]"
114         assert var_is_arr_regex.match(fn_arg[8:])
115         rust_obj = "LDKFourBytes"
116         arr_access = "data"
117     elif fn_arg.startswith("LDKSixteenBytes"):
118         fn_arg = "uint8_t (*" + fn_arg[16:] + ")[16]"
119         assert var_is_arr_regex.match(fn_arg[8:])
120         rust_obj = "LDKSixteenBytes"
121         arr_access = "data"
122     elif fn_arg.startswith("LDKTenBytes"):
123         fn_arg = "uint8_t (*" + fn_arg[12:] + ")[10]"
124         assert var_is_arr_regex.match(fn_arg[8:])
125         rust_obj = "LDKTenBytes"
126         arr_access = "data"
127     elif fn_arg.startswith("LDKu8slice"):
128         fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
129         assert var_is_arr_regex.match(fn_arg[8:])
130         rust_obj = "LDKu8slice"
131         arr_access = "data"
132     elif fn_arg.startswith("LDKCVec_u8Z"):
133         fn_arg = "uint8_t (*" + fn_arg[12:] + ")[datalen]"
134         rust_obj = "LDKCVec_u8Z"
135         assert var_is_arr_regex.match(fn_arg[8:])
136         arr_access = "data"
137     elif fn_arg.startswith("LDKTransaction"):
138         fn_arg = "uint8_t (*" + fn_arg[15:] + ")[datalen]"
139         rust_obj = "LDKTransaction"
140         assert var_is_arr_regex.match(fn_arg[8:])
141         arr_access = "data"
142     elif fn_arg.startswith("LDKCVec_"):
143         is_ptr = False
144         if "*" in fn_arg:
145             fn_arg = fn_arg.replace("*", "")
146             is_ptr = True
147
148         tyn = fn_arg[8:].split(" ")
149         assert tyn[0].endswith("Z")
150         if tyn[0] == "u64Z":
151             new_arg = "uint64_t"
152         else:
153             new_arg = "LDK" + tyn[0][:-1]
154         for a in tyn[1:]:
155             new_arg = new_arg + " " + a
156         res = java_c_types(new_arg, ret_arr_len)
157         if res is None:
158             assert java_c_types_none_allowed
159             return None
160         if is_ptr:
161             res.pass_by_ref = True
162         if res.is_native_primitive or res.passed_as_ptr:
163             return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
164                 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=res.c_ty + "Array", passed_as_ptr=False, is_ptr=is_ptr, is_const=is_const,
165                 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
166         else:
167             return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
168                 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=consts.ptr_arr, passed_as_ptr=False, is_ptr=is_ptr, is_const=is_const,
169                 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
170
171     is_primitive = False
172     arr_len = None
173     mapped_type = []
174     java_type_plural = None
175     if fn_arg.startswith("void"):
176         java_ty = "void"
177         c_ty = "void"
178         fn_ty_arg = "V"
179         fn_arg = fn_arg[4:].strip()
180         is_primitive = True
181     elif fn_arg.startswith("bool"):
182         java_ty = "boolean"
183         c_ty = "jboolean"
184         fn_ty_arg = "Z"
185         fn_arg = fn_arg[4:].strip()
186         is_primitive = True
187     elif fn_arg.startswith("uint8_t"):
188         mapped_type = consts.c_type_map['byte']
189         java_ty = mapped_type[0]
190         c_ty = "int8_t"
191         fn_ty_arg = "B"
192         fn_arg = fn_arg[7:].strip()
193         is_primitive = True
194     elif fn_arg.startswith("uint16_t"):
195         java_ty = "short"
196         c_ty = "jshort"
197         fn_ty_arg = "S"
198         fn_arg = fn_arg[8:].strip()
199         is_primitive = True
200     elif fn_arg.startswith("uint32_t"):
201         java_ty = "int"
202         c_ty = "int32_t"
203         fn_ty_arg = "I"
204         fn_arg = fn_arg[8:].strip()
205         is_primitive = True
206     elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
207         # TODO: uintptr_t is arch-dependent :(
208         java_ty = "long"
209         c_ty = "int64_t"
210         fn_ty_arg = "J"
211         if fn_arg.startswith("uint64_t"):
212             fn_arg = fn_arg[8:].strip()
213         else:
214             fn_arg = fn_arg[9:].strip()
215         is_primitive = True
216     elif is_const and fn_arg.startswith("char *"):
217         java_ty = "String"
218         c_ty = "const char*"
219         fn_ty_arg = "Ljava/lang/String;"
220         fn_arg = fn_arg[6:].strip()
221     elif fn_arg.startswith("LDKStr"):
222         java_ty = "String"
223         c_ty = "jstring"
224         fn_ty_arg = "Ljava/lang/String;"
225         fn_arg = fn_arg[6:].strip()
226         arr_access = "chars"
227         arr_len = "len"
228     else:
229         ma = var_ty_regex.match(fn_arg)
230         if ma.group(1).strip() in unitary_enums:
231             java_ty = ma.group(1).strip()
232             c_ty = consts.result_c_ty
233             fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
234             fn_arg = ma.group(2).strip()
235             rust_obj = ma.group(1).strip()
236         elif ma.group(1).strip().startswith("LDKC2Tuple"):
237             c_ty = consts.ptr_c_ty
238             java_ty = consts.ptr_native_ty
239             java_hu_ty = "TwoTuple<"
240             if not ma.group(1).strip() in tuple_types:
241                 assert java_c_types_none_allowed
242                 return None
243             for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
244                 if idx != 0:
245                     java_hu_ty = java_hu_ty + ", "
246                 if ty_info.is_native_primitive:
247                     if ty_info.java_hu_ty == "int":
248                         java_hu_ty = java_hu_ty + "Integer" # Java concrete integer type is Integer, not Int
249                     else:
250                         java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
251                 else:
252                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty
253             java_hu_ty = java_hu_ty + ">"
254             fn_ty_arg = "J"
255             fn_arg = ma.group(2).strip()
256             rust_obj = ma.group(1).strip()
257             take_by_ptr = True
258         elif ma.group(1).strip().startswith("LDKC3Tuple"):
259             c_ty = consts.ptr_c_ty
260             java_ty = consts.ptr_native_ty
261             java_hu_ty = "ThreeTuple<"
262             if not ma.group(1).strip() in tuple_types:
263                 assert java_c_types_none_allowed
264                 return None
265             for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
266                 if idx != 0:
267                     java_hu_ty = java_hu_ty + ", "
268                 if ty_info.is_native_primitive:
269                     if ty_info.java_hu_ty == "int":
270                         java_hu_ty = java_hu_ty + "Integer" # Java concrete integer type is Integer, not Int
271                     else:
272                         java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
273                 else:
274                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty
275             java_hu_ty = java_hu_ty + ">"
276             fn_ty_arg = "J"
277             fn_arg = ma.group(2).strip()
278             rust_obj = ma.group(1).strip()
279             take_by_ptr = True
280         else:
281             c_ty = consts.ptr_c_ty
282             java_ty = consts.ptr_native_ty
283             java_hu_ty = ma.group(1).strip().replace("LDKCResult", "Result").replace("LDK", "")
284             fn_ty_arg = "J"
285             fn_arg = ma.group(2).strip()
286             rust_obj = ma.group(1).strip()
287             take_by_ptr = True
288
289     if fn_arg.startswith(" *") or fn_arg.startswith("*"):
290         fn_arg = fn_arg.replace("*", "").strip()
291         is_ptr = True
292         c_ty = consts.ptr_c_ty
293         java_ty = consts.ptr_native_ty
294         fn_ty_arg = "J"
295         is_primitive = False
296
297     var_is_arr = var_is_arr_regex.match(fn_arg)
298     if var_is_arr is not None or ret_arr_len is not None:
299         assert(not take_by_ptr)
300         assert(not is_ptr)
301         # is there a special case for plurals?
302         if len(mapped_type) == 2:
303             java_ty = mapped_type[1]
304         else:
305             java_ty = java_ty + "[]"
306         c_ty = c_ty + "Array"
307         if var_is_arr is not None:
308             if var_is_arr.group(1) == "":
309                 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, is_const=is_const,
310                     passed_as_ptr=False, is_ptr=False, var_name="arg", arr_len=var_is_arr.group(2), arr_access=arr_access, is_native_primitive=False)
311             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, is_const=is_const,
312                 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, is_native_primitive=False)
313
314     if java_hu_ty is None:
315         java_hu_ty = java_ty
316     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,
317         is_const=is_const, is_ptr=is_ptr, var_name=fn_arg, arr_len=arr_len, arr_access=arr_access, is_native_primitive=is_primitive)
318
319 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
320 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
321 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
322 clone_fns = set()
323 constructor_fns = {}
324 c_array_class_caches = set()
325 with open(sys.argv[1]) as in_h:
326     for line in in_h:
327         reg_fn = reg_fn_regex.match(line)
328         if reg_fn is not None:
329             if reg_fn.group(2).endswith("_clone"):
330                 clone_fns.add(reg_fn.group(2))
331             else:
332                 rty = java_c_types(reg_fn.group(1), None)
333                 if rty is not None and rty.rust_obj is not None and reg_fn.group(2) == rty.java_hu_ty + "_new":
334                     constructor_fns[rty.rust_obj] = reg_fn.group(3)
335             continue
336         arr_fn = fn_ret_arr_regex.match(line)
337         if arr_fn is not None:
338             if arr_fn.group(2).endswith("_clone"):
339                 clone_fns.add(arr_fn.group(2))
340             # No object constructors return arrays, as then they wouldn't be an object constructor
341             continue
342
343 # Define some manual clones...
344 clone_fns.add("ThirtyTwoBytes_clone")
345 write_c("static inline struct LDKThirtyTwoBytes ThirtyTwoBytes_clone(const struct LDKThirtyTwoBytes *orig) { struct LDKThirtyTwoBytes ret; memcpy(ret.data, orig->data, 32); return ret; }\n")
346
347 java_c_types_none_allowed = False # C structs created by cbindgen are declared in dependency order
348
349 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java:
350     def map_type(fn_arg, print_void, ret_arr_len, is_free, holds_ref):
351         ty_info = java_c_types(fn_arg, ret_arr_len)
352         return map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref)
353
354     def map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref):
355         if ty_info.c_ty == "void":
356             if not print_void:
357                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
358                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
359                     ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
360         if ty_info.c_ty.endswith("Array"):
361             arr_len = ty_info.arr_len
362             if arr_len is not None:
363                 arr_name = ty_info.var_name
364             else:
365                 arr_name = "ret"
366                 arr_len = ret_arr_len
367             if ty_info.c_ty == "int8_tArray":
368                 (set_pfx, set_sfx) = consts.set_native_arr_contents(arr_name + "_arr", arr_len, ty_info)
369                 ret_conv = ("int8_tArray " + arr_name + "_arr = " + consts.create_native_arr_call(arr_len, ty_info) + ";\n" + set_pfx, "")
370                 arg_conv_cleanup = None
371                 if not arr_len.isdigit():
372                     arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
373                     arg_conv = arg_conv + arr_name + "_ref." + arr_len + " = " +  consts.get_native_arr_len_call[0] + arr_name + consts.get_native_arr_len_call[1] + ";\n"
374                     if (not ty_info.is_ptr or not holds_ref) and ty_info.rust_obj != "LDKu8slice":
375                         arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = MALLOC(" + arr_name + "_ref." + arr_len + ", \"" + ty_info.rust_obj + " Bytes\");\n"
376                         arg_conv = arg_conv + consts.get_native_arr_contents(arr_name, arr_name + "_ref." + ty_info.arr_access, arr_name + "_ref." + arr_len, ty_info, True) + ";"
377                     else:
378                         arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = " + consts.get_native_arr_contents(arr_name, "NO_DEST", arr_name + "_ref." + arr_len, ty_info, False) + ";"
379                         arg_conv_cleanup = consts.cleanup_native_arr_ref_contents(arr_name, arr_name + "_ref." + ty_info.arr_access, arr_name + "_ref." + arr_len, ty_info)
380                     if ty_info.rust_obj == "LDKTransaction":
381                         arg_conv = arg_conv + "\n" + arr_name + "_ref.data_is_owned = " + str(holds_ref).lower() + ";"
382                     ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
383                     ret_conv = (ret_conv[0], ";\nint8_tArray " + arr_name + "_arr = " + consts.create_native_arr_call(arr_name + "_var." + arr_len, ty_info) + ";\n")
384                     (pfx, sfx) = consts.set_native_arr_contents(arr_name + "_arr", arr_name + "_var." + arr_len, ty_info)
385                     ret_conv = (ret_conv[0], ret_conv[1] + pfx + arr_name + "_var." + ty_info.arr_access + sfx + ";")
386                     if not holds_ref and ty_info.rust_obj != "LDKu8slice":
387                         ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
388                 elif ty_info.rust_obj is not None:
389                     arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
390                     arg_conv = arg_conv + "CHECK(" + consts.get_native_arr_len_call[0] + arr_name + consts.get_native_arr_len_call[1] + " == " + arr_len + ");\n"
391                     arg_conv = arg_conv + consts.get_native_arr_contents(arr_name, arr_name + "_ref." + ty_info.arr_access, arr_len, ty_info, True) + ";"
392                     ret_conv = (ret_conv[0], "." + ty_info.arr_access + set_sfx + ";")
393                 else:
394                     arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n"
395                     arg_conv = arg_conv + "CHECK(" + consts.get_native_arr_len_call[0] + arr_name + consts.get_native_arr_len_call[1] + " == " + arr_len + ");\n"
396                     arg_conv = arg_conv + consts.get_native_arr_contents(arr_name, arr_name + "_arr", arr_len, ty_info, True) + ";\n"
397                     arg_conv = arg_conv + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
398                     ret_conv = (ret_conv[0] + "*", set_sfx + ";")
399                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
400                     arg_conv = arg_conv, arg_conv_name = arr_name + "_ref", arg_conv_cleanup = arg_conv_cleanup,
401                     ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
402             else:
403                 assert not arr_len.isdigit() # fixed length arrays not implemented
404                 assert ty_info.java_ty[len(ty_info.java_ty) - 2:] == "[]"
405                 conv_name = "arr_conv_" + str(len(ty_info.java_hu_ty))
406                 idxc = chr(ord('a') + (len(ty_info.java_hu_ty) % 26))
407                 ty_info.subty.var_name = conv_name
408                 #XXX: We'd really prefer to only ever set to False, avoiding lots of clone, but need smarter free logic
409                 #if ty_info.is_ptr or holds_ref:
410                 #    ty_info.subty.requires_clone = False
411                 ty_info.subty.requires_clone = not ty_info.is_ptr or not holds_ref
412                 subty = map_type_with_info(ty_info.subty, False, None, is_free, holds_ref)
413                 if arr_name == "":
414                     arr_name = "arg"
415                 arg_conv = ty_info.rust_obj + " " + arr_name + "_constr;\n"
416                 arg_conv = arg_conv + arr_name + "_constr." + arr_len + " = " + consts.get_native_arr_len_call[0] + arr_name + consts.get_native_arr_len_call[1] + ";\n"
417                 arg_conv = arg_conv + "if (" + arr_name + "_constr." + arr_len + " > 0)\n"
418                 if subty.rust_obj is None:
419                     szof = subty.c_ty
420                 else:
421                     szof = subty.rust_obj
422                 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = MALLOC(" + arr_name + "_constr." + arr_len + " * sizeof(" + szof + "), \"" + ty_info.rust_obj + " Elements\");\n"
423                 arg_conv = arg_conv + "else\n"
424                 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = NULL;\n"
425                 get_arr = consts.get_native_arr_contents(arr_name, "NO_DEST", arr_name + "_constr." + arr_len, ty_info, False)
426                 if get_arr != None:
427                     arg_conv = arg_conv + subty.c_ty + "* " + arr_name + "_vals = " + get_arr + ";\n"
428                 arg_conv = arg_conv + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_constr." + arr_len + "; " + idxc + "++) {\n"
429                 if get_arr != None:
430                     arg_conv = arg_conv + "\t" + subty.c_ty + " " + conv_name + " = " + arr_name + "_vals[" + idxc + "];"
431                     if subty.arg_conv is not None:
432                         arg_conv = arg_conv + "\n\t" + subty.arg_conv.replace("\n", "\n\t")
433                 else:
434                     arg_conv = arg_conv + "\t" + subty.c_ty + " " + conv_name + " = " + consts.get_native_arr_elem(arr_name, idxc, ty_info) + ";\n"
435                     arg_conv = arg_conv + "\t" + subty.arg_conv.replace("\n", "\n\t")
436                 arg_conv = arg_conv + "\n\t" + arr_name + "_constr." + ty_info.arr_access + "[" + idxc + "] = " + subty.arg_conv_name + ";\n}"
437                 if get_arr != None:
438                     cleanup = consts.cleanup_native_arr_ref_contents(arr_name, arr_name + "_vals", arr_name + "_constr." + arr_len, ty_info)
439                     if cleanup is not None:
440                         arg_conv = arg_conv + "\n" + cleanup + ";"
441                 if ty_info.is_ptr:
442                     arg_conv_name = "&" + arr_name + "_constr"
443                 else:
444                     arg_conv_name = arr_name + "_constr"
445                 arg_conv_cleanup = None
446                 if ty_info.is_ptr:
447                     arg_conv_cleanup = "FREE(" + arr_name + "_constr." + ty_info.arr_access + ");"
448
449                 if arr_name == "arg":
450                     arr_name = "ret"
451                 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
452                 if subty.ret_conv is None:
453                     ret_conv = ("DUMMY", "DUMMY")
454                 elif not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
455                     ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = " + consts.create_native_arr_call(arr_name + "_var." + arr_len, ty_info) + ";\n")
456                     ret_conv = (ret_conv[0], ret_conv[1] + subty.c_ty + " *" + arr_name + "_arr_ptr = " + consts.get_native_arr_ptr_call[0] + arr_name + "_arr" + consts.get_native_arr_ptr_call[1] + ";\n")
457                     ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
458                     ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
459                     ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
460                     ret_conv = (ret_conv[0], ret_conv[1] + "\n\t" + arr_name + "_arr_ptr[" + idxc + "] = " + subty.ret_conv_name + ";\n}")
461                     cleanup = consts.release_native_arr_ptr_call(arr_name + "_arr", arr_name + "_arr_ptr")
462                     if cleanup is not None:
463                         ret_conv = (ret_conv[0], ret_conv[1] + "\n" + cleanup + ";")
464                 else:
465                     assert ty_info.java_fn_ty_arg.startswith("[")
466                     clz_var = ty_info.java_fn_ty_arg[1:].replace("[", "arr_of_")
467                     c_array_class_caches.add(clz_var)
468                     ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = (*env)->NewObjectArray(env, " + arr_name + "_var." + arr_len + ", " + clz_var + "_clz, NULL);\n")
469                     ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
470                     ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
471                     ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
472                     ret_conv = (ret_conv[0], ret_conv[1] + "\n\t(*env)->SetObjectArrayElement(env, " + arr_name + "_arr, " + idxc + ", " + subty.ret_conv_name + ");\n")
473                     ret_conv = (ret_conv[0], ret_conv[1] + "}")
474                 if not holds_ref:
475                     # XXX: The commented if's are a bit smarter freeing, but we need to be a nudge smarter still
476                     # Note that we don't drop the full vec here - we're passing ownership to java (or have cloned) or free'd by now!
477                     ret_conv = (ret_conv[0], ret_conv[1] + "\nFREE(" + arr_name + "_var." + ty_info.arr_access + ");")
478                     #if subty.rust_obj is not None and subty.rust_obj in opaque_structs:
479                     #    ret_conv = (ret_conv[0], ret_conv[1] + "\nFREE(" + arr_name + "_var." + ty_info.arr_access + ");")
480                     #else:
481                     #    ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
482
483                 to_hu_conv = None
484                 to_hu_conv_name = None
485                 if subty.to_hu_conv is not None:
486                     to_hu_conv = ty_info.java_hu_ty + " " + conv_name + "_arr = new " + ty_info.subty.java_hu_ty.split("<")[0] + "[" + arr_name + ".length];\n"
487                     to_hu_conv = to_hu_conv + "for (int " + idxc + " = 0; " + idxc + " < " + arr_name + ".length; " + idxc + "++) {\n"
488                     to_hu_conv = to_hu_conv + "\t" + subty.java_ty + " " + conv_name + " = " + arr_name + "[" + idxc + "];\n"
489                     to_hu_conv = to_hu_conv + "\t" + subty.to_hu_conv.replace("\n", "\n\t") + "\n"
490                     to_hu_conv = to_hu_conv + "\t" + conv_name + "_arr[" + idxc + "] = " + subty.to_hu_conv_name + ";\n}"
491                     to_hu_conv_name = conv_name + "_arr"
492                 from_hu_conv = None
493                 if subty.from_hu_conv is not None:
494                     if subty.java_ty == "long" and subty.java_hu_ty != "long":
495                         from_hu_conv = ("Arrays.stream(" + arr_name + ").mapToLong(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + "  */")
496                     elif subty.java_ty == "long":
497                         from_hu_conv = ("Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + "  */")
498                     else:
499                         from_hu_conv = ("(" + ty_info.java_ty + ")Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + "  */")
500
501                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
502                     arg_conv = arg_conv, arg_conv_name = arg_conv_name, arg_conv_cleanup = arg_conv_cleanup,
503                     ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = to_hu_conv, to_hu_conv_name = to_hu_conv_name, from_hu_conv = from_hu_conv)
504         elif ty_info.java_ty == "String":
505             if ty_info.arr_access is None:
506                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
507                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
508                     ret_conv = ("jstring " + ty_info.var_name + "_conv = (*env)->NewStringUTF(env, ", ");"), ret_conv_name = ty_info.var_name + "_conv",
509                     to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
510             else:
511                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
512                     arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
513                     ret_conv = ("LDKStr " + ty_info.var_name + "_str = ",
514                         ";\nchar* " + ty_info.var_name + "_buf = MALLOC(" + ty_info.var_name + "_str." + ty_info.arr_len + " + 1, \"str conv buf\");\n" +
515                         "memcpy(" + ty_info.var_name + "_buf, " + ty_info.var_name + "_str." + ty_info.arr_access + ", " + ty_info.var_name + "_str." + ty_info.arr_len + ");\n" +
516                         ty_info.var_name + "_buf[" + ty_info.var_name + "_str." + ty_info.arr_len + "] = 0;\n" +
517                         "jstring " + ty_info.var_name + "_conv = (*env)->NewStringUTF(env, " + ty_info.var_name + "_str." + ty_info.arr_access + ");\n" +
518                         "FREE(" + ty_info.var_name + "_buf);"),
519                     ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
520         elif ty_info.var_name == "" and not print_void:
521             # We don't have a parameter name, and want one, just call it arg
522             if ty_info.rust_obj is not None:
523                 assert(not is_free or ty_info.rust_obj not in opaque_structs)
524                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
525                     arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
526                     arg_conv_name = "arg_conv", arg_conv_cleanup = None,
527                     ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 7", to_hu_conv_name = None, from_hu_conv = None)
528             else:
529                 assert(not is_free)
530                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
531                     arg_conv = None, arg_conv_name = "arg", arg_conv_cleanup = None,
532                     ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 8", to_hu_conv_name = None, from_hu_conv = None)
533         elif ty_info.rust_obj is None:
534             return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
535                 arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None,
536                 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
537         else:
538             if ty_info.var_name == "":
539                 ty_info.var_name = "ret"
540
541             if ty_info.rust_obj in opaque_structs:
542                 opaque_arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv;\n"
543                 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
544                 if ty_info.is_ptr and holds_ref:
545                     opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = false;"
546                 else:
547                     opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
548                 if not is_free and (not ty_info.is_ptr or not holds_ref or ty_info.requires_clone == True) and ty_info.requires_clone != False:
549                     if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
550                         # 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.
551                         opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
552                         opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&" + ty_info.var_name + "_conv);"
553                     elif ty_info.passed_as_ptr:
554                         opaque_arg_conv = opaque_arg_conv + "\n// Warning: we may need a move here but can't clone!"
555
556                 opaque_ret_conv_suf = ";\n"
557                 if not holds_ref and ty_info.is_ptr and (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns: # is_ptr, not holds_ref implies passing a pointed-to value to java, which needs copied
558                     opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "->inner != NULL)\n"
559                     opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_var = " + ty_info.rust_obj.replace("LDK", "") + "_clone(" + ty_info.var_name + ");\n"
560                 elif not holds_ref and ty_info.is_ptr:
561                     opaque_ret_conv_suf = opaque_ret_conv_suf + "// Warning: we may need a move here but can't clone!\n"
562
563                 opaque_ret_conv_suf = opaque_ret_conv_suf + "CHECK((((long)" + ty_info.var_name + "_var.inner) & 1) == 0); // We rely on a free low bit, malloc guarantees this.\n"
564                 opaque_ret_conv_suf = opaque_ret_conv_suf + "CHECK((((long)&" + ty_info.var_name + "_var) & 1) == 0); // We rely on a free low bit, pointer alignment guarantees this.\n"
565                 if holds_ref:
566                     opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner & ~1;"
567                 else:
568                     opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner;\n"
569                     opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "_var.is_owned) {\n"
570                     opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_ref |= 1;\n"
571                     opaque_ret_conv_suf = opaque_ret_conv_suf + "}"
572
573                 if ty_info.is_ptr:
574                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
575                         arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv", arg_conv_cleanup = None,
576                         ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = *", opaque_ret_conv_suf),
577                         ret_conv_name = ty_info.var_name + "_ref",
578                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
579                         to_hu_conv_name = ty_info.var_name + "_hu_conv",
580                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
581                 else:
582                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
583                         arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
584                         ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", opaque_ret_conv_suf),
585                         ret_conv_name = ty_info.var_name + "_ref",
586                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
587                         to_hu_conv_name = ty_info.var_name + "_hu_conv",
588                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
589
590             if not ty_info.is_ptr:
591                 if ty_info.rust_obj in unitary_enums:
592                     (ret_pfx, ret_sfx) = consts.c_unitary_enum_to_native_call(ty_info)
593                     (arg_pfx, arg_sfx) = consts.native_unitary_enum_to_c_call(ty_info)
594                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
595                         arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + arg_pfx + ty_info.var_name + arg_sfx + ";",
596                         arg_conv_name = ty_info.var_name + "_conv",
597                         arg_conv_cleanup = None,
598                         ret_conv = (ty_info.c_ty + " " + ty_info.var_name + "_conv = " + ret_pfx, ret_sfx + ";"),
599                         ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
600                 base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";"
601                 if ty_info.rust_obj in trait_structs:
602                     if not is_free:
603                         needs_full_clone = not is_free and (not ty_info.is_ptr and not holds_ref or ty_info.requires_clone == True) and ty_info.requires_clone != False
604                         if needs_full_clone and (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
605                             base_conv = base_conv + "\n" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(" + ty_info.var_name + ");"
606                         else:
607                             base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
608                             base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
609                             base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
610                             if needs_full_clone:
611                                 base_conv = base_conv + "// Warning: we may need a move here but can't do a full clone!\n"
612
613                     else:
614                         base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
615                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
616                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
617                         ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
618                         ret_conv_name = "(long)ret",
619                         to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");\nret_hu_conv.ptrs_to.add(this);",
620                         to_hu_conv_name = "ret_hu_conv",
621                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
622                 if ty_info.rust_obj != "LDKu8slice":
623                     # Don't bother free'ing slices passed in - Rust doesn't auto-free the
624                     # underlying unlike Vecs, and it gives Java more freedom.
625                     base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
626                 if ty_info.rust_obj in complex_enums:
627                     ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";")
628                     if not holds_ref:
629                         ret_conv = (ty_info.rust_obj + " *" + ty_info.var_name + "_copy = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n", "")
630                         if ty_info.requires_clone == True: # Set in object array mapping
631                             if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
632                                 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&", ");\n")
633                             else:
634                                 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", "; // XXX: We likely need to clone here, but no _clone fn is available!\n")
635                         else:
636                             ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", ";\n")
637                         ret_conv = (ret_conv[0], ret_conv[1] + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_copy;")
638                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
639                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
640                         ret_conv = ret_conv, ret_conv_name = ty_info.var_name + "_ref",
641                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");\n" + ty_info.var_name + "_hu_conv.ptrs_to.add(this);",
642                         to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
643                 if ty_info.rust_obj in result_types:
644                     if holds_ref:
645                         # If we're trying to return a ref, we have to clone.
646                         # We just blindly assume its implemented and let the compiler fail if its not.
647                         ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_conv = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_conv = ", ";")
648                         ret_conv = (ret_conv[0], ret_conv[1] + "\n*" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(" + ty_info.var_name + "_conv);")
649                     else:
650                         ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_conv = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_conv = ", ";")
651                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
652                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
653                         ret_conv = ret_conv, ret_conv_name = "(long)" + ty_info.var_name + "_conv",
654                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");",
655                         to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + " != null ? " + ty_info.var_name + ".ptr : 0", ""))
656                 if ty_info.rust_obj in tuple_types:
657                     from_hu_conv = "bindings." + tuple_types[ty_info.rust_obj][1].replace("LDK", "") + "_new("
658                     to_hu_conv_pfx = ""
659                     to_hu_conv_sfx = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " + ty_info.java_hu_ty + "("
660                     clone_ret_str = ""
661                     for idx, conv in enumerate(tuple_types[ty_info.rust_obj][0]):
662                         if idx != 0:
663                             to_hu_conv_sfx = to_hu_conv_sfx + ", "
664                             from_hu_conv = from_hu_conv + ", "
665                         conv.var_name = ty_info.var_name + "_" + chr(idx + ord("a"))
666                         conv_map = map_type_with_info(conv, False, None, is_free, holds_ref)
667                         to_hu_conv_pfx = to_hu_conv_pfx + conv.java_ty + " " + ty_info.var_name + "_" + chr(idx + ord("a")) + " = " + "bindings." + tuple_types[ty_info.rust_obj][1] + "_get_" + chr(idx + ord("a")) + "(" + ty_info.var_name + ");\n"
668                         if conv_map.to_hu_conv is not None:
669                             to_hu_conv_pfx = to_hu_conv_pfx + conv_map.to_hu_conv + ";\n"
670                             to_hu_conv_sfx = to_hu_conv_sfx + conv_map.to_hu_conv_name
671                         else:
672                             to_hu_conv_sfx = to_hu_conv_sfx + ty_info.var_name + "_" + chr(idx + ord("a"))
673                         if conv_map.from_hu_conv is not None:
674                             from_hu_conv = from_hu_conv + conv_map.from_hu_conv[0].replace(ty_info.var_name + "_" + chr(idx + ord("a")), ty_info.var_name + "." + chr(idx + ord("a")))
675                             if conv_map.from_hu_conv[1] != "":
676                                 from_hu_conv = from_hu_conv + "/*XXX: " + conv_map.from_hu_conv[1] + "*/"
677                         else:
678                             from_hu_conv = from_hu_conv + ty_info.var_name + "." + chr(idx + ord("a"))
679
680                         if conv.is_native_primitive:
681                             pass
682                         elif (conv_map.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
683                             accessor = ty_info.var_name + "_ref->" + chr(idx + ord("a"))
684                             clone_ret_str = clone_ret_str + "\n" + accessor + " = " + conv_map.rust_obj.replace("LDK", "") + "_clone(&" + accessor + ");"
685                         else:
686                             clone_ret_str = clone_ret_str + "\n// XXX: We likely need to clone here, but no _clone fn is available for " + conv_map.java_hu_ty
687                     if not ty_info.is_ptr and not holds_ref:
688                         ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_ref = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_ref = ", ";")
689                         if not is_free and (not ty_info.is_ptr and not holds_ref or ty_info.requires_clone == True) and ty_info.requires_clone != False:
690                             ret_conv = (ret_conv[0], ret_conv[1] + clone_ret_str)
691                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
692                             arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
693                             ret_conv = ret_conv,
694                             ret_conv_name = "(long)" + ty_info.var_name + "_ref",
695                             to_hu_conv = to_hu_conv_pfx + to_hu_conv_sfx + ");", to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (from_hu_conv + ")", ""))
696                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
697                         arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
698                         ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
699                         to_hu_conv = to_hu_conv_pfx + to_hu_conv_sfx + ");", to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (from_hu_conv + ")", ""))
700
701                 # The manually-defined types - TxOut and Transaction
702                 assert ty_info.rust_obj == "LDKTxOut"
703                 if not ty_info.is_ptr and not holds_ref:
704                     ret_conv = ("LDKTxOut* " + ty_info.var_name + "_ref = MALLOC(sizeof(LDKTxOut), \"LDKTxOut\");\n*" + ty_info.var_name + "_ref = ", ";")
705                 else:
706                     ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";")
707                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
708                     arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
709                     ret_conv = ret_conv, ret_conv_name = "(long)" + ty_info.var_name + "_ref",
710                     to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " +ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
711                     to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
712             elif ty_info.is_ptr:
713                 assert(not is_free)
714                 if ty_info.rust_obj in complex_enums:
715                     return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
716                         arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
717                         arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
718                         ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
719                         to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");",
720                         to_hu_conv_name = ty_info.var_name + "_hu_conv",
721                         from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
722                 elif ty_info.rust_obj in trait_structs:
723                     if ty_info.rust_obj.replace("LDK", "") + "_clone" in clone_fns:
724                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
725                             arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
726                             arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
727                             ret_conv = (ty_info.rust_obj + " *" + ty_info.var_name + "_clone = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n" +
728                                 "*" + ty_info.var_name + "_clone = " + ty_info.rust_obj.replace("LDK", "") + "_clone(", ");"),
729                             ret_conv_name = "(long)" + ty_info.var_name + "_clone",
730                             to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");\nret_hu_conv.ptrs_to.add(this);",
731                             to_hu_conv_name = "ret_hu_conv",
732                             from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
733                     else:
734                         return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
735                             arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
736                             arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
737                             ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
738                             to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");\nret_hu_conv.ptrs_to.add(this);",
739                             to_hu_conv_name = "ret_hu_conv",
740                             from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
741                 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
742                     arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
743                     arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
744                     ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
745                     to_hu_conv = "TODO 3", to_hu_conv_name = None, from_hu_conv = None) # its a pointer, no conv needed
746             assert False # We should have handled every case by now.
747
748     def map_fn(line, re_match, ret_arr_len, c_call_string):
749         out_java.write("\t// " + line)
750         out_java.write("\tpublic static native ")
751         write_c(consts.c_fn_ty_pfx)
752
753         is_free = re_match.group(2).endswith("_free")
754         struct_meth = re_match.group(2).split("_")[0]
755
756         ret_info = map_type(re_match.group(1), True, ret_arr_len, False, False)
757         write_c(ret_info.c_ty)
758         out_java.write(ret_info.java_ty)
759
760         if ret_info.ret_conv is not None:
761             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
762
763         out_java.write(" " + re_match.group(2) + "(")
764         write_c(" " + consts.c_fn_name_pfx + re_match.group(2).replace('_', '_1') + "(" + consts.c_fn_args_pfx)
765
766         arg_names = []
767         default_constructor_args = {}
768         takes_self = False
769         args_known = True
770         for idx, arg in enumerate(re_match.group(3).split(',')):
771             if idx != 0:
772                 out_java.write(", ")
773             if arg != "void":
774                 write_c(", ")
775             arg_conv_info = map_type(arg, False, None, is_free, True)
776             if arg_conv_info.c_ty != "void":
777                 write_c(arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
778                 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
779             if idx == 0 and arg_conv_info.java_hu_ty == struct_meth:
780                 takes_self = True
781             if arg_conv_info.arg_conv is not None and "Warning" in arg_conv_info.arg_conv:
782                 if arg_conv_info.rust_obj in constructor_fns:
783                     assert not is_free
784                     for explode_arg in constructor_fns[arg_conv_info.rust_obj].split(','):
785                         explode_arg_conv = map_type(explode_arg, False, None, False, True)
786                         if explode_arg_conv.c_ty == "void":
787                             # We actually want to handle this case, but for now its only used in NetGraphMsgHandler::new()
788                             # which ends up resulting in a redundant constructor - both without arguments for the NetworkGraph.
789                             args_known = False
790                             pass
791                         if not arg_conv_info.arg_name in default_constructor_args:
792                             default_constructor_args[arg_conv_info.arg_name] = []
793                         default_constructor_args[arg_conv_info.arg_name].append(explode_arg_conv)
794             arg_names.append(arg_conv_info)
795
796         out_java_struct = None
797         if ("LDK" + struct_meth in opaque_structs or "LDK" + struct_meth in trait_structs) and not is_free:
798             out_java_struct = open(f"{sys.argv[3]}/structs/{struct_meth}{consts.file_ext}", "a")
799             if not args_known:
800                 out_java_struct.write("\t// Skipped " + re_match.group(2) + "\n")
801                 out_java_struct.close()
802                 out_java_struct = None
803             else:
804                 meth_n = re_match.group(2)[len(struct_meth) + 1:]
805                 if not takes_self:
806                     out_java_struct.write("\tpublic static " + ret_info.java_hu_ty + " constructor_" + meth_n + "(")
807                 else:
808                     out_java_struct.write("\tpublic " + ret_info.java_hu_ty + " " + meth_n + "(")
809                 for idx, arg in enumerate(arg_names):
810                     if idx != 0:
811                         if not takes_self or idx > 1:
812                             out_java_struct.write(", ")
813                     elif takes_self:
814                         continue
815                     if arg.java_ty != "void":
816                         if arg.arg_name in default_constructor_args:
817                             for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
818                                 if explode_idx != 0:
819                                     out_java_struct.write(", ")
820                                 out_java_struct.write(explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
821                         else:
822                             out_java_struct.write(arg.java_hu_ty + " " + arg.arg_name)
823
824
825         out_java.write(");\n")
826         write_c(") {\n")
827         if out_java_struct is not None:
828             out_java_struct.write(") {\n")
829
830         for info in arg_names:
831             if info.arg_conv is not None:
832                 write_c("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
833
834         if ret_info.ret_conv is not None:
835             write_c("\t" + ret_conv_pfx.replace('\n', '\n\t'))
836         elif ret_info.c_ty != "void":
837             write_c("\t" + ret_info.c_ty + " ret_val = ")
838         else:
839             write_c("\t")
840
841         if c_call_string is None:
842             write_c(re_match.group(2) + "(")
843         else:
844             write_c(c_call_string)
845         for idx, info in enumerate(arg_names):
846             if info.arg_conv_name is not None:
847                 if idx != 0:
848                     write_c(", ")
849                 elif c_call_string is not None:
850                     continue
851                 write_c(info.arg_conv_name)
852         write_c(")")
853         if ret_info.ret_conv is not None:
854             write_c(ret_conv_sfx.replace('\n', '\n\t'))
855         else:
856             write_c(";")
857         for info in arg_names:
858             if info.arg_conv_cleanup is not None:
859                 write_c("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
860         if ret_info.ret_conv is not None:
861             write_c("\n\treturn " + ret_info.ret_conv_name + ";")
862         elif ret_info.c_ty != "void":
863             write_c("\n\treturn ret_val;")
864         write_c("\n}\n\n")
865         if out_java_struct is not None:
866             out_java_struct.write("\t\t")
867             if ret_info.java_ty != "void":
868                 out_java_struct.write(ret_info.java_ty + " ret = ")
869             out_java_struct.write("bindings." + re_match.group(2) + "(")
870             for idx, info in enumerate(arg_names):
871                 if idx != 0:
872                     out_java_struct.write(", ")
873                 if idx == 0 and takes_self:
874                     out_java_struct.write("this.ptr")
875                 elif info.arg_name in default_constructor_args:
876                     out_java_struct.write("bindings." + info.java_hu_ty + "_new(")
877                     for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
878                         if explode_idx != 0:
879                             out_java_struct.write(", ")
880                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
881                         if explode_arg.from_hu_conv is not None:
882                             out_java_struct.write(explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
883                         else:
884                             out_java_struct.write(expl_arg_name)
885                     out_java_struct.write(")")
886                 elif info.from_hu_conv is not None:
887                     out_java_struct.write(info.from_hu_conv[0])
888                 else:
889                     out_java_struct.write(info.arg_name)
890             out_java_struct.write(");\n")
891             if ret_info.to_hu_conv is not None:
892                 if not takes_self:
893                     out_java_struct.write("\t\t" + ret_info.to_hu_conv.replace("\n", "\n\t\t").replace("this", ret_info.to_hu_conv_name) + "\n")
894                 else:
895                     out_java_struct.write("\t\t" + ret_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
896
897             for idx, info in enumerate(arg_names):
898                 if idx == 0 and takes_self:
899                     pass
900                 elif info.arg_name in default_constructor_args:
901                     for explode_arg in default_constructor_args[info.arg_name]:
902                         expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
903                         if explode_arg.from_hu_conv is not None and ret_info.to_hu_conv_name:
904                             out_java_struct.write("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name, expl_arg_name).replace("this", ret_info.to_hu_conv_name) + ";\n")
905                 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
906                     if not takes_self and ret_info.to_hu_conv_name is not None:
907                         out_java_struct.write("\t\t" + info.from_hu_conv[1].replace("this", ret_info.to_hu_conv_name) + ";\n")
908                     else:
909                         out_java_struct.write("\t\t" + info.from_hu_conv[1] + ";\n")
910
911             if ret_info.to_hu_conv_name is not None:
912                 out_java_struct.write("\t\treturn " + ret_info.to_hu_conv_name + ";\n")
913             elif ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
914                 out_java_struct.write("\t\treturn ret;\n")
915             out_java_struct.write("\t}\n\n")
916             out_java_struct.close()
917
918     def map_unitary_enum(struct_name, field_lines):
919         with open(f"{sys.argv[3]}/enums/{struct_name}{consts.file_ext}", "w") as out_java_enum:
920             unitary_enums.add(struct_name)
921             for idx, struct_line in enumerate(field_lines):
922                 if idx == 0:
923                     assert(struct_line == "typedef enum %s {" % struct_name)
924                 elif idx == len(field_lines) - 3:
925                     assert(struct_line.endswith("_Sentinel,"))
926                 elif idx == len(field_lines) - 2:
927                     assert(struct_line == "} %s;" % struct_name)
928                 elif idx == len(field_lines) - 1:
929                     assert(struct_line == "")
930             (c_out, native_file_out, native_out) = consts.native_c_unitary_enum_map(struct_name, [x.strip().strip(",") for x in field_lines[1:-3]])
931             write_c(c_out)
932             out_java_enum.write(native_file_out)
933             out_java.write(native_out)
934
935     def map_complex_enum(struct_name, union_enum_items):
936         java_hu_type = struct_name.replace("LDK", "")
937         complex_enums.add(struct_name)
938
939         enum_variants = []
940         tag_field_lines = union_enum_items["field_lines"]
941         for idx, struct_line in enumerate(tag_field_lines):
942             if idx == 0:
943                 assert(struct_line == "typedef enum %s_Tag {" % struct_name)
944             elif idx == len(tag_field_lines) - 3:
945                 assert(struct_line.endswith("_Sentinel,"))
946             elif idx == len(tag_field_lines) - 2:
947                 assert(struct_line == "} %s_Tag;" % struct_name)
948             elif idx == len(tag_field_lines) - 1:
949                 assert(struct_line == "")
950             else:
951                 variant_name = struct_line.strip(' ,')[len(struct_name) + 1:]
952                 fields = []
953                 if "LDK" + variant_name in union_enum_items:
954                     enum_var_lines = union_enum_items["LDK" + variant_name]
955                     for idx, field in enumerate(enum_var_lines):
956                         if idx != 0 and idx < len(enum_var_lines) - 2:
957                             fields.append(map_type(field.strip(' ;'), False, None, False, True))
958                         else:
959                             # TODO: Assert line format
960                             pass
961                 else:
962                     # TODO: Assert line format
963                     pass
964                 enum_variants.append(ComplexEnumVariantInfo(variant_name, fields))
965
966         with open(f"{sys.argv[3]}/structs/{java_hu_type}{consts.file_ext}", "w") as out_java_enum:
967             (out_java_addendum, out_java_enum_addendum, out_c_addendum) = consts.map_complex_enum(struct_name, enum_variants, camel_to_snake)
968
969             out_java_enum.write(out_java_enum_addendum)
970             out_java.write(out_java_addendum)
971             write_c(out_c_addendum)
972
973     def map_trait(struct_name, field_var_lines, trait_fn_lines):
974         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "w") as out_java_trait:
975             field_var_convs = []
976             for var_line in field_var_lines:
977                 if var_line.group(1) in trait_structs:
978                     field_var_convs.append((var_line.group(1), var_line.group(2)))
979                 else:
980                     field_var_convs.append(map_type(var_line.group(1) + " " + var_line.group(2), False, None, False, False))
981
982             field_fns = []
983             for fn_line in trait_fn_lines:
984                 ret_ty_info = map_type(fn_line.group(2), True, None, False, False)
985                 is_const = fn_line.group(4) is not None
986
987                 arg_tys = []
988                 for idx, arg in enumerate(fn_line.group(5).split(',')):
989                     if arg == "":
990                         continue
991                     arg_conv_info = map_type(arg, True, None, False, False)
992                     arg_tys.append(arg_conv_info)
993                 field_fns.append(TraitMethInfo(fn_line.group(3), is_const, ret_ty_info, arg_tys))
994
995             (out_java_addendum, out_java_trait_addendum, out_c_addendum) = consts.native_c_map_trait(struct_name, field_var_convs, field_fns)
996             write_c(out_c_addendum)
997             out_java_trait.write(out_java_trait_addendum)
998             out_java.write(out_java_addendum)
999
1000         for fn_line in trait_fn_lines:
1001             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
1002             is_log = fn_line.group(3) == "log" and struct_name == "LDKLogger"
1003             if fn_line.group(3) != "free" and fn_line.group(3) != "clone" and fn_line.group(3) != "eq" and not is_log:
1004                 dummy_line = fn_line.group(2) + struct_name.replace("LDK", "") + "_" + fn_line.group(3) + " " + struct_name + "* this_arg" + fn_line.group(5) + "\n"
1005                 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(3) + ")(this_arg_conv->this_arg")
1006         for idx, var_line in enumerate(field_var_lines):
1007             if var_line.group(1) not in trait_structs:
1008                 write_c(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
1009                 write_c("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
1010                 write_c("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
1011                 write_c("\treturn this_arg->" + var_line.group(2) + ";\n")
1012                 write_c("}\n")
1013                 dummy_line = var_line.group(1) + " " + struct_name.replace("LDK", "") + "_get_" + var_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(5) + "\n"
1014                 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, struct_name + "_set_get_" + var_line.group(2) + "(this_arg_conv")
1015
1016     def map_result(struct_name, res_ty, err_ty):
1017         result_types.add(struct_name)
1018         human_ty = struct_name.replace("LDKCResult", "Result")
1019         with open(f"{sys.argv[3]}/structs/{human_ty}{consts.file_ext}", "w") as out_java_struct:
1020             out_java_struct.write(consts.hu_struct_file_prefix)
1021             out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
1022             out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
1023             out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1024             out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
1025             out_java_struct.write("\t}\n\n")
1026             out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
1027             out_java_struct.write("\t\tif (bindings." + struct_name + "_result_ok(ptr)) {\n")
1028             out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
1029             out_java_struct.write("\t\t} else {\n")
1030             out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
1031             out_java_struct.write("\t\t}\n")
1032             out_java_struct.write("\t}\n")
1033
1034             res_map = map_type(res_ty + " res", True, None, False, True)
1035             err_map = map_type(err_ty + " err", True, None, False, True)
1036             can_clone = True
1037             if not res_map.is_native_primitive and (res_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
1038                 can_clone = False
1039             if not err_map.is_native_primitive and (err_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
1040                 can_clone = False
1041
1042             out_java.write("\tpublic static native boolean " + struct_name + "_result_ok(long arg);\n")
1043             write_c(consts.c_fn_ty_pfx + "jboolean " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1result_1ok (" + consts.c_fn_args_pfx + ", " + consts.ptr_c_ty + " arg) {\n")
1044             write_c("\treturn ((" + struct_name + "*)arg)->result_ok;\n")
1045             write_c("}\n")
1046
1047             out_java.write("\tpublic static native " + res_map.java_ty + " " + struct_name + "_get_ok(long arg);\n")
1048             write_c(consts.c_fn_ty_pfx + res_map.c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1ok (" + consts.c_fn_args_pfx + ", " + consts.ptr_c_ty + " arg) {\n")
1049             write_c("\t" + struct_name + " *val = (" + struct_name + "*)arg;\n")
1050             write_c("\tCHECK(val->result_ok);\n\t")
1051             out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
1052             if res_map.ret_conv is not None:
1053                 write_c(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
1054                 write_c(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
1055             else:
1056                 write_c("return *val->contents.result")
1057             write_c(";\n}\n")
1058
1059             if res_map.java_hu_ty != "void":
1060                 out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
1061             out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
1062             out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1063             if res_map.java_hu_ty == "void":
1064                 pass
1065             elif res_map.to_hu_conv is not None:
1066                 out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + struct_name + "_get_ok(ptr);\n")
1067                 out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1068                 out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
1069             else:
1070                 out_java_struct.write("\t\t\tthis.res = bindings." + struct_name + "_get_ok(ptr);\n")
1071             out_java_struct.write("\t\t}\n")
1072             if struct_name.startswith("LDKCResult_None"):
1073                 out_java_struct.write("\t\tpublic " + human_ty + "_OK() {\n\t\t\tthis(null, bindings.C" + human_ty + "_ok());\n")
1074             else:
1075                 out_java_struct.write("\t\tpublic " + human_ty + "_OK(" + res_map.java_hu_ty + " res) {\n")
1076                 if res_map.from_hu_conv is not None:
1077                     out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(" + res_map.from_hu_conv[0] + "));\n")
1078                     if res_map.from_hu_conv[1] != "":
1079                         out_java_struct.write("\t\t\t" + res_map.from_hu_conv[1] + ";\n")
1080                 else:
1081                     out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(res));\n")
1082             out_java_struct.write("\t\t}\n\t}\n\n")
1083
1084             out_java.write("\tpublic static native " + err_map.java_ty + " " + struct_name + "_get_err(long arg);\n")
1085             write_c(consts.c_fn_ty_pfx + err_map.c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1err (" + consts.c_fn_args_pfx + ", " + consts.ptr_c_ty + " arg) {\n")
1086             write_c("\t" + struct_name + " *val = (" + struct_name + "*)arg;\n")
1087             write_c("\tCHECK(!val->result_ok);\n\t")
1088             out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
1089             if err_map.ret_conv is not None:
1090                 write_c(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
1091                 write_c(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
1092             else:
1093                 write_c("return *val->contents.err")
1094             write_c(";\n}\n")
1095
1096             if err_map.java_hu_ty != "void":
1097                 out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
1098             out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
1099             out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1100             if err_map.java_hu_ty == "void":
1101                 pass
1102             elif err_map.to_hu_conv is not None:
1103                 out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + struct_name + "_get_err(ptr);\n")
1104                 out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1105                 out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
1106             else:
1107                 out_java_struct.write("\t\t\tthis.err = bindings." + struct_name + "_get_err(ptr);\n")
1108             out_java_struct.write("\t\t}\n")
1109
1110             if struct_name.endswith("NoneZ"):
1111                 out_java_struct.write("\t\tpublic " + human_ty + "_Err() {\n\t\t\tthis(null, bindings.C" + human_ty + "_err());\n")
1112             else:
1113                 out_java_struct.write("\t\tpublic " + human_ty + "_Err(" + err_map.java_hu_ty + " err) {\n")
1114                 if err_map.from_hu_conv is not None:
1115                     out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(" + err_map.from_hu_conv[0] + "));\n")
1116                     if err_map.from_hu_conv[1] != "":
1117                         out_java_struct.write("\t\t\t" + err_map.from_hu_conv[1] + ";\n")
1118                 else:
1119                     out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(err));\n")
1120             out_java_struct.write("\t\t}\n\t}\n}\n")
1121
1122             if can_clone:
1123                 clone_fns.add(struct_name.replace("LDK", "") + "_clone")
1124                 write_c("static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n")
1125                 write_c("\t" + struct_name + " res = { .result_ok = orig->result_ok };\n")
1126                 write_c("\tif (orig->result_ok) {\n")
1127                 if res_map.c_ty == "void":
1128                     write_c("\t\tres.contents.result = NULL;\n")
1129                 else:
1130                     if res_map.is_native_primitive:
1131                         write_c("\t\t" + res_map.c_ty + "* contents = MALLOC(sizeof(" + res_map.c_ty + "), \"" + res_map.c_ty + " result OK clone\");\n")
1132                         write_c("\t\t*contents = *orig->contents.result;\n")
1133                     else:
1134                         write_c("\t\t" + res_map.rust_obj + "* contents = MALLOC(sizeof(" + res_map.rust_obj + "), \"" + res_map.rust_obj + " result OK clone\");\n")
1135                         write_c("\t\t*contents = " + res_map.rust_obj.replace("LDK", "") + "_clone(orig->contents.result);\n")
1136                     write_c("\t\tres.contents.result = contents;\n")
1137                 write_c("\t} else {\n")
1138                 if err_map.c_ty == "void":
1139                     write_c("\t\tres.contents.err = NULL;\n")
1140                 else:
1141                     if err_map.is_native_primitive:
1142                         write_c("\t\t" + err_map.c_ty + "* contents = MALLOC(sizeof(" + err_map.c_ty + "), \"" + err_map.c_ty + " result Err clone\");\n")
1143                         write_c("\t\t*contents = *orig->contents.err;\n")
1144                     else:
1145                         write_c("\t\t" + err_map.rust_obj + "* contents = MALLOC(sizeof(" + err_map.rust_obj + "), \"" + err_map.rust_obj + " result Err clone\");\n")
1146                         write_c("\t\t*contents = " + err_map.rust_obj.replace("LDK", "") + "_clone(orig->contents.err);\n")
1147                     write_c("\t\tres.contents.err = contents;\n")
1148                 write_c("\t}\n\treturn res;\n}\n")
1149
1150     def map_tuple(struct_name, field_lines):
1151         out_java.write("\tpublic static native long " + struct_name + "_new(")
1152         write_c(consts.c_fn_ty_pfx + consts.ptr_c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1new(" + consts.c_fn_args_pfx)
1153         ty_list = []
1154         for idx, line in enumerate(field_lines):
1155             if idx != 0 and idx < len(field_lines) - 2:
1156                 ty_info = java_c_types(line.strip(';'), None)
1157                 if idx != 1:
1158                     out_java.write(", ")
1159                 e = chr(ord('a') + idx - 1)
1160                 out_java.write(ty_info.java_ty + " " + e)
1161                 write_c(", " + ty_info.c_ty + " " + e)
1162                 ty_list.append(ty_info)
1163         tuple_types[struct_name] = (ty_list, struct_name)
1164         out_java.write(");\n")
1165         write_c(") {\n")
1166         write_c("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1167         can_clone = True
1168         clone_str = "static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n"
1169         clone_str = clone_str + "\t" + struct_name + " ret = {\n"
1170         for idx, line in enumerate(field_lines):
1171             if idx != 0 and idx < len(field_lines) - 2:
1172                 ty_info = map_type(line.strip(';'), False, None, False, False)
1173                 e = chr(ord('a') + idx - 1)
1174                 if ty_info.arg_conv is not None:
1175                     write_c("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
1176                     write_c("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
1177                 else:
1178                     write_c("\tret->" + e + " = " + e + ";\n")
1179                 if ty_info.arg_conv_cleanup is not None:
1180                     write_c("\t//TODO: Really need to call " + ty_info.arg_conv_cleanup + " here\n")
1181                 if not ty_info.is_native_primitive and (ty_info.rust_obj.replace("LDK", "") + "_clone") not in clone_fns:
1182                     can_clone = False
1183                 elif can_clone and ty_info.is_native_primitive:
1184                     clone_str = clone_str + "\t\t." + chr(ord('a') + idx - 1) + " = orig->" + chr(ord('a') + idx - 1) + ",\n"
1185                 elif can_clone:
1186                     clone_str = clone_str + "\t\t." + chr(ord('a') + idx - 1) + " = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&orig->" + chr(ord('a') + idx - 1) + "),\n"
1187         write_c("\treturn (long)ret;\n")
1188         write_c("}\n")
1189
1190         if can_clone:
1191             clone_fns.add(struct_name.replace("LDK", "") + "_clone")
1192             write_c(clone_str)
1193             write_c("\t};\n\treturn ret;\n}\n")
1194
1195         for idx, ty_info in enumerate(ty_list):
1196             e = chr(ord('a') + idx)
1197             out_java.write("\tpublic static native " + ty_info.java_ty + " " + struct_name + "_get_" + e + "(long ptr);\n")
1198             write_c(consts.c_fn_ty_pfx + ty_info.c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1" + e + "(" + consts.c_fn_args_pfx + ", " + consts.ptr_c_ty + " ptr) {\n")
1199             write_c("\t" + struct_name + " *tuple = (" + struct_name + "*)ptr;\n")
1200             conv_info = map_type_with_info(ty_info, False, None, False, True)
1201             if conv_info.ret_conv is not None:
1202                 write_c("\t" + conv_info.ret_conv[0].replace("\n", "\n\t") + "tuple->" + e + conv_info.ret_conv[1].replace("\n", "\n\t") + "\n")
1203                 write_c("\treturn " + conv_info.ret_conv_name + ";\n")
1204             else:
1205                 write_c("\treturn tuple->" + e + ";\n")
1206             write_c("}\n")
1207
1208     out_java.write("""package org.ldk.impl;
1209 import org.ldk.enums.*;
1210
1211 public class bindings {
1212         public static class VecOrSliceDef {
1213                 public long dataptr;
1214                 public long datalen;
1215                 public long stride;
1216                 public VecOrSliceDef(long dataptr, long datalen, long stride) {
1217                         this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
1218                 }
1219         }
1220         static {
1221                 System.loadLibrary(\"lightningjni\");
1222                 init(java.lang.Enum.class, VecOrSliceDef.class);
1223                 init_class_cache();
1224         }
1225         static native void init(java.lang.Class c, java.lang.Class slicedef);
1226         static native void init_class_cache();
1227
1228         public static native boolean deref_bool(long ptr);
1229         public static native long deref_long(long ptr);
1230         public static native void free_heap_ptr(long ptr);
1231         public static native byte[] read_bytes(long ptr, long len);
1232         public static native byte[] get_u8_slice_bytes(long slice_ptr);
1233         public static native long bytes_to_u8_vec(byte[] bytes);
1234         public static native long new_txpointer_copy_data(byte[] txdata);
1235         public static native void txpointer_free(long ptr);
1236         public static native byte[] txpointer_get_buffer(long ptr);
1237         public static native long vec_slice_len(long vec);
1238         public static native long new_empty_slice_vec();
1239
1240 """)
1241
1242     with open(f"{sys.argv[3]}/structs/CommonBase{consts.file_ext}", "w") as out_java_struct:
1243         out_java_struct.write(consts.common_base)
1244
1245     in_block_comment = False
1246     cur_block_obj = None
1247
1248     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1249
1250     line_indicates_result_regex = re.compile("^   union (LDKCResult_[A-Za-z_0-9]*Ptr) contents;$")
1251     line_indicates_vec_regex = re.compile("^   (struct |enum |union )?([A-Za-z_0-9]*) \*data;$")
1252     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
1253     line_indicates_trait_regex = re.compile("^   (struct |enum |union )?([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
1254     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
1255     assert(line_indicates_trait_regex.match("   struct LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
1256     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
1257     assert(line_indicates_trait_regex.match("   struct LDKCVec_u8Z (*write)(const void *this_arg);"))
1258     line_field_var_regex = re.compile("^   struct ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1259     assert(line_field_var_regex.match("   struct LDKMessageSendEventsProvider MessageSendEventsProvider;"))
1260     assert(line_field_var_regex.match("   struct LDKChannelPublicKeys pubkeys;"))
1261     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
1262     assert(struct_name_regex.match("typedef struct LDKCVec_u8Z {"))
1263     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
1264
1265     union_enum_items = {}
1266     result_ptr_struct_items = {}
1267     for line in in_h:
1268         if in_block_comment:
1269             if line.endswith("*/\n"):
1270                 in_block_comment = False
1271         elif cur_block_obj is not None:
1272             cur_block_obj  = cur_block_obj + line
1273             if line.startswith("} "):
1274                 field_lines = []
1275                 struct_name = None
1276                 vec_ty = None
1277                 obj_lines = cur_block_obj.split("\n")
1278                 is_opaque = False
1279                 result_contents = None
1280                 is_unitary_enum = False
1281                 is_union_enum = False
1282                 is_union = False
1283                 is_tuple = False
1284                 trait_fn_lines = []
1285                 field_var_lines = []
1286
1287                 for idx, struct_line in enumerate(obj_lines):
1288                     if struct_line.strip().startswith("/*"):
1289                         in_block_comment = True
1290                     if in_block_comment:
1291                         if struct_line.endswith("*/"):
1292                             in_block_comment = False
1293                     else:
1294                         struct_name_match = struct_name_regex.match(struct_line)
1295                         if struct_name_match is not None:
1296                             struct_name = struct_name_match.group(3)
1297                             if struct_name_match.group(1) == "enum":
1298                                 if not struct_name.endswith("_Tag"):
1299                                     is_unitary_enum = True
1300                                 else:
1301                                     is_union_enum = True
1302                             elif struct_name_match.group(1) == "union":
1303                                 is_union = True
1304                         if line_indicates_opaque_regex.match(struct_line):
1305                             is_opaque = True
1306                         result_match = line_indicates_result_regex.match(struct_line)
1307                         if result_match is not None:
1308                             result_contents = result_match.group(1)
1309                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
1310                         if vec_ty_match is not None and struct_name.startswith("LDKCVec_"):
1311                             vec_ty = vec_ty_match.group(2)
1312                         elif struct_name.startswith("LDKC2Tuple_") or struct_name.startswith("LDKC3Tuple_"):
1313                             is_tuple = True
1314                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
1315                         if trait_fn_match is not None:
1316                             trait_fn_lines.append(trait_fn_match)
1317                         field_var_match = line_field_var_regex.match(struct_line)
1318                         if field_var_match is not None:
1319                             field_var_lines.append(field_var_match)
1320                         field_lines.append(struct_line)
1321
1322                 assert(struct_name is not None)
1323                 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))
1324                 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))
1325                 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))
1326                 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))
1327                 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))
1328                 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))
1329                 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))
1330
1331                 if is_opaque:
1332                     opaque_structs.add(struct_name)
1333                     with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "w") as out_java_struct:
1334                         out_java_struct.write(consts.hu_struct_file_prefix)
1335                         out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase")
1336                         if struct_name.startswith("LDKLocked"):
1337                             out_java_struct.write(" implements AutoCloseable")
1338                         out_java_struct.write(" {\n")
1339                         out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
1340                         if struct_name.startswith("LDKLocked"):
1341                             out_java_struct.write("\t@Override public void close() {\n")
1342                         else:
1343                             out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1344                             out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1345                             out_java_struct.write("\t\tsuper.finalize();\n")
1346                         out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1347                         out_java_struct.write("\t}\n\n")
1348                 elif result_contents is not None:
1349                     assert result_contents in result_ptr_struct_items
1350                     res_ty, err_ty = result_ptr_struct_items[result_contents]
1351                     map_result(struct_name, res_ty, err_ty)
1352                 elif struct_name.startswith("LDKCResult_") and struct_name.endswith("ZPtr"):
1353                     for line in field_lines:
1354                         if line.endswith("*result;"):
1355                             res_ty = line[:-8].strip()
1356                         elif line.endswith("*err;"):
1357                             err_ty = line[:-5].strip()
1358                     result_ptr_struct_items[struct_name] = (res_ty, err_ty)
1359                     result_types.add(struct_name[:-3])
1360                 elif is_tuple:
1361                     map_tuple(struct_name, field_lines)
1362                 elif vec_ty is not None:
1363                     ty_info = map_type(vec_ty + " arr_elem", False, None, False, False)
1364                     if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
1365                         out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
1366                         write_c(consts.c_fn_ty_pfx + consts.ptr_c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1new(" + consts.c_fn_args_pfx + ", " + ty_info.c_ty + "Array elems) {\n")
1367                         write_c("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1368                         write_c("\tret->datalen = " + consts.get_native_arr_len_call[0] + "elems" + consts.get_native_arr_len_call[1] + ";\n")
1369                         write_c("\tif (ret->datalen == 0) {\n")
1370                         write_c("\t\tret->data = NULL;\n")
1371                         write_c("\t} else {\n")
1372                         write_c("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1373                         write_c("\t\t" + ty_info.c_ty + " *java_elems = " + consts.get_native_arr_ptr_call[0] + "elems" + consts.get_native_arr_ptr_call[1] + ";\n")
1374                         write_c("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1375                         if ty_info.arg_conv is not None:
1376                             write_c("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1377                             write_c("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1378                             write_c("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1379                             assert ty_info.arg_conv_cleanup is None
1380                         else:
1381                             write_c("\t\t\tret->data[i] = java_elems[i];\n")
1382                         write_c("\t\t}\n")
1383                         cleanup = consts.release_native_arr_ptr_call("elems", "java_elems")
1384                         if cleanup is not None:
1385                             write_c("\t\t" + cleanup + ";\n")
1386                         write_c("\t}\n")
1387                         write_c("\treturn (long)ret;\n")
1388                         write_c("}\n")
1389
1390                     if ty_info.is_native_primitive:
1391                         clone_fns.add(struct_name.replace("LDK", "") + "_clone")
1392                         write_c("static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n")
1393                         write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.c_ty + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
1394                         write_c("\tmemcpy(ret.data, orig->data, sizeof(" + ty_info.c_ty + ") * ret.datalen);\n")
1395                         write_c("\treturn ret;\n}\n")
1396                     elif (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
1397                         ty_name = "CVec_" + ty_info.rust_obj.replace("LDK", "") + "Z";
1398                         clone_fns.add(ty_name + "_clone")
1399                         write_c("static inline " + struct_name + " " + ty_name + "_clone(const " + struct_name + " *orig) {\n")
1400                         write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.rust_obj + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
1401                         write_c("\tfor (size_t i = 0; i < ret.datalen; i++) {\n")
1402                         write_c("\t\tret.data[i] = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&orig->data[i]);\n")
1403                         write_c("\t}\n\treturn ret;\n}\n")
1404                 elif is_union_enum:
1405                     assert(struct_name.endswith("_Tag"))
1406                     struct_name = struct_name[:-4]
1407                     union_enum_items[struct_name] = {"field_lines": field_lines}
1408                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
1409                     enum_var_name = struct_name.split("_")
1410                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
1411                 elif struct_name in union_enum_items:
1412                     map_complex_enum(struct_name, union_enum_items[struct_name])
1413                 elif is_unitary_enum:
1414                     map_unitary_enum(struct_name, field_lines)
1415                 elif len(trait_fn_lines) > 0:
1416                     trait_structs.add(struct_name)
1417                     map_trait(struct_name, field_var_lines, trait_fn_lines)
1418                 elif struct_name == "LDKTxOut":
1419                     with open(f"{sys.argv[3]}/structs/TxOut{consts.file_ext}", "w") as out_java_struct:
1420                         out_java_struct.write(consts.hu_struct_file_prefix)
1421                         out_java_struct.write("public class TxOut extends CommonBase{\n")
1422                         out_java_struct.write("\tTxOut(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
1423                         out_java_struct.write("\tlong to_c_ptr() { return 0; }\n")
1424                         out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1425                         out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1426                         out_java_struct.write("\t\tsuper.finalize();\n")
1427                         out_java_struct.write("\t\tif (ptr != 0) { bindings.TxOut_free(ptr); }\n")
1428                         out_java_struct.write("\t}\n")
1429                         # TODO: TxOut body
1430                         out_java_struct.write("}")
1431                 else:
1432                     pass # Everything remaining is a byte[] or some form
1433                 cur_block_obj = None
1434         else:
1435             fn_ptr = fn_ptr_regex.match(line)
1436             fn_ret_arr = fn_ret_arr_regex.match(line)
1437             reg_fn = reg_fn_regex.match(line)
1438             const_val = const_val_regex.match(line)
1439
1440             if line.startswith("#include <"):
1441                 pass
1442             elif line.startswith("/*"):
1443                 #out_java.write("\t" + line)
1444                 if not line.endswith("*/\n"):
1445                     in_block_comment = True
1446             elif line.startswith("typedef enum "):
1447                 cur_block_obj = line
1448             elif line.startswith("typedef struct "):
1449                 cur_block_obj = line
1450             elif line.startswith("typedef union "):
1451                 cur_block_obj = line
1452             elif fn_ptr is not None:
1453                 map_fn(line, fn_ptr, None, None)
1454             elif fn_ret_arr is not None:
1455                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1456             elif reg_fn is not None:
1457                 map_fn(line, reg_fn, None, None)
1458             elif const_val_regex is not None:
1459                 # TODO Map const variables
1460                 pass
1461             else:
1462                 assert(line == "\n")
1463
1464     out_java.write("}\n")
1465     for struct_name in opaque_structs:
1466         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1467             out_java_struct.write("}\n")
1468     for struct_name in trait_structs:
1469         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1470             out_java_struct.write("}\n")
1471 with open(sys.argv[4], "w") as out_c:
1472     out_c.write(consts.c_file_pfx)
1473     out_c.write(consts.init_str(c_array_class_caches))
1474     out_c.write(c_file)