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