update tests for new upstream and check null result
[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 = doc.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
602                     arg_tys = []
603                     for idx, arg in enumerate(fn_line.group(5).split(',')):
604                         if arg == "":
605                             continue
606                         arg_conv_info = type_mapping_generator.map_type(arg, True, None, False, False)
607                         arg_tys.append(arg_conv_info)
608                     field_fns.append(TraitMethInfo(fn_line.group(3), is_const, ret_ty_info, arg_tys, fn_docs))
609
610             (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)
611             write_c(out_c_addendum)
612             out_java_trait.write(out_java_trait_addendum)
613             out_java.write(out_java_addendum)
614
615         for fn_docs, fn_line in trait_fn_lines:
616             if fn_line == "cloned":
617                 continue
618             # For now, just disable enabling the _call_log - we don't know how to inverse-map String
619             is_log = fn_line.group(3) == "log" and struct_name == "LDKLogger"
620             if fn_line.group(3) != "free" and fn_line.group(3) != "eq" and not is_log:
621                 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"
622                 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)
623         for idx, var_line in enumerate(field_var_lines):
624             if var_line.group(1) not in trait_structs:
625                 write_c(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
626                 write_c("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
627                 write_c("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
628                 write_c("\treturn this_arg->" + var_line.group(2) + ";\n")
629                 write_c("}\n")
630                 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"
631                 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)
632
633     def map_result(struct_name, res_ty, err_ty):
634         result_types.add(struct_name)
635         human_ty = struct_name.replace("LDKCResult", "Result")
636         with open(f"{sys.argv[3]}/structs/{human_ty}{consts.file_ext}", "w") as out_java_struct:
637             out_java_struct.write(consts.hu_struct_file_prefix)
638             out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
639             out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
640             out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
641             out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
642             out_java_struct.write("\t}\n\n")
643             out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
644             out_java_struct.write("\t\tif (bindings." + struct_name + "_result_ok(ptr)) {\n")
645             out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
646             out_java_struct.write("\t\t} else {\n")
647             out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
648             out_java_struct.write("\t\t}\n")
649             out_java_struct.write("\t}\n")
650
651             res_map = type_mapping_generator.map_type(res_ty + " res", True, None, False, True)
652             err_map = type_mapping_generator.map_type(err_ty + " err", True, None, False, True)
653             can_clone = True
654             if not res_map.is_native_primitive and (res_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
655                 can_clone = False
656             if not err_map.is_native_primitive and (err_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
657                 can_clone = False
658
659             out_java.write("\tpublic static native boolean " + struct_name + "_result_ok(long arg);\n")
660             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")
661             write_c("\treturn ((" + struct_name + "*)arg)->result_ok;\n")
662             write_c("}\n")
663
664             out_java.write("\tpublic static native " + res_map.java_ty + " " + struct_name + "_get_ok(long arg);\n")
665             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")
666             write_c("\t" + struct_name + " *val = (" + struct_name + "*)(arg & ~1);\n")
667             write_c("\tCHECK(val->result_ok);\n\t")
668             out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
669             if res_map.ret_conv is not None:
670                 write_c(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
671                 write_c(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
672             else:
673                 write_c("return *val->contents.result")
674             write_c(";\n}\n")
675
676             if res_map.java_hu_ty != "void":
677                 out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
678             out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
679             out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
680             if res_map.java_hu_ty == "void":
681                 pass
682             elif res_map.to_hu_conv is not None:
683                 out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + struct_name + "_get_ok(ptr);\n")
684                 out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
685                 out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
686             else:
687                 out_java_struct.write("\t\t\tthis.res = bindings." + struct_name + "_get_ok(ptr);\n")
688             out_java_struct.write("\t\t}\n")
689             out_java_struct.write("\t}\n\n")
690
691             out_java.write("\tpublic static native " + err_map.java_ty + " " + struct_name + "_get_err(long arg);\n")
692             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")
693             write_c("\t" + struct_name + " *val = (" + struct_name + "*)(arg & ~1);\n")
694             write_c("\tCHECK(!val->result_ok);\n\t")
695             out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
696             if err_map.ret_conv is not None:
697                 write_c(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
698                 write_c(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
699             else:
700                 write_c("return *val->contents.err")
701             write_c(";\n}\n")
702
703             if err_map.java_hu_ty != "void":
704                 out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
705             out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
706             out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
707             if err_map.java_hu_ty == "void":
708                 pass
709             elif err_map.to_hu_conv is not None:
710                 out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + struct_name + "_get_err(ptr);\n")
711                 out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
712                 out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
713             else:
714                 out_java_struct.write("\t\t\tthis.err = bindings." + struct_name + "_get_err(ptr);\n")
715             out_java_struct.write("\t\t}\n")
716
717             out_java_struct.write("\t}\n\n")
718
719     def map_tuple(struct_name, field_lines):
720         out_java.write("\tpublic static native long " + struct_name + "_new(")
721         write_c(consts.c_fn_ty_pfx + consts.ptr_c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_new", len(field_lines) > 3))
722         ty_list = []
723         for idx, line in enumerate(field_lines):
724             if idx != 0 and idx < len(field_lines) - 2:
725                 ty_info = java_c_types(line.strip(';'), None)
726                 if idx != 1:
727                     out_java.write(", ")
728                     write_c(", ")
729                 e = chr(ord('a') + idx - 1)
730                 out_java.write(ty_info.java_ty + " " + e)
731                 write_c(ty_info.c_ty + " " + e)
732                 ty_list.append(ty_info)
733         tuple_types[struct_name] = (ty_list, struct_name)
734         out_java.write(");\n")
735         write_c(") {\n")
736         write_c("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
737         for idx, line in enumerate(field_lines):
738             if idx != 0 and idx < len(field_lines) - 2:
739                 ty_info = type_mapping_generator.map_type(line.strip(';'), False, None, False, False)
740                 e = chr(ord('a') + idx - 1)
741                 if ty_info.arg_conv is not None:
742                     write_c("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
743                     write_c("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
744                 else:
745                     write_c("\tret->" + e + " = " + e + ";\n")
746                 if ty_info.arg_conv_cleanup is not None:
747                     write_c("\t//TODO: Really need to call " + ty_info.arg_conv_cleanup + " here\n")
748         write_c("\treturn (uint64_t)ret;\n")
749         write_c("}\n")
750
751         for idx, ty_info in enumerate(ty_list):
752             e = chr(ord('a') + idx)
753             out_java.write("\tpublic static native " + ty_info.java_ty + " " + struct_name + "_get_" + e + "(long ptr);\n")
754             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")
755             write_c("\t" + struct_name + " *tuple = (" + struct_name + "*)(ptr & ~1);\n")
756             conv_info = type_mapping_generator.map_type_with_info(ty_info, False, None, False, True)
757             if conv_info.ret_conv is not None:
758                 write_c("\t" + conv_info.ret_conv[0].replace("\n", "\n\t") + "tuple->" + e + conv_info.ret_conv[1].replace("\n", "\n\t") + "\n")
759                 write_c("\treturn " + conv_info.ret_conv_name + ";\n")
760             else:
761                 write_c("\treturn tuple->" + e + ";\n")
762             write_c("}\n")
763
764     out_java.write(consts.bindings_header.replace('<git_version_ldk_garbagecollected>', local_git_version))
765
766     with open(f"{sys.argv[3]}/structs/CommonBase{consts.file_ext}", "w") as out_java_struct:
767         out_java_struct.write(consts.common_base)
768
769     block_comment = None
770     last_block_comment = None
771     cur_block_obj = None
772
773     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
774
775     line_indicates_result_regex = re.compile("^   union (LDKCResult_[A-Za-z_0-9]*Ptr) contents;$")
776     line_indicates_vec_regex = re.compile("^   (struct |enum |union )?([A-Za-z_0-9]*) \*data;$")
777     line_indicates_opaque_regex = re.compile("^   bool is_owned;$")
778     line_indicates_trait_regex = re.compile("^   (struct |enum |union )?([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
779     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
780     assert(line_indicates_trait_regex.match("   struct LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
781     assert(line_indicates_trait_regex.match("   struct LDKCVec_u8Z (*write)(const void *this_arg);"))
782     line_indicates_trait_clone_regex = re.compile("^   void \(\*cloned\)\(struct ([A-Za-z0-9])* \*NONNULL_PTR new_[A-Za-z0-9]*\);$")
783     assert(line_indicates_trait_clone_regex.match("   void (*cloned)(struct LDKSign *NONNULL_PTR new_Sign);"))
784     line_field_var_regex = re.compile("^   struct ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
785     assert(line_field_var_regex.match("   struct LDKMessageSendEventsProvider MessageSendEventsProvider;"))
786     assert(line_field_var_regex.match("   struct LDKChannelPublicKeys pubkeys;"))
787     struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
788     assert(struct_name_regex.match("typedef struct LDKCVec_u8Z {"))
789     assert(struct_name_regex.match("typedef enum LDKNetwork {"))
790
791     union_enum_items = {}
792     result_ptr_struct_items = {}
793     for line in in_h:
794         if block_comment is not None:
795             if line.endswith("*/\n"):
796                 last_block_comment = block_comment.strip("\n")
797                 block_comment = None
798             else:
799                 block_comment = block_comment + line.strip(" /*")
800         elif cur_block_obj is not None:
801             cur_block_obj  = cur_block_obj + line
802             if line.startswith("} "):
803                 field_lines = []
804                 struct_name = None
805                 vec_ty = None
806                 obj_lines = cur_block_obj.split("\n")
807                 is_opaque = False
808                 result_contents = None
809                 is_unitary_enum = False
810                 is_union_enum = False
811                 is_union = False
812                 is_tuple = False
813                 trait_fn_lines = []
814                 field_var_lines = []
815
816                 for idx, struct_line in enumerate(obj_lines):
817                     if struct_line.strip().startswith("/*"):
818                         block_comment = struct_line.strip(" /*")
819                     if block_comment is not None:
820                         if struct_line.endswith("*/"):
821                             last_struct_block_comment = block_comment.strip("\n")
822                             block_comment = None
823                         else:
824                             block_comment = block_comment + "\n" + struct_line.strip(" /*")
825                     else:
826                         struct_name_match = struct_name_regex.match(struct_line)
827                         if struct_name_match is not None:
828                             struct_name = struct_name_match.group(3)
829                             if struct_name_match.group(1) == "enum":
830                                 if not struct_name.endswith("_Tag"):
831                                     is_unitary_enum = True
832                                 else:
833                                     is_union_enum = True
834                             elif struct_name_match.group(1) == "union":
835                                 is_union = True
836                         if line_indicates_opaque_regex.match(struct_line):
837                             is_opaque = True
838                         result_match = line_indicates_result_regex.match(struct_line)
839                         if result_match is not None:
840                             result_contents = result_match.group(1)
841                         vec_ty_match = line_indicates_vec_regex.match(struct_line)
842                         if vec_ty_match is not None and struct_name.startswith("LDKCVec_"):
843                             vec_ty = vec_ty_match.group(2)
844                         elif struct_name.startswith("LDKC2Tuple_") or struct_name.startswith("LDKC3Tuple_"):
845                             is_tuple = True
846                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
847                         if trait_fn_match is not None:
848                             trait_fn_lines.append((last_struct_block_comment, trait_fn_match))
849                         trait_clone_fn_match = line_indicates_trait_clone_regex.match(struct_line)
850                         if trait_clone_fn_match is not None:
851                             trait_fn_lines.append((last_struct_block_comment, "cloned"))
852                         field_var_match = line_field_var_regex.match(struct_line)
853                         if field_var_match is not None:
854                             field_var_lines.append(field_var_match)
855                         field_lines.append(struct_line)
856
857                 assert(struct_name is not None)
858                 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))
859                 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))
860                 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))
861                 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))
862                 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))
863                 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))
864                 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))
865
866                 if is_opaque:
867                     opaque_structs.add(struct_name)
868                     with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "w") as out_java_struct:
869                         out_opaque_struct_human = consts.map_opaque_struct(struct_name, last_block_comment)
870                         last_block_comment = None
871                         out_java_struct.write(out_opaque_struct_human)
872                 elif result_contents is not None:
873                     assert result_contents in result_ptr_struct_items
874                     res_ty, err_ty = result_ptr_struct_items[result_contents]
875                     map_result(struct_name, res_ty, err_ty)
876                 elif struct_name.startswith("LDKCResult_") and struct_name.endswith("ZPtr"):
877                     for line in field_lines:
878                         if line.endswith("*result;"):
879                             res_ty = line[:-8].strip()
880                         elif line.endswith("*err;"):
881                             err_ty = line[:-5].strip()
882                     result_ptr_struct_items[struct_name] = (res_ty, err_ty)
883                     result_types.add(struct_name[:-3])
884                 elif is_tuple:
885                     map_tuple(struct_name, field_lines)
886                 elif vec_ty is not None:
887                     ty_info = type_mapping_generator.map_type(vec_ty + " arr_elem", False, None, False, False)
888                     if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
889                         out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
890                         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")
891                         write_c("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
892                         write_c("\tret->datalen = " + consts.get_native_arr_len_call[0] + "elems" + consts.get_native_arr_len_call[1] + ";\n")
893                         write_c("\tif (ret->datalen == 0) {\n")
894                         write_c("\t\tret->data = NULL;\n")
895                         write_c("\t} else {\n")
896                         write_c("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
897                         native_arr_ptr_call = consts.get_native_arr_ptr_call(ty_info.ty_info)
898                         write_c("\t\t" + ty_info.c_ty + " *java_elems = " + native_arr_ptr_call[0] + "elems" + native_arr_ptr_call[1] + ";\n")
899                         write_c("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
900                         if ty_info.arg_conv is not None:
901                             write_c("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
902                             write_c("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
903                             write_c("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
904                             assert ty_info.arg_conv_cleanup is None
905                         else:
906                             write_c("\t\t\tret->data[i] = java_elems[i];\n")
907                         write_c("\t\t}\n")
908                         cleanup = consts.release_native_arr_ptr_call(ty_info.ty_info, "elems", "java_elems")
909                         if cleanup is not None:
910                             write_c("\t\t" + cleanup + ";\n")
911                         write_c("\t}\n")
912                         write_c("\treturn (uint64_t)ret;\n")
913                         write_c("}\n")
914
915                     if ty_info.is_native_primitive:
916                         clone_fns.add(struct_name.replace("LDK", "") + "_clone")
917                         write_c("static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n")
918                         write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.c_ty + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
919                         write_c("\tmemcpy(ret.data, orig->data, sizeof(" + ty_info.c_ty + ") * ret.datalen);\n")
920                         write_c("\treturn ret;\n}\n")
921                     elif (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
922                         ty_name = "CVec_" + ty_info.rust_obj.replace("LDK", "") + "Z";
923                         clone_fns.add(ty_name + "_clone")
924                         write_c("static inline " + struct_name + " " + ty_name + "_clone(const " + struct_name + " *orig) {\n")
925                         write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.rust_obj + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
926                         write_c("\tfor (size_t i = 0; i < ret.datalen; i++) {\n")
927                         write_c("\t\tret.data[i] = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&orig->data[i]);\n")
928                         write_c("\t}\n\treturn ret;\n}\n")
929                 elif is_union_enum:
930                     assert(struct_name.endswith("_Tag"))
931                     struct_name = struct_name[:-4]
932                     union_enum_items[struct_name] = {"field_lines": field_lines}
933                 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
934                     enum_var_name = struct_name.split("_")
935                     union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
936                 elif struct_name in union_enum_items:
937                     tuple_variants = {}
938                     elem_items = -1
939                     for line in field_lines:
940                         if line == "      struct {":
941                             elem_items = 0
942                         elif line == "      };":
943                             elem_items = -1
944                         elif elem_items > -1:
945                             line = line.strip()
946                             if line.startswith("struct "):
947                                 line = line[7:]
948                             elif line.startswith("enum "):
949                                 line = line[5:]
950                             split = line.split(" ")
951                             assert len(split) == 2
952                             tuple_variants[split[1].strip(";")] = split[0]
953                             elem_items += 1
954                             if elem_items > 1:
955                                 # We don't currently support tuple variant with more than one element
956                                 assert False
957                     map_complex_enum(struct_name, union_enum_items[struct_name], tuple_variants, last_block_comment)
958                     last_block_comment = None
959                 elif is_unitary_enum:
960                     map_unitary_enum(struct_name, field_lines, last_block_comment)
961                     last_block_comment = None
962                 elif len(trait_fn_lines) > 0:
963                     map_trait(struct_name, field_var_lines, trait_fn_lines, last_block_comment)
964                 elif struct_name == "LDKTxOut":
965                     with open(f"{sys.argv[3]}/structs/TxOut{consts.file_ext}", "w") as out_java_struct:
966                         out_java_struct.write(consts.hu_struct_file_prefix)
967                         out_java_struct.write("public class TxOut extends CommonBase{\n")
968                         out_java_struct.write("\tTxOut(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
969                         out_java_struct.write("\tlong to_c_ptr() { return 0; }\n")
970                         out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
971                         out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
972                         out_java_struct.write("\t\tsuper.finalize();\n")
973                         out_java_struct.write("\t\tif (ptr != 0) { bindings.TxOut_free(ptr); }\n")
974                         out_java_struct.write("\t}\n")
975                         # TODO: TxOut body
976                         out_java_struct.write("}")
977                 else:
978                     pass # Everything remaining is a byte[] or some form
979                 cur_block_obj = None
980         else:
981             fn_ptr = fn_ptr_regex.match(line)
982             fn_ret_arr = fn_ret_arr_regex.match(line)
983             reg_fn = reg_fn_regex.match(line)
984             const_val = const_val_regex.match(line)
985
986             if line.startswith("#include <"):
987                 pass
988             elif line.startswith("/*"):
989                 if not line.endswith("*/\n"):
990                     block_comment = line.strip(" /*")
991             elif line.startswith("typedef enum "):
992                 cur_block_obj = line
993             elif line.startswith("typedef struct "):
994                 cur_block_obj = line
995             elif line.startswith("typedef union "):
996                 cur_block_obj = line
997             elif fn_ptr is not None:
998                 map_fn(line, fn_ptr, None, None, last_block_comment)
999                 last_block_comment = None
1000             elif fn_ret_arr is not None:
1001                 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None, last_block_comment)
1002                 last_block_comment = None
1003             elif reg_fn is not None:
1004                 map_fn(line, reg_fn, None, None, last_block_comment)
1005                 last_block_comment = None
1006             elif const_val_regex is not None:
1007                 # TODO Map const variables
1008                 pass
1009             else:
1010                 assert(line == "\n")
1011
1012     out_java.write(consts.bindings_footer)
1013     for struct_name in opaque_structs:
1014         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1015             out_java_struct.write("}\n")
1016     for struct_name in trait_structs:
1017         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1018             out_java_struct.write("}\n")
1019     for struct_name in complex_enums:
1020         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '').replace('COption', 'Option')}{consts.file_ext}", "a") as out_java_struct:
1021             out_java_struct.write("}\n")
1022     for struct_name in result_types:
1023         with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDKCResult', 'Result')}{consts.file_ext}", "a") as out_java_struct:
1024             out_java_struct.write("}\n")
1025
1026 with open(sys.argv[4], "w") as out_c:
1027     out_c.write(consts.c_file_pfx.replace('<git_version_ldk_garbagecollected>', local_git_version))
1028     out_c.write(consts.init_str())
1029     out_c.write(c_file)
1030 with open(f"{sys.argv[3]}/structs/UtilMethods{consts.file_ext}", "a") as util:
1031     util.write(consts.util_fn_sfx)