Mark function arguments and return values Nullable if relevant
[ldk-java] / genbindings.py
1 #!/usr/bin/env python3
2 import os, sys, re, subprocess
3
4 if len(sys.argv) < 7:
5     print("USAGE: /path/to/lightning.h /path/to/bindings/output /path/to/bindings/ /path/to/bindings/output.c debug lang")
6     sys.exit(1)
7
8 if sys.argv[5] == "false":
9     DEBUG = False
10 elif sys.argv[5] == "true":
11     DEBUG = True
12 else:
13     print("debug should be true or false and indicates whether to track allocations and ensure we don't leak")
14     sys.exit(1)
15
16 target = None
17 if sys.argv[6] == "java" or sys.argv[6] == "android":
18     import java_strings
19     from java_strings import Consts
20     target = java_strings.Target.JAVA
21     if sys.argv[6] == "android":
22         target = java_strings.Target.ANDROID
23 elif sys.argv[6] == "typescript":
24     import typescript_strings
25     from typescript_strings import Consts
26     target = typescript_strings.Target.NODEJS
27     if len(sys.argv) == 8 and sys.argv[7] == 'browser':
28         target = typescript_strings.Target.BROWSER
29 else:
30     print("Only java or typescript can be set for lang")
31     sys.exit(1)
32
33
34 consts = Consts(DEBUG, target=target)
35
36 local_git_version = os.getenv("LDK_GARBAGECOLLECTED_GIT_OVERRIDE")
37 if local_git_version is None:
38     local_git_version = subprocess.check_output(["git", "describe", '--tag', '--dirty']).decode("utf-8").strip()
39
40 from bindingstypes import *
41
42 c_file = ""
43 def write_c(s):
44     global c_file
45     c_file += s
46
47 def camel_to_snake(s):
48     # Convert camel case to snake case, in a way that appears to match cbindgen
49     con = "_"
50     ret = ""
51     lastchar = ""
52     lastund = False
53     for char in s:
54         if lastchar.isupper():
55             if not char.isupper() and not lastund:
56                 ret = ret + "_"
57                 lastund = True
58             else:
59                 lastund = False
60             ret = ret + lastchar.lower()
61         else:
62             ret = ret + lastchar
63             if char.isupper() and not lastund:
64                 ret = ret + "_"
65                 lastund = True
66             else:
67                 lastund = False
68         lastchar = char
69         if char.isnumeric():
70             lastund = True
71     return (ret + lastchar.lower()).strip("_")
72
73 def doc_to_params_ret_nullable(doc):
74     if doc is None:
75         return (set(), False)
76     params = set()
77     ret_null = False
78     for line in doc.splitlines():
79         if "may be NULL or all-0s to represent None" not in line:
80             continue
81         if "Note that the return value" in line:
82             ret_null = True
83         elif "Note that " in line:
84             param = line.split("Note that ")[1].split(" ")[0]
85             params.add(param)
86     return (params, ret_null)
87
88 unitary_enums = set()
89 complex_enums = set()
90 opaque_structs = set()
91 trait_structs = {}
92 result_types = set()
93 tuple_types = {}
94
95 var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([a-z0-9]*)\]")
96 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
97 java_c_types_none_allowed = True # Unset when we do the real pass that populates the above sets
98 def java_c_types(fn_arg, ret_arr_len):
99     fn_arg = fn_arg.strip()
100     if fn_arg.startswith("MUST_USE_RES "):
101         fn_arg = fn_arg[13:]
102     is_const = False
103     if fn_arg.startswith("const "):
104         fn_arg = fn_arg[6:]
105         is_const = True
106     if fn_arg.startswith("struct "):
107         fn_arg = fn_arg[7:]
108     if fn_arg.startswith("enum "):
109         fn_arg = fn_arg[5:]
110     nonnull_ptr = "NONNULL_PTR" in fn_arg
111     fn_arg = fn_arg.replace("NONNULL_PTR", "")
112
113     is_ptr = False
114     take_by_ptr = False
115     rust_obj = None
116     arr_access = None
117     java_hu_ty = None
118     if fn_arg.startswith("LDKThirtyTwoBytes"):
119         fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
120         assert var_is_arr_regex.match(fn_arg[8:])
121         rust_obj = "LDKThirtyTwoBytes"
122         arr_access = "data"
123     elif fn_arg.startswith("LDKTxid"):
124         fn_arg = "uint8_t (*" + fn_arg[8:] + ")[32]"
125         assert var_is_arr_regex.match(fn_arg[8:])
126         rust_obj = "LDKThirtyTwoBytes"
127         arr_access = "data"
128     elif fn_arg.startswith("LDKPublicKey"):
129         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
130         assert var_is_arr_regex.match(fn_arg[8:])
131         rust_obj = "LDKPublicKey"
132         arr_access = "compressed_form"
133     elif fn_arg.startswith("LDKSecretKey"):
134         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
135         assert var_is_arr_regex.match(fn_arg[8:])
136         rust_obj = "LDKSecretKey"
137         arr_access = "bytes"
138     elif fn_arg.startswith("LDKSignature"):
139         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
140         assert var_is_arr_regex.match(fn_arg[8:])
141         rust_obj = "LDKSignature"
142         arr_access = "compact_form"
143     elif fn_arg.startswith("LDKRecoverableSignature"):
144         fn_arg = "uint8_t (*" + fn_arg[25:] + ")[68]"
145         assert var_is_arr_regex.match(fn_arg[8:])
146         rust_obj = "LDKRecoverableSignature"
147         arr_access = "serialized_form"
148     elif fn_arg.startswith("LDKThreeBytes"):
149         fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
150         assert var_is_arr_regex.match(fn_arg[8:])
151         rust_obj = "LDKThreeBytes"
152         arr_access = "data"
153     elif fn_arg.startswith("LDKFourBytes"):
154         fn_arg = "uint8_t (*" + fn_arg[13:] + ")[4]"
155         assert var_is_arr_regex.match(fn_arg[8:])
156         rust_obj = "LDKFourBytes"
157         arr_access = "data"
158     elif fn_arg.startswith("LDKSixteenBytes"):
159         fn_arg = "uint8_t (*" + fn_arg[16:] + ")[16]"
160         assert var_is_arr_regex.match(fn_arg[8:])
161         rust_obj = "LDKSixteenBytes"
162         arr_access = "data"
163     elif fn_arg.startswith("LDKTwentyBytes"):
164         fn_arg = "uint8_t (*" + fn_arg[15:] + ")[20]"
165         assert var_is_arr_regex.match(fn_arg[8:])
166         rust_obj = "LDKTwentyBytes"
167         arr_access = "data"
168     elif fn_arg.startswith("LDKTenBytes"):
169         fn_arg = "uint8_t (*" + fn_arg[12:] + ")[10]"
170         assert var_is_arr_regex.match(fn_arg[8:])
171         rust_obj = "LDKTenBytes"
172         arr_access = "data"
173     elif fn_arg.startswith("LDKu8slice"):
174         fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
175         assert var_is_arr_regex.match(fn_arg[8:])
176         rust_obj = "LDKu8slice"
177         arr_access = "data"
178     elif fn_arg.startswith("LDKCVec_u8Z"):
179         fn_arg = "uint8_t (*" + fn_arg[12:] + ")[datalen]"
180         rust_obj = "LDKCVec_u8Z"
181         assert var_is_arr_regex.match(fn_arg[8:])
182         arr_access = "data"
183     elif fn_arg.startswith("LDKTransaction ") or fn_arg == "LDKTransaction":
184         fn_arg = "uint8_t (*" + fn_arg[15:] + ")[datalen]"
185         rust_obj = "LDKTransaction"
186         assert var_is_arr_regex.match(fn_arg[8:])
187         arr_access = "data"
188     elif fn_arg.startswith("LDKCVec_"):
189         is_ptr = False
190         if "*" in fn_arg:
191             fn_arg = fn_arg.replace("*", "")
192             is_ptr = True
193
194         tyn = fn_arg[8:].split(" ")
195         assert tyn[0].endswith("Z")
196         if tyn[0] == "u64Z":
197             new_arg = "uint64_t"
198         else:
199             new_arg = "LDK" + tyn[0][:-1]
200         for a in tyn[1:]:
201             new_arg = new_arg + " " + a
202         res = java_c_types(new_arg, ret_arr_len)
203         if res is None:
204             assert java_c_types_none_allowed
205             return None
206         if is_ptr:
207             res.pass_by_ref = True
208         if res.is_native_primitive or res.passed_as_ptr:
209             return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
210                 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=res.c_ty + "Array", passed_as_ptr=False, is_ptr=is_ptr,
211                 nonnull_ptr=nonnull_ptr, is_const=is_const,
212                 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
213         else:
214             return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
215                 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=consts.ptr_arr, passed_as_ptr=False, is_ptr=is_ptr,
216                 nonnull_ptr=nonnull_ptr, is_const=is_const,
217                 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
218
219     is_primitive = False
220     arr_len = None
221     mapped_type = []
222     java_type_plural = None
223     if fn_arg.startswith("void"):
224         java_ty = "void"
225         c_ty = "void"
226         fn_ty_arg = "V"
227         fn_arg = fn_arg[4:].strip()
228         is_primitive = True
229     elif fn_arg.startswith("bool"):
230         java_ty = "boolean"
231         c_ty = "jboolean"
232         fn_ty_arg = "Z"
233         fn_arg = fn_arg[4:].strip()
234         is_primitive = True
235     elif fn_arg.startswith("uint8_t"):
236         mapped_type = consts.c_type_map['uint8_t']
237         java_ty = mapped_type[0]
238         c_ty = "int8_t"
239         fn_ty_arg = "B"
240         fn_arg = fn_arg[7:].strip()
241         is_primitive = True
242     elif fn_arg.startswith("LDKu5"):
243         java_ty = consts.c_type_map['uint8_t'][0]
244         java_hu_ty = "UInt5"
245         rust_obj = "LDKu5"
246         c_ty = "int8_t"
247         fn_ty_arg = "B"
248         fn_arg = fn_arg[6:].strip()
249     elif fn_arg.startswith("uint16_t"):
250         mapped_type = consts.c_type_map['uint16_t']
251         java_ty = mapped_type[0]
252         c_ty = "int16_t"
253         fn_ty_arg = "S"
254         fn_arg = fn_arg[8:].strip()
255         is_primitive = True
256     elif fn_arg.startswith("uint32_t"):
257         mapped_type = consts.c_type_map['uint32_t']
258         java_ty = mapped_type[0]
259         c_ty = "int32_t"
260         fn_ty_arg = "I"
261         fn_arg = fn_arg[8:].strip()
262         is_primitive = True
263     elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
264         # TODO: uintptr_t is arch-dependent :(
265         mapped_type = consts.c_type_map['uint64_t']
266         java_ty = mapped_type[0]
267         fn_ty_arg = "J"
268         if fn_arg.startswith("uint64_t"):
269             c_ty = "int64_t"
270             fn_arg = fn_arg[8:].strip()
271         else:
272             c_ty = "int64_t"
273             rust_obj = "uintptr_t"
274             fn_arg = fn_arg[9:].strip()
275         is_primitive = True
276     elif is_const and fn_arg.startswith("char *"):
277         java_ty = "String"
278         c_ty = "const char*"
279         fn_ty_arg = "Ljava/lang/String;"
280         fn_arg = fn_arg[6:].strip()
281     elif fn_arg.startswith("LDKStr"):
282         rust_obj = "LDKStr"
283         java_ty = "String"
284         c_ty = "jstring"
285         fn_ty_arg = "Ljava/lang/String;"
286         fn_arg = fn_arg[6:].strip()
287         arr_access = "chars"
288         arr_len = "len"
289     else:
290         ma = var_ty_regex.match(fn_arg)
291         if ma.group(1).strip() in unitary_enums:
292             assert ma.group(1).strip().startswith("LDK")
293             java_ty = ma.group(1).strip()[3:]
294             java_hu_ty = java_ty
295             c_ty = consts.result_c_ty
296             fn_ty_arg = "Lorg/ldk/enums/" + java_ty + ";"
297             fn_arg = ma.group(2).strip()
298             rust_obj = ma.group(1).strip()
299         elif ma.group(1).strip().startswith("LDKC2Tuple"):
300             c_ty = consts.ptr_c_ty
301             java_ty = consts.ptr_native_ty
302             java_hu_ty = "TwoTuple<"
303             if not ma.group(1).strip() in tuple_types:
304                 assert java_c_types_none_allowed
305                 return None
306             for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
307                 if idx != 0:
308                     java_hu_ty = java_hu_ty + ", "
309                 if ty_info.is_native_primitive:
310                     if ty_info.java_hu_ty == "int":
311                         java_hu_ty = java_hu_ty + "Integer" # Java concrete integer type is Integer, not Int
312                     else:
313                         java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
314                 else:
315                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty
316             java_hu_ty = java_hu_ty + ">"
317             fn_ty_arg = "J"
318             fn_arg = ma.group(2).strip()
319             rust_obj = ma.group(1).strip()
320             take_by_ptr = True
321         elif ma.group(1).strip().startswith("LDKC3Tuple"):
322             c_ty = consts.ptr_c_ty
323             java_ty = consts.ptr_native_ty
324             java_hu_ty = "ThreeTuple<"
325             if not ma.group(1).strip() in tuple_types:
326                 assert java_c_types_none_allowed
327                 return None
328             for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
329                 if idx != 0:
330                     java_hu_ty = java_hu_ty + ", "
331                 if ty_info.is_native_primitive:
332                     if ty_info.java_hu_ty == "int":
333                         java_hu_ty = java_hu_ty + "Integer" # Java concrete integer type is Integer, not Int
334                     else:
335                         java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
336                 else:
337                     java_hu_ty = java_hu_ty + ty_info.java_hu_ty
338             java_hu_ty = java_hu_ty + ">"
339             fn_ty_arg = "J"
340             fn_arg = ma.group(2).strip()
341             rust_obj = ma.group(1).strip()
342             take_by_ptr = True
343         else:
344             c_ty = consts.ptr_c_ty
345             java_ty = consts.ptr_native_ty
346             java_hu_ty = ma.group(1).strip().replace("LDKCOption", "Option").replace("LDKCResult", "Result").replace("LDK", "")
347             fn_ty_arg = "J"
348             fn_arg = ma.group(2).strip()
349             rust_obj = ma.group(1).strip()
350             take_by_ptr = True
351
352     if fn_arg.startswith(" *") or fn_arg.startswith("*"):
353         fn_arg = fn_arg.replace("*", "").strip()
354         is_ptr = True
355         c_ty = consts.ptr_c_ty
356         java_ty = consts.ptr_native_ty
357         fn_ty_arg = "J"
358
359     var_is_arr = var_is_arr_regex.match(fn_arg)
360     if var_is_arr is not None or ret_arr_len is not None:
361         assert(not take_by_ptr)
362         assert(not is_ptr)
363         # is there a special case for plurals?
364         if len(mapped_type) == 2:
365             java_ty = mapped_type[1]
366         else:
367             java_ty = java_ty + "[]"
368         c_ty = c_ty + "Array"
369         if var_is_arr is not None:
370             if var_is_arr.group(1) == "":
371                 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,
372                     passed_as_ptr=False, is_ptr=False, nonnull_ptr=nonnull_ptr, var_name="arg",
373                     arr_len=var_is_arr.group(2), arr_access=arr_access, is_native_primitive=False)
374             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,
375                 passed_as_ptr=False, is_ptr=False, nonnull_ptr=nonnull_ptr, var_name=var_is_arr.group(1),
376                 arr_len=var_is_arr.group(2), arr_access=arr_access, is_native_primitive=False)
377
378     if java_hu_ty is None:
379         java_hu_ty = java_ty
380     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,
381         is_const=is_const, is_ptr=is_ptr, nonnull_ptr=nonnull_ptr, var_name=fn_arg, arr_len=arr_len, arr_access=arr_access, is_native_primitive=is_primitive)
382
383 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
384 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
385 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
386 clone_fns = set()
387 constructor_fns = {}
388
389 from gen_type_mapping import TypeMappingGenerator
390 type_mapping_generator = TypeMappingGenerator(java_c_types, consts, opaque_structs, clone_fns, unitary_enums, trait_structs, complex_enums, result_types, tuple_types)
391
392 with open(sys.argv[1]) as in_h:
393     for line in in_h:
394         reg_fn = reg_fn_regex.match(line)
395         if reg_fn is not None:
396             if reg_fn.group(2).endswith("_clone"):
397                 clone_fns.add(reg_fn.group(2))
398             else:
399                 rty = java_c_types(reg_fn.group(1), None)
400                 if rty is not None and not rty.is_native_primitive and reg_fn.group(2) == rty.java_hu_ty + "_new":
401                     constructor_fns[rty.rust_obj] = reg_fn.group(3)
402             continue
403         arr_fn = fn_ret_arr_regex.match(line)
404         if arr_fn is not None:
405             if arr_fn.group(2).endswith("_clone"):
406                 clone_fns.add(arr_fn.group(2))
407             # No object constructors return arrays, as then they wouldn't be an object constructor
408             continue
409
410 # Define some manual clones...
411 clone_fns.add("ThirtyTwoBytes_clone")
412 write_c("static inline struct LDKThirtyTwoBytes ThirtyTwoBytes_clone(const struct LDKThirtyTwoBytes *orig) { struct LDKThirtyTwoBytes ret; memcpy(ret.data, orig->data, 32); return ret; }\n")
413
414 java_c_types_none_allowed = False # C structs created by cbindgen are declared in dependency order
415
416 with open(f"{sys.argv[3]}/structs/UtilMethods{consts.file_ext}", "a") as util:
417     util.write(consts.util_fn_pfx)
418
419 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java:
420     # Map a top-level function
421     def map_fn(line, re_match, ret_arr_len, c_call_string, doc_comment):
422         method_return_type = re_match.group(1)
423         method_name = re_match.group(2)
424         orig_method_name = str(method_name)
425         method_comma_separated_arguments = re_match.group(3)
426         method_arguments = method_comma_separated_arguments.split(',')
427
428         is_free = method_name.endswith("_free")
429         if method_name.startswith("COption") or method_name.startswith("CResult"):
430             struct_meth = method_name.rsplit("Z", 1)[0][1:] + "Z"
431         else:
432             struct_meth = method_name.split("_")[0]
433
434         return_type_info = type_mapping_generator.map_type(method_return_type.strip() + " ret", True, ret_arr_len, False, False)
435
436         (params_nullable, ret_nullable) = doc_to_params_ret_nullable(doc_comment)
437         if ret_nullable:
438             return_type_info.nullable = True
439
440         argument_types = []
441         default_constructor_args = {}
442         takes_self = False
443         takes_self_ptr = False
444         args_known = True
445
446         for argument_index, argument in enumerate(method_arguments):
447             argument_conversion_info = type_mapping_generator.map_type(argument, False, None, is_free, True)
448             if argument_index == 0 and argument_conversion_info.java_hu_ty == struct_meth:
449                 takes_self = True
450                 if argument_conversion_info.ty_info.is_ptr:
451                     takes_self_ptr = True
452             elif argument_conversion_info.arg_name in params_nullable:
453                 argument_conversion_info.nullable = True
454             if argument_conversion_info.arg_conv is not None and "Warning" in argument_conversion_info.arg_conv:
455                 assert not argument_conversion_info.arg_name in params_nullable
456                 if argument_conversion_info.rust_obj in constructor_fns:
457                     assert not is_free
458                     for explode_arg in constructor_fns[argument_conversion_info.rust_obj].split(','):
459                         explode_arg_conv = type_mapping_generator.map_type(explode_arg, False, None, False, True)
460                         if explode_arg_conv.c_ty == "void":
461                             # We actually want to handle this case, but for now its only used in NetGraphMsgHandler::new()
462                             # which ends up resulting in a redundant constructor - both without arguments for the NetworkGraph.
463                             args_known = False
464                             pass
465                         if not argument_conversion_info.arg_name in default_constructor_args:
466                             default_constructor_args[argument_conversion_info.arg_name] = []
467                         default_constructor_args[argument_conversion_info.arg_name].append(explode_arg_conv)
468             argument_types.append(argument_conversion_info)
469         if not takes_self and return_type_info.java_hu_ty != struct_meth:
470             if not return_type_info.java_hu_ty.startswith("Result_" + struct_meth):
471                 method_name = orig_method_name
472                 struct_meth = ""
473
474         out_java.write("\t// " + line)
475         (out_java_delta, out_c_delta, out_java_struct_delta) = \
476             consts.map_function(argument_types, c_call_string, method_name, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_ptr, args_known, type_mapping_generator, doc_comment)
477         out_java.write(out_java_delta)
478
479         if is_free:
480             assert len(argument_types) == 1
481             assert return_type_info.c_ty == "void"
482             write_c(consts.c_fn_ty_pfx + "void " + consts.c_fn_name_define_pfx(method_name, True) + argument_types[0].c_ty + " " + argument_types[0].ty_info.var_name + ") {\n")
483             if argument_types[0].ty_info.passed_as_ptr and not argument_types[0].ty_info.rust_obj in opaque_structs:
484                 write_c("\tif ((" + argument_types[0].ty_info.var_name + " & 1) != 0) return;\n")
485
486             for info in argument_types:
487                 if info.arg_conv is not None:
488                     write_c("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
489             assert c_call_string is None
490             write_c("\t" + method_name + "(")
491             if argument_types[0].arg_conv_name is not None:
492                 write_c(argument_types[0].arg_conv_name)
493             write_c(");")
494             for info in argument_types:
495                 if info.arg_conv_cleanup is not None:
496                     write_c("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
497             write_c("\n}\n\n")
498         else:
499             write_c(out_c_delta)
500
501         out_java_struct = None
502         expected_struct = "LDK" + struct_meth
503         expected_cstruct = "LDKC" + struct_meth
504         if (expected_struct in opaque_structs or expected_struct in trait_structs
505                 or expected_struct in complex_enums or expected_cstruct in complex_enums
506                 or expected_cstruct in result_types) and not is_free:
507             out_java_struct = open(f"{sys.argv[3]}/structs/{struct_meth}{consts.file_ext}", "a")
508             out_java_struct.write(out_java_struct_delta)
509         elif (not is_free and not method_name.endswith("_clone") and
510                 not method_name.startswith("_") and
511                 method_name != "check_platform" and method_name != "Result_read" and
512                 not expected_struct in unitary_enums and
513                 ((not method_name.startswith("C2Tuple_") and not method_name.startswith("C3Tuple_"))
514                   or method_name.endswith("_read"))):
515             out_java_struct = open(f"{sys.argv[3]}/structs/UtilMethods{consts.file_ext}", "a")
516             for line in out_java_struct_delta.splitlines():
517                 if not line.strip().startswith("this."):
518                     out_java_struct.write(line + "\n")
519                 else:
520                     out_java_struct.write("\t\t// " + line.strip() + "\n")
521
522     def map_unitary_enum(struct_name, field_lines, enum_doc_comment):
523         assert struct_name.startswith("LDK")
524         with open(f"{sys.argv[3]}/enums/{struct_name[3:]}{consts.file_ext}", "w") as out_java_enum:
525             unitary_enums.add(struct_name)
526             for idx, struct_line in enumerate(field_lines):
527                 if idx == 0:
528                     assert(struct_line == "typedef enum %s {" % struct_name)
529                 elif idx == len(field_lines) - 3:
530                     assert(struct_line.endswith("_Sentinel,"))
531                 elif idx == len(field_lines) - 2:
532                     assert(struct_line == "} %s;" % struct_name)
533                 elif idx == len(field_lines) - 1:
534                     assert(struct_line == "")
535             assert struct_name.startswith("LDK")
536             (c_out, native_file_out, native_out) = consts.native_c_unitary_enum_map(struct_name[3:], [x.strip().strip(",") for x in field_lines[1:-3]], enum_doc_comment)
537             write_c(c_out)
538             out_java_enum.write(native_file_out)
539             out_java.write(native_out)
540
541     def map_complex_enum(struct_name, union_enum_items, inline_enum_variants, enum_doc_comment):
542         java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
543         complex_enums.add(struct_name)
544
545         enum_variants = []
546         tag_field_lines = union_enum_items["field_lines"]
547         for idx, struct_line in enumerate(tag_field_lines):
548             if idx == 0:
549                 assert(struct_line == "typedef enum %s_Tag {" % struct_name)
550             elif idx == len(tag_field_lines) - 3:
551                 assert(struct_line.endswith("_Sentinel,"))
552             elif idx == len(tag_field_lines) - 2:
553                 assert(struct_line == "} %s_Tag;" % struct_name)
554             elif idx == len(tag_field_lines) - 1:
555                 assert(struct_line == "")
556             else:
557                 variant_name = struct_line.strip(' ,')[len(struct_name) + 1:]
558                 fields = []
559                 if "LDK" + variant_name in union_enum_items:
560                     enum_var_lines = union_enum_items["LDK" + variant_name]
561                     for idx, field in enumerate(enum_var_lines):
562                         if idx != 0 and idx < len(enum_var_lines) - 2 and field.strip() != "":
563                             fields.append(type_mapping_generator.map_type(field.strip(' ;'), False, None, False, True))
564                     enum_variants.append(ComplexEnumVariantInfo(variant_name, fields, False))
565                 elif camel_to_snake(variant_name) in inline_enum_variants:
566                     fields.append(type_mapping_generator.map_type(inline_enum_variants[camel_to_snake(variant_name)] + " " + camel_to_snake(variant_name), False, None, False, True))
567                     enum_variants.append(ComplexEnumVariantInfo(variant_name, fields, True))
568                 else:
569                     enum_variants.append(ComplexEnumVariantInfo(variant_name, fields, True))
570
571         with open(f"{sys.argv[3]}/structs/{java_hu_type}{consts.file_ext}", "w") as out_java_enum:
572             (out_java_addendum, out_java_enum_addendum, out_c_addendum) = consts.map_complex_enum(struct_name, enum_variants, camel_to_snake, enum_doc_comment)
573
574             out_java_enum.write(out_java_enum_addendum)
575             out_java.write(out_java_addendum)
576             write_c(out_c_addendum)
577
578     def map_trait(struct_name, field_var_lines, trait_fn_lines, trait_doc_comment):
579         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "w") as out_java_trait:
580             field_var_convs = []
581             flattened_field_var_convs = []
582             for var_line in field_var_lines:
583                 if var_line.group(1) in trait_structs:
584                     field_var_convs.append((var_line.group(1), var_line.group(2), trait_structs[var_line.group(1)]))
585                     flattened_field_var_convs.append((var_line.group(1), var_line.group(2), ))
586                     flattened_field_var_convs.extend(trait_structs[var_line.group(1)])
587                 else:
588                     mapped = type_mapping_generator.map_type(var_line.group(1) + " " + var_line.group(2), False, None, False, False)
589                     field_var_convs.append(mapped)
590                     flattened_field_var_convs.append(mapped)
591             trait_structs[struct_name] = field_var_convs
592
593             field_fns = []
594             for fn_docs, fn_line in trait_fn_lines:
595                 if fn_line == "cloned":
596                     ret_ty_info = type_mapping_generator.map_type("void", True, None, False, False)
597                     field_fns.append(TraitMethInfo("cloned", False, ret_ty_info, [], fn_docs))
598                 else:
599                     ret_ty_info = type_mapping_generator.map_type(fn_line.group(2).strip() + " ret", True, None, False, False)
600                     is_const = fn_line.group(4) is not None
601                     (nullable_params, ret_nullable) = doc_to_params_ret_nullable(fn_docs)
602                     if ret_nullable:
603                         assert False # This isn't yet handled on the Java side
604                         ret_ty_info.nullable = True
605
606                     arg_tys = []
607                     for idx, arg in enumerate(fn_line.group(5).split(',')):
608                         if arg == "":
609                             continue
610                         arg_conv_info = type_mapping_generator.map_type(arg, True, None, False, False)
611                         if arg_conv_info.arg_name in nullable_params:
612                             # Types that are actually null instead of all-0s aren't yet handled on the Java side:
613                             assert arg_conv_info.rust_obj == "LDKPublicKey"
614                             arg_conv_info.nullable = True
615                         arg_tys.append(arg_conv_info)
616                     field_fns.append(TraitMethInfo(fn_line.group(3), is_const, ret_ty_info, arg_tys, fn_docs))
617
618             (out_java_addendum, out_java_trait_addendum, out_c_addendum) = consts.native_c_map_trait(struct_name, field_var_convs, flattened_field_var_convs, field_fns, trait_doc_comment)
619             write_c(out_c_addendum)
620             out_java_trait.write(out_java_trait_addendum)
621             out_java.write(out_java_addendum)
622
623         for fn_docs, fn_line in trait_fn_lines:
624             if fn_line == "cloned":
625                 continue
626             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
627             is_log = fn_line.group(3) == "log" and struct_name == "LDKLogger"
628             if fn_line.group(3) != "free" and fn_line.group(3) != "eq" and not is_log:
629                 dummy_line = fn_line.group(2) + struct_name.replace("LDK", "") + "_" + fn_line.group(3) + " " + struct_name + " *NONNULL_PTR this_arg" + fn_line.group(5) + "\n"
630                 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", fn_docs)
631         for idx, var_line in enumerate(field_var_lines):
632             if var_line.group(1) not in trait_structs:
633                 write_c(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
634                 write_c("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
635                 write_c("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
636                 write_c("\treturn this_arg->" + var_line.group(2) + ";\n")
637                 write_c("}\n")
638                 dummy_line = var_line.group(1) + " " + struct_name.replace("LDK", "") + "_get_" + var_line.group(2) + " " + struct_name + " *NONNULL_PTR this_arg" + fn_line.group(5) + "\n"
639                 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", fn_docs)
640
641     def map_result(struct_name, res_ty, err_ty):
642         result_types.add(struct_name)
643         human_ty = struct_name.replace("LDKCResult", "Result")
644         with open(f"{sys.argv[3]}/structs/{human_ty}{consts.file_ext}", "w") as out_java_struct:
645             out_java_struct.write(consts.hu_struct_file_prefix)
646             out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
647             out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
648             out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
649             out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
650             out_java_struct.write("\t}\n\n")
651             out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
652             out_java_struct.write("\t\tif (bindings." + struct_name + "_result_ok(ptr)) {\n")
653             out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
654             out_java_struct.write("\t\t} else {\n")
655             out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
656             out_java_struct.write("\t\t}\n")
657             out_java_struct.write("\t}\n")
658
659             res_map = type_mapping_generator.map_type(res_ty + " res", True, None, False, True)
660             err_map = type_mapping_generator.map_type(err_ty + " err", True, None, False, True)
661             can_clone = True
662             if not res_map.is_native_primitive and (res_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
663                 can_clone = False
664             if not err_map.is_native_primitive and (err_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
665                 can_clone = False
666
667             out_java.write("\tpublic static native boolean " + struct_name + "_result_ok(long arg);\n")
668             write_c(consts.c_fn_ty_pfx + "jboolean " + consts.c_fn_name_define_pfx(struct_name + "_result_ok", True) + consts.ptr_c_ty + " arg) {\n")
669             write_c("\treturn ((" + struct_name + "*)arg)->result_ok;\n")
670             write_c("}\n")
671
672             out_java.write("\tpublic static native " + res_map.java_ty + " " + struct_name + "_get_ok(long arg);\n")
673             write_c(consts.c_fn_ty_pfx + res_map.c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_get_ok", True) + consts.ptr_c_ty + " arg) {\n")
674             write_c("\t" + struct_name + " *val = (" + struct_name + "*)(arg & ~1);\n")
675             write_c("\tCHECK(val->result_ok);\n\t")
676             out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
677             if res_map.ret_conv is not None:
678                 write_c(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
679                 write_c(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
680             else:
681                 write_c("return *val->contents.result")
682             write_c(";\n}\n")
683
684             if res_map.java_hu_ty != "void":
685                 out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
686             out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
687             out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
688             if res_map.java_hu_ty == "void":
689                 pass
690             elif res_map.to_hu_conv is not None:
691                 out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + struct_name + "_get_ok(ptr);\n")
692                 out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
693                 out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
694             else:
695                 out_java_struct.write("\t\t\tthis.res = bindings." + struct_name + "_get_ok(ptr);\n")
696             out_java_struct.write("\t\t}\n")
697             out_java_struct.write("\t}\n\n")
698
699             out_java.write("\tpublic static native " + err_map.java_ty + " " + struct_name + "_get_err(long arg);\n")
700             write_c(consts.c_fn_ty_pfx + err_map.c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_get_err", True) + consts.ptr_c_ty + " arg) {\n")
701             write_c("\t" + struct_name + " *val = (" + struct_name + "*)(arg & ~1);\n")
702             write_c("\tCHECK(!val->result_ok);\n\t")
703             out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
704             if err_map.ret_conv is not None:
705                 write_c(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
706                 write_c(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
707             else:
708                 write_c("return *val->contents.err")
709             write_c(";\n}\n")
710
711             if err_map.java_hu_ty != "void":
712                 out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
713             out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
714             out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
715             if err_map.java_hu_ty == "void":
716                 pass
717             elif err_map.to_hu_conv is not None:
718                 out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + struct_name + "_get_err(ptr);\n")
719                 out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
720                 out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
721             else:
722                 out_java_struct.write("\t\t\tthis.err = bindings." + struct_name + "_get_err(ptr);\n")
723             out_java_struct.write("\t\t}\n")
724
725             out_java_struct.write("\t}\n\n")
726
727     def map_tuple(struct_name, field_lines):
728         out_java.write("\tpublic static native long " + struct_name + "_new(")
729         write_c(consts.c_fn_ty_pfx + consts.ptr_c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_new", len(field_lines) > 3))
730         ty_list = []
731         for idx, line in enumerate(field_lines):
732             if idx != 0 and idx < len(field_lines) - 2:
733                 ty_info = java_c_types(line.strip(';'), None)
734                 if idx != 1:
735                     out_java.write(", ")
736                     write_c(", ")
737                 e = chr(ord('a') + idx - 1)
738                 out_java.write(ty_info.java_ty + " " + e)
739                 write_c(ty_info.c_ty + " " + e)
740                 ty_list.append(ty_info)
741         tuple_types[struct_name] = (ty_list, struct_name)
742         out_java.write(");\n")
743         write_c(") {\n")
744         write_c("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
745         for idx, line in enumerate(field_lines):
746             if idx != 0 and idx < len(field_lines) - 2:
747                 ty_info = type_mapping_generator.map_type(line.strip(';'), False, None, False, False)
748                 e = chr(ord('a') + idx - 1)
749                 if ty_info.arg_conv is not None:
750                     write_c("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
751                     write_c("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
752                 else:
753                     write_c("\tret->" + e + " = " + e + ";\n")
754                 if ty_info.arg_conv_cleanup is not None:
755                     write_c("\t//TODO: Really need to call " + ty_info.arg_conv_cleanup + " here\n")
756         write_c("\treturn (uint64_t)ret;\n")
757         write_c("}\n")
758
759         for idx, ty_info in enumerate(ty_list):
760             e = chr(ord('a') + idx)
761             out_java.write("\tpublic static native " + ty_info.java_ty + " " + struct_name + "_get_" + e + "(long ptr);\n")
762             write_c(consts.c_fn_ty_pfx + ty_info.c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_get_" + e, True) + consts.ptr_c_ty + " ptr) {\n")
763             write_c("\t" + struct_name + " *tuple = (" + struct_name + "*)(ptr & ~1);\n")
764             conv_info = type_mapping_generator.map_type_with_info(ty_info, False, None, False, True)
765             if conv_info.ret_conv is not None:
766                 write_c("\t" + conv_info.ret_conv[0].replace("\n", "\n\t") + "tuple->" + e + conv_info.ret_conv[1].replace("\n", "\n\t") + "\n")
767                 write_c("\treturn " + conv_info.ret_conv_name + ";\n")
768             else:
769                 write_c("\treturn tuple->" + e + ";\n")
770             write_c("}\n")
771
772     out_java.write(consts.bindings_header.replace('<git_version_ldk_garbagecollected>', local_git_version))
773
774     with open(f"{sys.argv[3]}/structs/CommonBase{consts.file_ext}", "w") as out_java_struct:
775         out_java_struct.write(consts.common_base)
776
777     block_comment = None
778     last_block_comment = None
779     cur_block_obj = None
780
781     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
782
783     line_indicates_result_regex = re.compile("^   union (LDKCResult_[A-Za-z_0-9]*Ptr) contents;$")
784     line_indicates_vec_regex = re.compile("^   (struct |enum |union )?([A-Za-z_0-9]*) \*data;$")
785     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
786     line_indicates_trait_regex = re.compile("^   (struct |enum |union )?([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
787     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
788     assert(line_indicates_trait_regex.match("   struct LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
789     assert(line_indicates_trait_regex.match("   struct LDKCVec_u8Z (*write)(const void *this_arg);"))
790     line_indicates_trait_clone_regex = re.compile("^   void \(\*cloned\)\(struct ([A-Za-z0-9])* \*NONNULL_PTR new_[A-Za-z0-9]*\);$")
791     assert(line_indicates_trait_clone_regex.match("   void (*cloned)(struct LDKSign *NONNULL_PTR new_Sign);"))
792     line_field_var_regex = re.compile("^   struct ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
793     assert(line_field_var_regex.match("   struct LDKMessageSendEventsProvider MessageSendEventsProvider;"))
794     assert(line_field_var_regex.match("   struct LDKChannelPublicKeys pubkeys;"))
795     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
796     assert(struct_name_regex.match("typedef struct LDKCVec_u8Z {"))
797     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
798
799     union_enum_items = {}
800     result_ptr_struct_items = {}
801     for line in in_h:
802         if block_comment is not None:
803             if line.endswith("*/\n"):
804                 last_block_comment = block_comment.strip("\n")
805                 block_comment = None
806             else:
807                 block_comment = block_comment + line.strip(" /*")
808         elif cur_block_obj is not None:
809             cur_block_obj  = cur_block_obj + line
810             if line.startswith("} "):
811                 field_lines = []
812                 struct_name = None
813                 vec_ty = None
814                 obj_lines = cur_block_obj.split("\n")
815                 is_opaque = False
816                 result_contents = None
817                 is_unitary_enum = False
818                 is_union_enum = False
819                 is_union = False
820                 is_tuple = False
821                 trait_fn_lines = []
822                 field_var_lines = []
823
824                 for idx, struct_line in enumerate(obj_lines):
825                     if struct_line.strip().startswith("/*"):
826                         block_comment = struct_line.strip(" /*")
827                     if block_comment is not None:
828                         if struct_line.endswith("*/"):
829                             last_struct_block_comment = block_comment.strip("\n")
830                             block_comment = None
831                         else:
832                             block_comment = block_comment + "\n" + struct_line.strip(" /*")
833                     else:
834                         struct_name_match = struct_name_regex.match(struct_line)
835                         if struct_name_match is not None:
836                             struct_name = struct_name_match.group(3)
837                             if struct_name_match.group(1) == "enum":
838                                 if not struct_name.endswith("_Tag"):
839                                     is_unitary_enum = True
840                                 else:
841                                     is_union_enum = True
842                             elif struct_name_match.group(1) == "union":
843                                 is_union = True
844                         if line_indicates_opaque_regex.match(struct_line):
845                             is_opaque = True
846                         result_match = line_indicates_result_regex.match(struct_line)
847                         if result_match is not None:
848                             result_contents = result_match.group(1)
849                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
850                         if vec_ty_match is not None and struct_name.startswith("LDKCVec_"):
851                             vec_ty = vec_ty_match.group(2)
852                         elif struct_name.startswith("LDKC2Tuple_") or struct_name.startswith("LDKC3Tuple_"):
853                             is_tuple = True
854                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
855                         if trait_fn_match is not None:
856                             trait_fn_lines.append((last_struct_block_comment, trait_fn_match))
857                         trait_clone_fn_match = line_indicates_trait_clone_regex.match(struct_line)
858                         if trait_clone_fn_match is not None:
859                             trait_fn_lines.append((last_struct_block_comment, "cloned"))
860                         field_var_match = line_field_var_regex.match(struct_line)
861                         if field_var_match is not None:
862                             field_var_lines.append(field_var_match)
863                         field_lines.append(struct_line)
864
865                 assert(struct_name is not None)
866                 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))
867                 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))
868                 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))
869                 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))
870                 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))
871                 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))
872                 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))
873
874                 if is_opaque:
875                     opaque_structs.add(struct_name)
876                     with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "w") as out_java_struct:
877                         out_opaque_struct_human = consts.map_opaque_struct(struct_name, last_block_comment)
878                         last_block_comment = None
879                         out_java_struct.write(out_opaque_struct_human)
880                 elif result_contents is not None:
881                     assert result_contents in result_ptr_struct_items
882                     res_ty, err_ty = result_ptr_struct_items[result_contents]
883                     map_result(struct_name, res_ty, err_ty)
884                 elif struct_name.startswith("LDKCResult_") and struct_name.endswith("ZPtr"):
885                     for line in field_lines:
886                         if line.endswith("*result;"):
887                             res_ty = line[:-8].strip()
888                         elif line.endswith("*err;"):
889                             err_ty = line[:-5].strip()
890                     result_ptr_struct_items[struct_name] = (res_ty, err_ty)
891                     result_types.add(struct_name[:-3])
892                 elif is_tuple:
893                     map_tuple(struct_name, field_lines)
894                 elif vec_ty is not None:
895                     ty_info = type_mapping_generator.map_type(vec_ty + " arr_elem", False, None, False, False)
896                     if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
897                         out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
898                         write_c(consts.c_fn_ty_pfx + consts.ptr_c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_new", True) + ty_info.c_ty + "Array elems) {\n")
899                         write_c("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
900                         write_c("\tret->datalen = " + consts.get_native_arr_len_call[0] + "elems" + consts.get_native_arr_len_call[1] + ";\n")
901                         write_c("\tif (ret->datalen == 0) {\n")
902                         write_c("\t\tret->data = NULL;\n")
903                         write_c("\t} else {\n")
904                         write_c("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
905                         native_arr_ptr_call = consts.get_native_arr_ptr_call(ty_info.ty_info)
906                         write_c("\t\t" + ty_info.c_ty + " *java_elems = " + native_arr_ptr_call[0] + "elems" + native_arr_ptr_call[1] + ";\n")
907                         write_c("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
908                         if ty_info.arg_conv is not None:
909                             write_c("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
910                             write_c("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
911                             write_c("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
912                             assert ty_info.arg_conv_cleanup is None
913                         else:
914                             write_c("\t\t\tret->data[i] = java_elems[i];\n")
915                         write_c("\t\t}\n")
916                         cleanup = consts.release_native_arr_ptr_call(ty_info.ty_info, "elems", "java_elems")
917                         if cleanup is not None:
918                             write_c("\t\t" + cleanup + ";\n")
919                         write_c("\t}\n")
920                         write_c("\treturn (uint64_t)ret;\n")
921                         write_c("}\n")
922
923                     if ty_info.is_native_primitive:
924                         clone_fns.add(struct_name.replace("LDK", "") + "_clone")
925                         write_c("static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n")
926                         write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.c_ty + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
927                         write_c("\tmemcpy(ret.data, orig->data, sizeof(" + ty_info.c_ty + ") * ret.datalen);\n")
928                         write_c("\treturn ret;\n}\n")
929                     elif (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
930                         ty_name = "CVec_" + ty_info.rust_obj.replace("LDK", "") + "Z";
931                         clone_fns.add(ty_name + "_clone")
932                         write_c("static inline " + struct_name + " " + ty_name + "_clone(const " + struct_name + " *orig) {\n")
933                         write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.rust_obj + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
934                         write_c("\tfor (size_t i = 0; i < ret.datalen; i++) {\n")
935                         write_c("\t\tret.data[i] = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&orig->data[i]);\n")
936                         write_c("\t}\n\treturn ret;\n}\n")
937                 elif is_union_enum:
938                     assert(struct_name.endswith("_Tag"))
939                     struct_name = struct_name[:-4]
940                     union_enum_items[struct_name] = {"field_lines": field_lines}
941                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
942                     enum_var_name = struct_name.split("_")
943                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
944                 elif struct_name in union_enum_items:
945                     tuple_variants = {}
946                     elem_items = -1
947                     for line in field_lines:
948                         if line == "      struct {":
949                             elem_items = 0
950                         elif line == "      };":
951                             elem_items = -1
952                         elif elem_items > -1:
953                             line = line.strip()
954                             if line.startswith("struct "):
955                                 line = line[7:]
956                             elif line.startswith("enum "):
957                                 line = line[5:]
958                             split = line.split(" ")
959                             assert len(split) == 2
960                             tuple_variants[split[1].strip(";")] = split[0]
961                             elem_items += 1
962                             if elem_items > 1:
963                                 # We don't currently support tuple variant with more than one element
964                                 assert False
965                     map_complex_enum(struct_name, union_enum_items[struct_name], tuple_variants, last_block_comment)
966                     last_block_comment = None
967                 elif is_unitary_enum:
968                     map_unitary_enum(struct_name, field_lines, last_block_comment)
969                     last_block_comment = None
970                 elif len(trait_fn_lines) > 0:
971                     map_trait(struct_name, field_var_lines, trait_fn_lines, last_block_comment)
972                 elif struct_name == "LDKTxOut":
973                     with open(f"{sys.argv[3]}/structs/TxOut{consts.file_ext}", "w") as out_java_struct:
974                         out_java_struct.write(consts.hu_struct_file_prefix)
975                         out_java_struct.write("public class TxOut extends CommonBase{\n")
976                         out_java_struct.write("\tTxOut(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
977                         out_java_struct.write("\tlong to_c_ptr() { return 0; }\n")
978                         out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
979                         out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
980                         out_java_struct.write("\t\tsuper.finalize();\n")
981                         out_java_struct.write("\t\tif (ptr != 0) { bindings.TxOut_free(ptr); }\n")
982                         out_java_struct.write("\t}\n")
983                         # TODO: TxOut body
984                         out_java_struct.write("}")
985                 else:
986                     pass # Everything remaining is a byte[] or some form
987                 cur_block_obj = None
988         else:
989             fn_ptr = fn_ptr_regex.match(line)
990             fn_ret_arr = fn_ret_arr_regex.match(line)
991             reg_fn = reg_fn_regex.match(line)
992             const_val = const_val_regex.match(line)
993
994             if line.startswith("#include <"):
995                 pass
996             elif line.startswith("/*"):
997                 if not line.endswith("*/\n"):
998                     block_comment = line.strip(" /*")
999             elif line.startswith("typedef enum "):
1000                 cur_block_obj = line
1001             elif line.startswith("typedef struct "):
1002                 cur_block_obj = line
1003             elif line.startswith("typedef union "):
1004                 cur_block_obj = line
1005             elif fn_ptr is not None:
1006                 map_fn(line, fn_ptr, None, None, last_block_comment)
1007                 last_block_comment = None
1008             elif fn_ret_arr is not None:
1009                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None, last_block_comment)
1010                 last_block_comment = None
1011             elif reg_fn is not None:
1012                 map_fn(line, reg_fn, None, None, last_block_comment)
1013                 last_block_comment = None
1014             elif const_val_regex is not None:
1015                 # TODO Map const variables
1016                 pass
1017             else:
1018                 assert(line == "\n")
1019
1020     out_java.write(consts.bindings_footer)
1021     for struct_name in opaque_structs:
1022         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1023             out_java_struct.write("}\n")
1024     for struct_name in trait_structs:
1025         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1026             out_java_struct.write("}\n")
1027     for struct_name in complex_enums:
1028         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '').replace('COption', 'Option')}{consts.file_ext}", "a") as out_java_struct:
1029             out_java_struct.write("}\n")
1030     for struct_name in result_types:
1031         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDKCResult', 'Result')}{consts.file_ext}", "a") as out_java_struct:
1032             out_java_struct.write("}\n")
1033
1034 with open(sys.argv[4], "w") as out_c:
1035     out_c.write(consts.c_file_pfx.replace('<git_version_ldk_garbagecollected>', local_git_version))
1036     out_c.write(consts.init_str())
1037     out_c.write(c_file)
1038 with open(f"{sys.argv[3]}/structs/UtilMethods{consts.file_ext}", "a") as util:
1039     util.write(consts.util_fn_sfx)