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