2 import os, sys, re, subprocess
5 print("USAGE: /path/to/lightning.h /path/to/bindings/output /path/to/bindings/ /path/to/bindings/output.c debug lang")
8 if sys.argv[5] == "false":
10 elif sys.argv[5] == "true":
13 print("debug should be true or false and indicates whether to track allocations and ensure we don't leak")
17 if sys.argv[6] == "java" or sys.argv[6] == "android":
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
30 print("Only java or typescript can be set for lang")
34 consts = Consts(DEBUG, target=target)
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()
40 from bindingstypes import *
47 def camel_to_snake(s):
48 # Convert camel case to snake case, in a way that appears to match cbindgen
54 if lastchar.isupper():
55 if not char.isupper() and not lastund:
60 ret = ret + lastchar.lower()
63 if char.isupper() and not lastund:
71 return (ret + lastchar.lower()).strip("_")
73 def doc_to_params_ret_nullable(doc):
78 for line in doc.splitlines():
79 if "may be NULL or all-0s to represent None" not in line:
81 if "Note that the return value" in line:
83 elif "Note that " in line:
84 param = line.split("Note that ")[1].split(" ")[0]
86 return (params, ret_null)
90 opaque_structs = set()
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 "):
103 if fn_arg.startswith("const "):
106 if fn_arg.startswith("struct "):
108 if fn_arg.startswith("enum "):
110 nonnull_ptr = "NONNULL_PTR" in fn_arg
111 fn_arg = fn_arg.replace("NONNULL_PTR", "")
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"
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"
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"
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"
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"
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"
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"
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"
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"
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:])
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:])
188 elif fn_arg.startswith("LDKCVec_"):
191 fn_arg = fn_arg.replace("*", "")
194 tyn = fn_arg[8:].split(" ")
195 assert tyn[0].endswith("Z")
199 new_arg = "LDK" + tyn[0][:-1]
201 new_arg = new_arg + " " + a
202 res = java_c_types(new_arg, ret_arr_len)
204 assert java_c_types_none_allowed
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)
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)
222 java_type_plural = None
223 if fn_arg.startswith("void"):
227 fn_arg = fn_arg[4:].strip()
229 elif fn_arg.startswith("bool"):
233 fn_arg = fn_arg[4:].strip()
235 elif fn_arg.startswith("uint8_t"):
236 mapped_type = consts.c_type_map['uint8_t']
237 java_ty = mapped_type[0]
240 fn_arg = fn_arg[7:].strip()
242 elif fn_arg.startswith("LDKu5"):
243 java_ty = consts.c_type_map['uint8_t'][0]
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]
254 fn_arg = fn_arg[8:].strip()
256 elif fn_arg.startswith("uint32_t"):
257 mapped_type = consts.c_type_map['uint32_t']
258 java_ty = mapped_type[0]
261 fn_arg = fn_arg[8:].strip()
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]
268 if fn_arg.startswith("uint64_t"):
270 fn_arg = fn_arg[8:].strip()
273 rust_obj = "uintptr_t"
274 fn_arg = fn_arg[9:].strip()
276 elif is_const and fn_arg.startswith("char *"):
279 fn_ty_arg = "Ljava/lang/String;"
280 fn_arg = fn_arg[6:].strip()
281 elif fn_arg.startswith("LDKStr"):
285 fn_ty_arg = "Ljava/lang/String;"
286 fn_arg = fn_arg[6:].strip()
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:]
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
306 for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][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
313 java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
315 java_hu_ty = java_hu_ty + ty_info.java_hu_ty
316 java_hu_ty = java_hu_ty + ">"
318 fn_arg = ma.group(2).strip()
319 rust_obj = ma.group(1).strip()
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
328 for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][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
335 java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
337 java_hu_ty = java_hu_ty + ty_info.java_hu_ty
338 java_hu_ty = java_hu_ty + ">"
340 fn_arg = ma.group(2).strip()
341 rust_obj = ma.group(1).strip()
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", "")
348 fn_arg = ma.group(2).strip()
349 rust_obj = ma.group(1).strip()
352 if fn_arg.startswith(" *") or fn_arg.startswith("*"):
353 fn_arg = fn_arg.replace("*", "").strip()
355 c_ty = consts.ptr_c_ty
356 java_ty = consts.ptr_native_ty
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)
363 # is there a special case for plurals?
364 if len(mapped_type) == 2:
365 java_ty = mapped_type[1]
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)
378 if java_hu_ty is None:
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)
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]*)\((.*)\);$")
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)
392 with open(sys.argv[1]) as 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))
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)
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
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")
414 java_c_types_none_allowed = False # C structs created by cbindgen are declared in dependency order
416 with open(f"{sys.argv[3]}/structs/UtilMethods{consts.file_ext}", "a") as util:
417 util.write(consts.util_fn_pfx)
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(',')
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"
432 struct_meth = method_name.split("_")[0]
434 return_type_info = type_mapping_generator.map_type(method_return_type.strip() + " ret", True, ret_arr_len, False, False)
436 (params_nullable, ret_nullable) = doc_to_params_ret_nullable(doc_comment)
438 return_type_info.nullable = True
441 default_constructor_args = {}
443 takes_self_ptr = False
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:
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:
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.
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
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)
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")
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)
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"))
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")
520 out_java_struct.write("\t\t// " + line.strip() + "\n")
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):
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)
538 out_java_enum.write(native_file_out)
539 out_java.write(native_out)
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)
546 tag_field_lines = union_enum_items["field_lines"]
547 for idx, struct_line in enumerate(tag_field_lines):
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 == "")
557 variant_name = struct_line.strip(' ,')[len(struct_name) + 1:]
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))
569 enum_variants.append(ComplexEnumVariantInfo(variant_name, fields, True))
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)
574 out_java_enum.write(out_java_enum_addendum)
575 out_java.write(out_java_addendum)
576 write_c(out_c_addendum)
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:
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)])
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
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))
599 ret_ty_info = type_mapping_generator.map_type(fn_line.group(2).strip() + " ret", True, None, False, False)
600 is_const = fn_line.group(4) is not None
601 (nullable_params, ret_nullable) = doc_to_params_ret_nullable(fn_docs)
603 assert False # This isn't yet handled on the Java side
604 ret_ty_info.nullable = True
607 for idx, arg in enumerate(fn_line.group(5).split(',')):
610 arg_conv_info = type_mapping_generator.map_type(arg, True, None, False, False)
611 if arg_conv_info.arg_name in nullable_params:
612 # Types that are actually null instead of all-0s aren't yet handled on the Java side:
613 assert arg_conv_info.rust_obj == "LDKPublicKey"
614 arg_conv_info.nullable = True
615 arg_tys.append(arg_conv_info)
616 field_fns.append(TraitMethInfo(fn_line.group(3), is_const, ret_ty_info, arg_tys, fn_docs))
618 (out_java_addendum, out_java_trait_addendum, out_c_addendum) = consts.native_c_map_trait(struct_name, field_var_convs, flattened_field_var_convs, field_fns, trait_doc_comment)
619 write_c(out_c_addendum)
620 out_java_trait.write(out_java_trait_addendum)
621 out_java.write(out_java_addendum)
623 for fn_docs, fn_line in trait_fn_lines:
624 if fn_line == "cloned":
626 # For now, just disable enabling the _call_log - we don't know how to inverse-map String
627 is_log = fn_line.group(3) == "log" and struct_name == "LDKLogger"
628 if fn_line.group(3) != "free" and fn_line.group(3) != "eq" and not is_log:
629 dummy_line = fn_line.group(2) + struct_name.replace("LDK", "") + "_" + fn_line.group(3) + " " + struct_name + " *NONNULL_PTR this_arg" + fn_line.group(5) + "\n"
630 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(this_arg_conv->" + fn_line.group(3) + ")(this_arg_conv->this_arg", fn_docs)
631 for idx, var_line in enumerate(field_var_lines):
632 if var_line.group(1) not in trait_structs:
633 write_c(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
634 write_c("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
635 write_c("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
636 write_c("\treturn this_arg->" + var_line.group(2) + ";\n")
638 dummy_line = var_line.group(1) + " " + struct_name.replace("LDK", "") + "_get_" + var_line.group(2) + " " + struct_name + " *NONNULL_PTR this_arg" + fn_line.group(5) + "\n"
639 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, struct_name + "_set_get_" + var_line.group(2) + "(this_arg_conv", fn_docs)
641 def map_result(struct_name, res_ty, err_ty):
642 result_types.add(struct_name)
643 human_ty = struct_name.replace("LDKCResult", "Result")
644 with open(f"{sys.argv[3]}/structs/{human_ty}{consts.file_ext}", "w") as out_java_struct:
645 out_java_struct.write(consts.hu_struct_file_prefix)
646 out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
647 out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
648 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
649 out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
650 out_java_struct.write("\t}\n\n")
651 out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
652 out_java_struct.write("\t\tif (bindings." + struct_name + "_result_ok(ptr)) {\n")
653 out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
654 out_java_struct.write("\t\t} else {\n")
655 out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
656 out_java_struct.write("\t\t}\n")
657 out_java_struct.write("\t}\n")
659 res_map = type_mapping_generator.map_type(res_ty + " res", True, None, False, True)
660 err_map = type_mapping_generator.map_type(err_ty + " err", True, None, False, True)
662 if not res_map.is_native_primitive and (res_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
664 if not err_map.is_native_primitive and (err_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
667 out_java.write("\tpublic static native boolean " + struct_name + "_result_ok(long arg);\n")
668 write_c(consts.c_fn_ty_pfx + "jboolean " + consts.c_fn_name_define_pfx(struct_name + "_result_ok", True) + consts.ptr_c_ty + " arg) {\n")
669 write_c("\treturn ((" + struct_name + "*)arg)->result_ok;\n")
672 out_java.write("\tpublic static native " + res_map.java_ty + " " + struct_name + "_get_ok(long arg);\n")
673 write_c(consts.c_fn_ty_pfx + res_map.c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_get_ok", True) + consts.ptr_c_ty + " arg) {\n")
674 write_c("\t" + struct_name + " *val = (" + struct_name + "*)(arg & ~1);\n")
675 write_c("\tCHECK(val->result_ok);\n\t")
676 out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
677 if res_map.ret_conv is not None:
678 write_c(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
679 write_c(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
681 write_c("return *val->contents.result")
684 if res_map.java_hu_ty != "void":
685 out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
686 out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
687 out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
688 if res_map.java_hu_ty == "void":
690 elif res_map.to_hu_conv is not None:
691 out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + struct_name + "_get_ok(ptr);\n")
692 out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
693 out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
695 out_java_struct.write("\t\t\tthis.res = bindings." + struct_name + "_get_ok(ptr);\n")
696 out_java_struct.write("\t\t}\n")
697 out_java_struct.write("\t}\n\n")
699 out_java.write("\tpublic static native " + err_map.java_ty + " " + struct_name + "_get_err(long arg);\n")
700 write_c(consts.c_fn_ty_pfx + err_map.c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_get_err", True) + consts.ptr_c_ty + " arg) {\n")
701 write_c("\t" + struct_name + " *val = (" + struct_name + "*)(arg & ~1);\n")
702 write_c("\tCHECK(!val->result_ok);\n\t")
703 out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
704 if err_map.ret_conv is not None:
705 write_c(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
706 write_c(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
708 write_c("return *val->contents.err")
711 if err_map.java_hu_ty != "void":
712 out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
713 out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
714 out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
715 if err_map.java_hu_ty == "void":
717 elif err_map.to_hu_conv is not None:
718 out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + struct_name + "_get_err(ptr);\n")
719 out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
720 out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
722 out_java_struct.write("\t\t\tthis.err = bindings." + struct_name + "_get_err(ptr);\n")
723 out_java_struct.write("\t\t}\n")
725 out_java_struct.write("\t}\n\n")
727 def map_tuple(struct_name, field_lines):
728 out_java.write("\tpublic static native long " + struct_name + "_new(")
729 write_c(consts.c_fn_ty_pfx + consts.ptr_c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_new", len(field_lines) > 3))
731 for idx, line in enumerate(field_lines):
732 if idx != 0 and idx < len(field_lines) - 2:
733 ty_info = java_c_types(line.strip(';'), None)
737 e = chr(ord('a') + idx - 1)
738 out_java.write(ty_info.java_ty + " " + e)
739 write_c(ty_info.c_ty + " " + e)
740 ty_list.append(ty_info)
741 tuple_types[struct_name] = (ty_list, struct_name)
742 out_java.write(");\n")
744 write_c("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
745 for idx, line in enumerate(field_lines):
746 if idx != 0 and idx < len(field_lines) - 2:
747 ty_info = type_mapping_generator.map_type(line.strip(';'), False, None, False, False)
748 e = chr(ord('a') + idx - 1)
749 if ty_info.arg_conv is not None:
750 write_c("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
751 write_c("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
753 write_c("\tret->" + e + " = " + e + ";\n")
754 if ty_info.arg_conv_cleanup is not None:
755 write_c("\t//TODO: Really need to call " + ty_info.arg_conv_cleanup + " here\n")
756 write_c("\treturn (uint64_t)ret;\n")
759 for idx, ty_info in enumerate(ty_list):
760 e = chr(ord('a') + idx)
761 out_java.write("\tpublic static native " + ty_info.java_ty + " " + struct_name + "_get_" + e + "(long ptr);\n")
762 write_c(consts.c_fn_ty_pfx + ty_info.c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_get_" + e, True) + consts.ptr_c_ty + " ptr) {\n")
763 write_c("\t" + struct_name + " *tuple = (" + struct_name + "*)(ptr & ~1);\n")
764 conv_info = type_mapping_generator.map_type_with_info(ty_info, False, None, False, True)
765 if conv_info.ret_conv is not None:
766 write_c("\t" + conv_info.ret_conv[0].replace("\n", "\n\t") + "tuple->" + e + conv_info.ret_conv[1].replace("\n", "\n\t") + "\n")
767 write_c("\treturn " + conv_info.ret_conv_name + ";\n")
769 write_c("\treturn tuple->" + e + ";\n")
772 out_java.write(consts.bindings_header.replace('<git_version_ldk_garbagecollected>', local_git_version))
774 with open(f"{sys.argv[3]}/structs/CommonBase{consts.file_ext}", "w") as out_java_struct:
775 out_java_struct.write(consts.common_base)
778 last_block_comment = None
781 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
783 line_indicates_result_regex = re.compile("^ union (LDKCResult_[A-Za-z_0-9]*Ptr) contents;$")
784 line_indicates_vec_regex = re.compile("^ (struct |enum |union )?([A-Za-z_0-9]*) \*data;$")
785 line_indicates_opaque_regex = re.compile("^ bool is_owned;$")
786 line_indicates_trait_regex = re.compile("^ (struct |enum |union )?([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
787 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
788 assert(line_indicates_trait_regex.match(" struct LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
789 assert(line_indicates_trait_regex.match(" struct LDKCVec_u8Z (*write)(const void *this_arg);"))
790 line_indicates_trait_clone_regex = re.compile("^ void \(\*cloned\)\(struct ([A-Za-z0-9])* \*NONNULL_PTR new_[A-Za-z0-9]*\);$")
791 assert(line_indicates_trait_clone_regex.match(" void (*cloned)(struct LDKSign *NONNULL_PTR new_Sign);"))
792 line_field_var_regex = re.compile("^ struct ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
793 assert(line_field_var_regex.match(" struct LDKMessageSendEventsProvider MessageSendEventsProvider;"))
794 assert(line_field_var_regex.match(" struct LDKChannelPublicKeys pubkeys;"))
795 struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
796 assert(struct_name_regex.match("typedef struct LDKCVec_u8Z {"))
797 assert(struct_name_regex.match("typedef enum LDKNetwork {"))
799 union_enum_items = {}
800 result_ptr_struct_items = {}
802 if block_comment is not None:
803 if line.endswith("*/\n"):
804 last_block_comment = block_comment.strip("\n")
807 block_comment = block_comment + line.strip(" /*")
808 elif cur_block_obj is not None:
809 cur_block_obj = cur_block_obj + line
810 if line.startswith("} "):
814 obj_lines = cur_block_obj.split("\n")
816 result_contents = None
817 is_unitary_enum = False
818 is_union_enum = False
824 for idx, struct_line in enumerate(obj_lines):
825 if struct_line.strip().startswith("/*"):
826 block_comment = struct_line.strip(" /*")
827 if block_comment is not None:
828 if struct_line.endswith("*/"):
829 last_struct_block_comment = block_comment.strip("\n")
832 block_comment = block_comment + "\n" + struct_line.strip(" /*")
834 struct_name_match = struct_name_regex.match(struct_line)
835 if struct_name_match is not None:
836 struct_name = struct_name_match.group(3)
837 if struct_name_match.group(1) == "enum":
838 if not struct_name.endswith("_Tag"):
839 is_unitary_enum = True
842 elif struct_name_match.group(1) == "union":
844 if line_indicates_opaque_regex.match(struct_line):
846 result_match = line_indicates_result_regex.match(struct_line)
847 if result_match is not None:
848 result_contents = result_match.group(1)
849 vec_ty_match = line_indicates_vec_regex.match(struct_line)
850 if vec_ty_match is not None and struct_name.startswith("LDKCVec_"):
851 vec_ty = vec_ty_match.group(2)
852 elif struct_name.startswith("LDKC2Tuple_") or struct_name.startswith("LDKC3Tuple_"):
854 trait_fn_match = line_indicates_trait_regex.match(struct_line)
855 if trait_fn_match is not None:
856 trait_fn_lines.append((last_struct_block_comment, trait_fn_match))
857 trait_clone_fn_match = line_indicates_trait_clone_regex.match(struct_line)
858 if trait_clone_fn_match is not None:
859 trait_fn_lines.append((last_struct_block_comment, "cloned"))
860 field_var_match = line_field_var_regex.match(struct_line)
861 if field_var_match is not None:
862 field_var_lines.append(field_var_match)
863 field_lines.append(struct_line)
865 assert(struct_name is not None)
866 assert(len(trait_fn_lines) == 0 or not (is_opaque or is_unitary_enum or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
867 assert(not is_opaque or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
868 assert(not is_unitary_enum or not (len(trait_fn_lines) != 0 or is_opaque or is_union_enum or is_union or result_contents is not None or vec_ty is not None))
869 assert(not is_union_enum or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_opaque or is_union or result_contents is not None or vec_ty is not None))
870 assert(not is_union or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or result_contents is not None or vec_ty is not None))
871 assert(result_contents is None or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or vec_ty is not None))
872 assert(vec_ty is None or not (len(trait_fn_lines) != 0 or is_unitary_enum or is_union_enum or is_opaque or is_union or result_contents is not None))
875 opaque_structs.add(struct_name)
876 with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "w") as out_java_struct:
877 out_opaque_struct_human = consts.map_opaque_struct(struct_name, last_block_comment)
878 last_block_comment = None
879 out_java_struct.write(out_opaque_struct_human)
880 elif result_contents is not None:
881 assert result_contents in result_ptr_struct_items
882 res_ty, err_ty = result_ptr_struct_items[result_contents]
883 map_result(struct_name, res_ty, err_ty)
884 elif struct_name.startswith("LDKCResult_") and struct_name.endswith("ZPtr"):
885 for line in field_lines:
886 if line.endswith("*result;"):
887 res_ty = line[:-8].strip()
888 elif line.endswith("*err;"):
889 err_ty = line[:-5].strip()
890 result_ptr_struct_items[struct_name] = (res_ty, err_ty)
891 result_types.add(struct_name[:-3])
893 map_tuple(struct_name, field_lines)
894 elif vec_ty is not None:
895 ty_info = type_mapping_generator.map_type(vec_ty + " arr_elem", False, None, False, False)
896 if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
897 out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
898 write_c(consts.c_fn_ty_pfx + consts.ptr_c_ty + " " + consts.c_fn_name_define_pfx(struct_name + "_new", True) + ty_info.c_ty + "Array elems) {\n")
899 write_c("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
900 write_c("\tret->datalen = " + consts.get_native_arr_len_call[0] + "elems" + consts.get_native_arr_len_call[1] + ";\n")
901 write_c("\tif (ret->datalen == 0) {\n")
902 write_c("\t\tret->data = NULL;\n")
903 write_c("\t} else {\n")
904 write_c("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
905 native_arr_ptr_call = consts.get_native_arr_ptr_call(ty_info.ty_info)
906 write_c("\t\t" + ty_info.c_ty + " *java_elems = " + native_arr_ptr_call[0] + "elems" + native_arr_ptr_call[1] + ";\n")
907 write_c("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
908 if ty_info.arg_conv is not None:
909 write_c("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
910 write_c("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
911 write_c("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
912 assert ty_info.arg_conv_cleanup is None
914 write_c("\t\t\tret->data[i] = java_elems[i];\n")
916 cleanup = consts.release_native_arr_ptr_call(ty_info.ty_info, "elems", "java_elems")
917 if cleanup is not None:
918 write_c("\t\t" + cleanup + ";\n")
920 write_c("\treturn (uint64_t)ret;\n")
923 if ty_info.is_native_primitive:
924 clone_fns.add(struct_name.replace("LDK", "") + "_clone")
925 write_c("static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n")
926 write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.c_ty + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
927 write_c("\tmemcpy(ret.data, orig->data, sizeof(" + ty_info.c_ty + ") * ret.datalen);\n")
928 write_c("\treturn ret;\n}\n")
929 elif (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
930 ty_name = "CVec_" + ty_info.rust_obj.replace("LDK", "") + "Z";
931 clone_fns.add(ty_name + "_clone")
932 write_c("static inline " + struct_name + " " + ty_name + "_clone(const " + struct_name + " *orig) {\n")
933 write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.rust_obj + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
934 write_c("\tfor (size_t i = 0; i < ret.datalen; i++) {\n")
935 write_c("\t\tret.data[i] = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&orig->data[i]);\n")
936 write_c("\t}\n\treturn ret;\n}\n")
938 assert(struct_name.endswith("_Tag"))
939 struct_name = struct_name[:-4]
940 union_enum_items[struct_name] = {"field_lines": field_lines}
941 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
942 enum_var_name = struct_name.split("_")
943 union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
944 elif struct_name in union_enum_items:
947 for line in field_lines:
948 if line == " struct {":
952 elif elem_items > -1:
954 if line.startswith("struct "):
956 elif line.startswith("enum "):
958 split = line.split(" ")
959 assert len(split) == 2
960 tuple_variants[split[1].strip(";")] = split[0]
963 # We don't currently support tuple variant with more than one element
965 map_complex_enum(struct_name, union_enum_items[struct_name], tuple_variants, last_block_comment)
966 last_block_comment = None
967 elif is_unitary_enum:
968 map_unitary_enum(struct_name, field_lines, last_block_comment)
969 last_block_comment = None
970 elif len(trait_fn_lines) > 0:
971 map_trait(struct_name, field_var_lines, trait_fn_lines, last_block_comment)
972 elif struct_name == "LDKTxOut":
973 with open(f"{sys.argv[3]}/structs/TxOut{consts.file_ext}", "w") as out_java_struct:
974 out_java_struct.write(consts.hu_struct_file_prefix)
975 out_java_struct.write("public class TxOut extends CommonBase{\n")
976 out_java_struct.write("\tTxOut(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
977 out_java_struct.write("\tlong to_c_ptr() { return 0; }\n")
978 out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
979 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
980 out_java_struct.write("\t\tsuper.finalize();\n")
981 out_java_struct.write("\t\tif (ptr != 0) { bindings.TxOut_free(ptr); }\n")
982 out_java_struct.write("\t}\n")
984 out_java_struct.write("}")
986 pass # Everything remaining is a byte[] or some form
989 fn_ptr = fn_ptr_regex.match(line)
990 fn_ret_arr = fn_ret_arr_regex.match(line)
991 reg_fn = reg_fn_regex.match(line)
992 const_val = const_val_regex.match(line)
994 if line.startswith("#include <"):
996 elif line.startswith("/*"):
997 if not line.endswith("*/\n"):
998 block_comment = line.strip(" /*")
999 elif line.startswith("typedef enum "):
1000 cur_block_obj = line
1001 elif line.startswith("typedef struct "):
1002 cur_block_obj = line
1003 elif line.startswith("typedef union "):
1004 cur_block_obj = line
1005 elif fn_ptr is not None:
1006 map_fn(line, fn_ptr, None, None, last_block_comment)
1007 last_block_comment = None
1008 elif fn_ret_arr is not None:
1009 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None, last_block_comment)
1010 last_block_comment = None
1011 elif reg_fn is not None:
1012 map_fn(line, reg_fn, None, None, last_block_comment)
1013 last_block_comment = None
1014 elif const_val_regex is not None:
1015 # TODO Map const variables
1018 assert(line == "\n")
1020 out_java.write(consts.bindings_footer)
1021 for struct_name in opaque_structs:
1022 with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1023 out_java_struct.write("}\n")
1024 for struct_name in trait_structs:
1025 with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1026 out_java_struct.write("}\n")
1027 for struct_name in complex_enums:
1028 with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '').replace('COption', 'Option')}{consts.file_ext}", "a") as out_java_struct:
1029 out_java_struct.write("}\n")
1030 for struct_name in result_types:
1031 with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDKCResult', 'Result')}{consts.file_ext}", "a") as out_java_struct:
1032 out_java_struct.write("}\n")
1034 with open(sys.argv[4], "w") as out_c:
1035 out_c.write(consts.c_file_pfx.replace('<git_version_ldk_garbagecollected>', local_git_version))
1036 out_c.write(consts.init_str())
1038 with open(f"{sys.argv[3]}/structs/UtilMethods{consts.file_ext}", "a") as util:
1039 util.write(consts.util_fn_sfx)