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