5 print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /path/to/bindings/ /path/to/bindings/output.c debug")
6 print("debug should be true or false and indicates whether to track allocations and ensure we don't leak")
9 hu_struct_file_prefix = """package org.ldk.structs;
11 import org.ldk.impl.bindings;
12 import org.ldk.enums.*;
13 import org.ldk.util.*;
14 import java.util.Arrays;
16 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
19 c_file_pfx = """#include \"org_ldk_impl_bindings.h\"
20 #include <rust_types.h>
21 #include <lightning.h>
23 #include <stdatomic.h>
26 if sys.argv[5] == "false":
27 c_file_pfx = c_file_pfx + """#define MALLOC(a, _) malloc(a)
28 #define FREE(p) if ((long)(p) > 1024) { free(p); }
29 #define DO_ASSERT(a) (void)(a)
33 c_file_pfx = c_file_pfx + """#include <assert.h>
34 // Always run a, then assert it is true:
35 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
36 // Assert a is true or do nothing
37 #define CHECK(a) DO_ASSERT(a)
39 // Running a leak check across all the allocations and frees of the JDK is a mess,
40 // so instead we implement our own naive leak checker here, relying on the -wrap
41 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
42 // and free'd in Rust or C across the generated bindings shared library.
46 static mtx_t allocation_mtx;
48 void __attribute__((constructor)) init_mtx() {
49 DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
53 typedef struct allocation {
54 struct allocation* next;
56 const char* struct_name;
60 static allocation* allocation_ll = NULL;
62 void* __real_malloc(size_t len);
63 void* __real_calloc(size_t nmemb, size_t len);
64 static void new_allocation(void* res, const char* struct_name) {
65 allocation* new_alloc = __real_malloc(sizeof(allocation));
67 new_alloc->struct_name = struct_name;
68 new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
69 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
70 new_alloc->next = allocation_ll;
71 allocation_ll = new_alloc;
72 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
74 static void* MALLOC(size_t len, const char* struct_name) {
75 void* res = __real_malloc(len);
76 new_allocation(res, struct_name);
79 void __real_free(void* ptr);
80 static void alloc_freed(void* ptr) {
82 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
83 allocation* it = allocation_ll;
84 while (it->ptr != ptr) {
85 p = it; it = it->next;
87 fprintf(stderr, "Tried to free unknown pointer %p at:\\n", ptr);
89 int bt_len = backtrace(bt, BT_MAX);
90 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
91 fprintf(stderr, "\\n\\n");
92 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
93 return; // addrsan should catch malloc-unknown and print more info than we have
96 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
97 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
98 DO_ASSERT(it->ptr == ptr);
101 static void FREE(void* ptr) {
102 if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
107 void* __wrap_malloc(size_t len) {
108 void* res = __real_malloc(len);
109 new_allocation(res, "malloc call");
112 void* __wrap_calloc(size_t nmemb, size_t len) {
113 void* res = __real_calloc(nmemb, len);
114 new_allocation(res, "calloc call");
117 void __wrap_free(void* ptr) {
118 if (ptr == NULL) return;
123 void* __real_realloc(void* ptr, size_t newlen);
124 void* __wrap_realloc(void* ptr, size_t len) {
125 if (ptr != NULL) alloc_freed(ptr);
126 void* res = __real_realloc(ptr, len);
127 new_allocation(res, "realloc call");
130 void __wrap_reallocarray(void* ptr, size_t new_sz) {
131 // Rust doesn't seem to use reallocarray currently
135 void __attribute__((destructor)) check_leaks() {
136 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
137 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
138 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
139 fprintf(stderr, "\\n\\n");
141 DO_ASSERT(allocation_ll == NULL);
151 def __init__(self, is_native_primitive, rust_obj, java_ty, java_fn_ty_arg, java_hu_ty, c_ty, passed_as_ptr, is_ptr, var_name, arr_len, arr_access, subty=None):
152 self.is_native_primitive = is_native_primitive
153 self.rust_obj = rust_obj
154 self.java_ty = java_ty
155 self.java_hu_ty = java_hu_ty
156 self.java_fn_ty_arg = java_fn_ty_arg
158 self.passed_as_ptr = passed_as_ptr
160 self.var_name = var_name
161 self.arr_len = arr_len
162 self.arr_access = arr_access
164 self.pass_by_ref = is_ptr
165 self.requires_clone = None
168 def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, arg_conv_cleanup, ret_conv, ret_conv_name, to_hu_conv, to_hu_conv_name, from_hu_conv):
169 assert(ty_info.c_ty is not None)
170 assert(ty_info.java_ty is not None)
171 assert(arg_name is not None)
172 self.passed_as_ptr = ty_info.passed_as_ptr
173 self.rust_obj = ty_info.rust_obj
174 self.c_ty = ty_info.c_ty
175 self.java_ty = ty_info.java_ty
176 self.java_hu_ty = ty_info.java_hu_ty
177 self.java_fn_ty_arg = ty_info.java_fn_ty_arg
178 self.arg_name = arg_name
179 self.arg_conv = arg_conv
180 self.arg_conv_name = arg_conv_name
181 self.arg_conv_cleanup = arg_conv_cleanup
182 self.ret_conv = ret_conv
183 self.ret_conv_name = ret_conv_name
184 self.to_hu_conv = to_hu_conv
185 self.to_hu_conv_name = to_hu_conv_name
186 self.from_hu_conv = from_hu_conv
190 out_java.write(self.java_ty)
192 def print_name(self):
193 if self.arg_name != "":
194 out_java.write(" " + self.arg_name)
195 write_c(" " + self.arg_name)
197 out_java.write(" arg")
200 def camel_to_snake(s):
201 # Convert camel case to snake case, in a way that appears to match cbindgen
207 if lastchar.isupper():
208 if not char.isupper() and not lastund:
213 ret = ret + lastchar.lower()
216 if char.isupper() and not lastund:
224 return (ret + lastchar.lower()).strip("_")
226 unitary_enums = set()
227 complex_enums = set()
228 opaque_structs = set()
229 trait_structs = set()
233 def is_common_base_ext(struct_name):
234 return struct_name in complex_enums or struct_name in opaque_structs or struct_name in trait_structs or struct_name in result_types
236 var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([a-z0-9]*)\]")
237 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
238 java_c_types_none_allowed = True # Unset when we do the real pass that populates the above sets
239 def java_c_types(fn_arg, ret_arr_len):
240 fn_arg = fn_arg.strip()
241 if fn_arg.startswith("MUST_USE_RES "):
244 if fn_arg.startswith("const "):
253 if fn_arg.startswith("LDKThirtyTwoBytes"):
254 fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
255 assert var_is_arr_regex.match(fn_arg[8:])
256 rust_obj = "LDKThirtyTwoBytes"
258 elif fn_arg.startswith("LDKPublicKey"):
259 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
260 assert var_is_arr_regex.match(fn_arg[8:])
261 rust_obj = "LDKPublicKey"
262 arr_access = "compressed_form"
263 elif fn_arg.startswith("LDKSecretKey"):
264 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
265 assert var_is_arr_regex.match(fn_arg[8:])
266 rust_obj = "LDKSecretKey"
268 elif fn_arg.startswith("LDKSignature"):
269 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
270 assert var_is_arr_regex.match(fn_arg[8:])
271 rust_obj = "LDKSignature"
272 arr_access = "compact_form"
273 elif fn_arg.startswith("LDKThreeBytes"):
274 fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
275 assert var_is_arr_regex.match(fn_arg[8:])
276 rust_obj = "LDKThreeBytes"
278 elif fn_arg.startswith("LDKFourBytes"):
279 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[4]"
280 assert var_is_arr_regex.match(fn_arg[8:])
281 rust_obj = "LDKFourBytes"
283 elif fn_arg.startswith("LDKSixteenBytes"):
284 fn_arg = "uint8_t (*" + fn_arg[16:] + ")[16]"
285 assert var_is_arr_regex.match(fn_arg[8:])
286 rust_obj = "LDKSixteenBytes"
288 elif fn_arg.startswith("LDKTenBytes"):
289 fn_arg = "uint8_t (*" + fn_arg[12:] + ")[10]"
290 assert var_is_arr_regex.match(fn_arg[8:])
291 rust_obj = "LDKTenBytes"
293 elif fn_arg.startswith("LDKu8slice"):
294 fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
295 assert var_is_arr_regex.match(fn_arg[8:])
296 rust_obj = "LDKu8slice"
298 elif fn_arg.startswith("LDKCVecTempl_u8") or fn_arg.startswith("LDKCVec_u8Z"):
299 if fn_arg.startswith("LDKCVecTempl_u8"):
300 fn_arg = "uint8_t (*" + fn_arg[16:] + ")[datalen]"
301 rust_obj = "LDKCVecTempl_u8"
302 assert var_is_arr_regex.match(fn_arg[8:])
304 fn_arg = "uint8_t (*" + fn_arg[12:] + ")[datalen]"
305 rust_obj = "LDKCVec_u8Z"
306 assert var_is_arr_regex.match(fn_arg[8:])
308 elif fn_arg.startswith("LDKTransaction"):
309 fn_arg = "uint8_t (*" + fn_arg[15:] + ")[datalen]"
310 rust_obj = "LDKTransaction"
311 assert var_is_arr_regex.match(fn_arg[8:])
313 elif fn_arg.startswith("LDKCVecTempl_") or fn_arg.startswith("LDKCVec_"):
316 fn_arg = fn_arg.replace("*", "")
319 if fn_arg.startswith("LDKCVec_"):
320 tyn = fn_arg[8:].split(" ")
321 assert tyn[0].endswith("Z")
325 new_arg = "LDK" + tyn[0][:-1]
327 new_arg = new_arg + " " + a
328 res = java_c_types(new_arg, ret_arr_len)
330 res = java_c_types("LDK" + fn_arg[13:], ret_arr_len)
332 assert java_c_types_none_allowed
335 res.pass_by_ref = True
336 if res.is_native_primitive or res.passed_as_ptr:
337 return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
338 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=res.c_ty + "Array", passed_as_ptr=False, is_ptr=is_ptr,
339 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
341 return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
342 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty="jobjectArray", passed_as_ptr=False, is_ptr=is_ptr,
343 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
347 if fn_arg.startswith("void"):
351 fn_arg = fn_arg[4:].strip()
353 elif fn_arg.startswith("bool"):
357 fn_arg = fn_arg[4:].strip()
359 elif fn_arg.startswith("uint8_t"):
363 fn_arg = fn_arg[7:].strip()
365 elif fn_arg.startswith("uint16_t"):
369 fn_arg = fn_arg[8:].strip()
371 elif fn_arg.startswith("uint32_t"):
375 fn_arg = fn_arg[8:].strip()
377 elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
381 if fn_arg.startswith("uint64_t"):
382 fn_arg = fn_arg[8:].strip()
384 fn_arg = fn_arg[9:].strip()
386 elif is_const and fn_arg.startswith("char *"):
389 fn_ty_arg = "Ljava/lang/String;"
390 fn_arg = fn_arg[6:].strip()
391 elif fn_arg.startswith("LDKStr"):
394 fn_ty_arg = "Ljava/lang/String;"
395 fn_arg = fn_arg[6:].strip()
399 ma = var_ty_regex.match(fn_arg)
400 if ma.group(1).strip() in unitary_enums:
401 java_ty = ma.group(1).strip()
403 fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
404 fn_arg = ma.group(2).strip()
405 rust_obj = ma.group(1).strip()
407 elif ma.group(1).strip().startswith("LDKC2Tuple"):
409 java_hu_ty = "TwoTuple<"
410 if not ma.group(1).strip() in tuple_types:
411 assert java_c_types_none_allowed
413 for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
415 java_hu_ty = java_hu_ty + ", "
416 if ty_info.is_native_primitive:
417 java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
419 java_hu_ty = java_hu_ty + ty_info.java_hu_ty
420 java_hu_ty = java_hu_ty + ">"
423 fn_arg = ma.group(2).strip()
424 rust_obj = ma.group(1).strip()
426 elif ma.group(1).strip().startswith("LDKC3Tuple"):
428 java_hu_ty = "ThreeTuple<"
429 if not ma.group(1).strip() in tuple_types:
430 assert java_c_types_none_allowed
432 for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
434 java_hu_ty = java_hu_ty + ", "
435 if ty_info.is_native_primitive:
436 java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
438 java_hu_ty = java_hu_ty + ty_info.java_hu_ty
439 java_hu_ty = java_hu_ty + ">"
442 fn_arg = ma.group(2).strip()
443 rust_obj = ma.group(1).strip()
447 java_hu_ty = ma.group(1).strip().replace("LDKCResult", "Result").replace("LDK", "")
450 fn_arg = ma.group(2).strip()
451 rust_obj = ma.group(1).strip()
454 if fn_arg.startswith(" *") or fn_arg.startswith("*"):
455 fn_arg = fn_arg.replace("*", "").strip()
462 var_is_arr = var_is_arr_regex.match(fn_arg)
463 if var_is_arr is not None or ret_arr_len is not None:
464 assert(not take_by_ptr)
466 java_ty = java_ty + "[]"
467 c_ty = c_ty + "Array"
468 if var_is_arr is not None:
469 if var_is_arr.group(1) == "":
470 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,
471 passed_as_ptr=False, is_ptr=False, var_name="arg", arr_len=var_is_arr.group(2), arr_access=arr_access, is_native_primitive=False)
472 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,
473 passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2), arr_access=arr_access, is_native_primitive=False)
475 if java_hu_ty is None:
477 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,
478 is_ptr=is_ptr, var_name=fn_arg, arr_len=arr_len, arr_access=arr_access, is_native_primitive=is_primitive)
480 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
481 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
482 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
485 c_array_class_caches = set()
486 with open(sys.argv[1]) as in_h:
488 reg_fn = reg_fn_regex.match(line)
489 if reg_fn is not None:
490 if reg_fn.group(2).endswith("_clone"):
491 clone_fns.add(reg_fn.group(2))
493 rty = java_c_types(reg_fn.group(1), None)
494 if rty is not None and rty.rust_obj is not None and reg_fn.group(2) == rty.java_hu_ty + "_new":
495 constructor_fns[rty.rust_obj] = reg_fn.group(3)
497 arr_fn = fn_ret_arr_regex.match(line)
498 if arr_fn is not None:
499 if arr_fn.group(2).endswith("_clone"):
500 clone_fns.add(arr_fn.group(2))
501 # No object constructors return arrays, as then they wouldn't be an object constructor
503 java_c_types_none_allowed = False # C structs created by cbindgen are declared in dependency order
505 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java:
506 def map_type(fn_arg, print_void, ret_arr_len, is_free, holds_ref):
507 ty_info = java_c_types(fn_arg, ret_arr_len)
508 return map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref)
510 def map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref):
511 if ty_info.c_ty == "void":
513 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
514 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
515 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
516 if ty_info.c_ty.endswith("Array"):
517 arr_len = ty_info.arr_len
518 if arr_len is not None:
519 arr_name = ty_info.var_name
522 arr_len = ret_arr_len
523 if ty_info.c_ty == "jbyteArray":
524 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", ", "")
525 arg_conv_cleanup = None
526 if not arr_len.isdigit():
527 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
528 arg_conv = arg_conv + arr_name + "_ref." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");\n"
529 if (not ty_info.is_ptr or not holds_ref) and ty_info.rust_obj != "LDKu8slice":
530 arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = MALLOC(" + arr_name + "_ref." + arr_len + ", \"" + ty_info.rust_obj + " Bytes\");\n"
531 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion(_env, " + arr_name + ", 0, " + arr_name + "_ref." + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
533 arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = (*_env)->GetByteArrayElements (_env, " + arr_name + ", NULL);"
534 arg_conv_cleanup = "(*_env)->ReleaseByteArrayElements(_env, " + arr_name + ", (int8_t*)" + arr_name + "_ref." + ty_info.arr_access + ", 0);"
535 if ty_info.rust_obj == "LDKTransaction":
536 arg_conv = arg_conv + "\n" + arr_name + "_ref.data_is_owned = " + str(holds_ref).lower() + ";"
537 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
538 ret_conv = (ret_conv[0], ";\njbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_name + "_var." + arr_len + ");\n")
539 ret_conv = (ret_conv[0], ret_conv[1] + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_name + "_var." + arr_len + ", " + arr_name + "_var." + ty_info.arr_access + ");")
540 if not holds_ref and ty_info.rust_obj != "LDKu8slice":
541 ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
542 elif ty_info.rust_obj is not None:
543 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
544 arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
545 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
546 ret_conv = (ret_conv[0], "." + ty_info.arr_access + ");")
548 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n"
549 arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
550 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
551 ret_conv = (ret_conv[0] + "*", ");")
552 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
553 arg_conv = arg_conv, arg_conv_name = arr_name + "_ref", arg_conv_cleanup = arg_conv_cleanup,
554 ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
556 assert not arr_len.isdigit() # fixed length arrays not implemented
557 assert ty_info.java_ty[len(ty_info.java_ty) - 2:] == "[]"
558 conv_name = "arr_conv_" + str(len(ty_info.java_hu_ty))
559 idxc = chr(ord('a') + (len(ty_info.java_hu_ty) % 26))
560 ty_info.subty.var_name = conv_name
561 ty_info.subty.requires_clone = not ty_info.is_ptr or not holds_ref
562 subty = map_type_with_info(ty_info.subty, False, None, is_free, holds_ref)
565 arg_conv = ty_info.rust_obj + " " + arr_name + "_constr;\n"
566 arg_conv = arg_conv + arr_name + "_constr." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");\n"
567 arg_conv = arg_conv + "if (" + arr_name + "_constr." + arr_len + " > 0)\n"
568 if subty.rust_obj is None:
571 szof = subty.rust_obj
572 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = MALLOC(" + arr_name + "_constr." + arr_len + " * sizeof(" + szof + "), \"" + ty_info.rust_obj + " Elements\");\n"
573 arg_conv = arg_conv + "else\n"
574 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = NULL;\n"
575 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
576 arg_conv = arg_conv + ty_info.java_ty.strip("[]") + "* " + arr_name + "_vals = (*_env)->Get" + ty_info.subty.java_ty.title() + "ArrayElements (_env, " + arr_name + ", NULL);\n"
577 arg_conv = arg_conv + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_constr." + arr_len + "; " + idxc + "++) {\n"
578 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
579 arg_conv = arg_conv + "\t" + ty_info.java_ty.strip("[]") + " " + conv_name + " = " + arr_name + "_vals[" + idxc + "];"
580 if subty.arg_conv is not None:
581 arg_conv = arg_conv + "\n\t" + subty.arg_conv.replace("\n", "\n\t")
583 arg_conv = arg_conv + "\tjobject " + conv_name + " = (*_env)->GetObjectArrayElement(_env, " + arr_name + ", " + idxc + ");\n"
584 arg_conv = arg_conv + "\t" + subty.arg_conv.replace("\n", "\n\t")
585 arg_conv = arg_conv + "\n\t" + arr_name + "_constr." + ty_info.arr_access + "[" + idxc + "] = " + subty.arg_conv_name + ";\n}"
586 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
587 arg_conv = arg_conv + "\n(*_env)->Release" + ty_info.java_ty.strip("[]").title() + "ArrayElements (_env, " + arr_name + ", " + arr_name + "_vals, 0);"
589 arg_conv_name = "&" + arr_name + "_constr"
591 arg_conv_name = arr_name + "_constr"
592 arg_conv_cleanup = None
594 arg_conv_cleanup = "FREE(" + arr_name + "_constr." + ty_info.arr_access + ");"
596 if arr_name == "arg":
598 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
599 if subty.ret_conv is None:
600 ret_conv = ("DUMMY", "DUMMY")
601 elif not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
602 ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = (*_env)->New" + ty_info.java_ty.strip("[]").title() + "Array(_env, " + arr_name + "_var." + arr_len + ");\n")
603 ret_conv = (ret_conv[0], ret_conv[1] + subty.c_ty + " *" + arr_name + "_arr_ptr = (*_env)->GetPrimitiveArrayCritical(_env, " + arr_name + "_arr, NULL);\n")
604 ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
605 ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
606 ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
607 ret_conv = (ret_conv[0], ret_conv[1] + "\n\t" + arr_name + "_arr_ptr[" + idxc + "] = " + subty.ret_conv_name + ";\n")
608 ret_conv = (ret_conv[0], ret_conv[1] + "}\n(*_env)->ReleasePrimitiveArrayCritical(_env, " + arr_name + "_arr, " + arr_name + "_arr_ptr, 0);")
610 assert ty_info.java_fn_ty_arg.startswith("[")
611 clz_var = ty_info.java_fn_ty_arg[1:].replace("[", "arr_of_")
612 c_array_class_caches.add(clz_var)
613 ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = (*_env)->NewObjectArray(_env, " + arr_name + "_var." + arr_len + ", " + clz_var + "_clz, NULL);\n")
614 ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
615 ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
616 ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
617 ret_conv = (ret_conv[0], ret_conv[1] + "\n\t(*_env)->SetObjectArrayElement(_env, " + arr_name + "_arr, " + idxc + ", " + subty.ret_conv_name + ");\n")
618 ret_conv = (ret_conv[0], ret_conv[1] + "}")
620 if subty.rust_obj is not None and subty.rust_obj in opaque_structs:
621 ret_conv = (ret_conv[0], ret_conv[1] + "\nFREE(" + arr_name + "_var." + ty_info.arr_access + ");")
623 ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
626 to_hu_conv_name = None
627 if subty.to_hu_conv is not None:
628 to_hu_conv = ty_info.java_hu_ty + " " + conv_name + "_arr = new " + ty_info.subty.java_hu_ty.split("<")[0] + "[" + arr_name + ".length];\n"
629 to_hu_conv = to_hu_conv + "for (int " + idxc + " = 0; " + idxc + " < " + arr_name + ".length; " + idxc + "++) {\n"
630 to_hu_conv = to_hu_conv + "\t" + subty.java_ty + " " + conv_name + " = " + arr_name + "[" + idxc + "];\n"
631 to_hu_conv = to_hu_conv + "\t" + subty.to_hu_conv.replace("\n", "\n\t") + "\n"
632 to_hu_conv = to_hu_conv + "\t" + conv_name + "_arr[" + idxc + "] = " + subty.to_hu_conv_name + ";\n}"
633 to_hu_conv_name = conv_name + "_arr"
635 if subty.from_hu_conv is not None:
636 if subty.java_ty == "long" and subty.java_hu_ty != "long":
637 from_hu_conv = ("Arrays.stream(" + arr_name + ").mapToLong(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + " */")
638 elif subty.java_ty == "long":
639 from_hu_conv = ("Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + " */")
641 from_hu_conv = ("(" + ty_info.java_ty + ")Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + " */")
643 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
644 arg_conv = arg_conv, arg_conv_name = arg_conv_name, arg_conv_cleanup = arg_conv_cleanup,
645 ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = to_hu_conv, to_hu_conv_name = to_hu_conv_name, from_hu_conv = from_hu_conv)
646 elif ty_info.java_ty == "String":
647 if ty_info.arr_access is None:
648 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
649 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
650 ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv",
651 to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
653 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
654 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
655 ret_conv = ("LDKStr " + ty_info.var_name + "_str = ",
656 ";\nchar* " + ty_info.var_name + "_buf = MALLOC(" + ty_info.var_name + "_str." + ty_info.arr_len + " + 1, \"str conv buf\");\n" +
657 "memcpy(" + ty_info.var_name + "_buf, " + ty_info.var_name + "_str." + ty_info.arr_access + ", " + ty_info.var_name + "_str." + ty_info.arr_len + ");\n" +
658 ty_info.var_name + "_buf[" + ty_info.var_name + "_str." + ty_info.arr_len + "] = 0;\n" +
659 "jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, " + ty_info.var_name + "_str." + ty_info.arr_access + ");\n" +
660 "FREE(" + ty_info.var_name + "_buf);"),
661 ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
662 elif ty_info.var_name == "" and not print_void:
663 # We don't have a parameter name, and want one, just call it arg
664 if ty_info.rust_obj is not None:
665 assert(not is_free or ty_info.rust_obj not in opaque_structs)
666 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
667 arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
668 arg_conv_name = "arg_conv", arg_conv_cleanup = None,
669 ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 7", to_hu_conv_name = None, from_hu_conv = None)
672 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
673 arg_conv = None, arg_conv_name = "arg", arg_conv_cleanup = None,
674 ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 8", to_hu_conv_name = None, from_hu_conv = None)
675 elif ty_info.rust_obj is None:
676 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
677 arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None,
678 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
680 if ty_info.var_name == "":
681 ty_info.var_name = "ret"
683 if ty_info.rust_obj in opaque_structs:
684 opaque_arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv;\n"
685 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
686 if ty_info.is_ptr and holds_ref:
687 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = false;"
689 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
690 if not is_free and (not ty_info.is_ptr or not holds_ref or ty_info.requires_clone == True) and ty_info.requires_clone != False:
691 if (ty_info.java_hu_ty + "_clone") in clone_fns:
692 # TODO: This is a bit too naive, even with the checks above, we really need to know if rust wants a ref or not, not just if its pass as a ptr.
693 opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
694 opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.java_hu_ty + "_clone(&" + ty_info.var_name + "_conv);"
695 elif ty_info.passed_as_ptr:
696 opaque_arg_conv = opaque_arg_conv + "\n// Warning: we may need a move here but can't clone!"
698 opaque_ret_conv_suf = ";\n"
699 if not holds_ref and ty_info.is_ptr and (ty_info.java_hu_ty + "_clone") in clone_fns: # is_ptr, not holds_ref implies passing a pointed-to value to java, which needs copied
700 opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "->inner != NULL)\n"
701 opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_var = " + ty_info.java_hu_ty + "_clone(" + ty_info.var_name + ");\n"
702 elif not holds_ref and ty_info.is_ptr:
703 opaque_ret_conv_suf = opaque_ret_conv_suf + "// Warning: we may need a move here but can't clone!\n"
705 opaque_ret_conv_suf = opaque_ret_conv_suf + "CHECK((((long)" + ty_info.var_name + "_var.inner) & 1) == 0); // We rely on a free low bit, malloc guarantees this.\n"
706 opaque_ret_conv_suf = opaque_ret_conv_suf + "CHECK((((long)&" + ty_info.var_name + "_var) & 1) == 0); // We rely on a free low bit, pointer alignment guarantees this.\n"
707 if holds_ref or ty_info.is_ptr:
708 opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner & ~1;"
710 opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner;\n"
711 opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "_var.is_owned) {\n"
712 opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_ref |= 1;\n"
713 opaque_ret_conv_suf = opaque_ret_conv_suf + "}"
716 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
717 arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv", arg_conv_cleanup = None,
718 ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = *", opaque_ret_conv_suf),
719 ret_conv_name = ty_info.var_name + "_ref",
720 to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
721 to_hu_conv_name = ty_info.var_name + "_hu_conv",
722 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
724 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
725 arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
726 ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", opaque_ret_conv_suf),
727 ret_conv_name = ty_info.var_name + "_ref",
728 to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
729 to_hu_conv_name = ty_info.var_name + "_hu_conv",
730 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
732 if not ty_info.is_ptr:
733 if ty_info.rust_obj in unitary_enums:
734 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
735 arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
736 arg_conv_name = ty_info.var_name + "_conv",
737 arg_conv_cleanup = None,
738 ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
739 ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
740 base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
741 if ty_info.rust_obj in trait_structs:
743 base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
744 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
745 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
747 base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
748 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
749 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
750 ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
751 ret_conv_name = "(long)ret",
752 to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, ret);\nret_hu_conv.ptrs_to.add(this);",
753 to_hu_conv_name = "ret_hu_conv",
754 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
755 if ty_info.rust_obj != "LDKu8slice":
756 # Don't bother free'ing slices passed in - Rust doesn't auto-free the
757 # underlying unlike Vecs, and it gives Java more freedom.
758 base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
759 if ty_info.rust_obj in complex_enums:
760 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";")
762 ret_conv = (ty_info.rust_obj + " *" + ty_info.var_name + "_copy = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n", "")
763 if ty_info.requires_clone == True: # Set in object array mapping
764 if (ty_info.java_hu_ty + "_clone") in clone_fns:
765 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = " + ty_info.java_hu_ty + "_clone(&", ");\n")
767 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", "; // XXX: We likely need to clone here, but no _clone fn is available!\n")
769 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", ";\n")
770 ret_conv = (ret_conv[0], ret_conv[1] + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_copy;")
771 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
772 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
773 ret_conv = ret_conv, ret_conv_name = ty_info.var_name + "_ref",
774 to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");\n" + ty_info.var_name + "_hu_conv.ptrs_to.add(this);",
775 to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
776 if ty_info.rust_obj in result_types:
777 assert not ty_info.is_ptr and not holds_ref # Otherwise we shouldn't be MALLOC'ing
778 ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_conv = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_conv = ", ";")
779 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
780 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
781 ret_conv = ret_conv, ret_conv_name = "(long)" + ty_info.var_name + "_conv",
782 to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");\n" + ty_info.var_name + "_hu_conv.ptrs_to.add(this);",
783 to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + " != null ? " + ty_info.var_name + ".ptr : 0", ""))
784 if ty_info.rust_obj in tuple_types:
785 from_hu_conv = "bindings." + tuple_types[ty_info.rust_obj][1].replace("LDK", "") + "_new("
787 to_hu_conv_sfx = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " + ty_info.java_hu_ty + "("
788 for idx, conv in enumerate(tuple_types[ty_info.rust_obj][0]):
790 to_hu_conv_sfx = to_hu_conv_sfx + ", "
791 from_hu_conv = from_hu_conv + ", "
792 conv.var_name = ty_info.var_name + "_" + chr(idx + ord("a"))
793 conv_map = map_type_with_info(conv, False, None, is_free, holds_ref)
794 to_hu_conv_pfx = to_hu_conv_pfx + conv.java_ty + " " + ty_info.var_name + "_" + chr(idx + ord("a")) + " = " + "bindings." + tuple_types[ty_info.rust_obj][1] + "_get_" + chr(idx + ord("a")) + "(" + ty_info.var_name + ");\n"
795 if conv_map.to_hu_conv is not None:
796 to_hu_conv_pfx = to_hu_conv_pfx + conv_map.to_hu_conv + ";\n"
797 to_hu_conv_sfx = to_hu_conv_sfx + conv_map.to_hu_conv_name
799 to_hu_conv_sfx = to_hu_conv_sfx + ty_info.var_name + "_" + chr(idx + ord("a"))
800 if conv_map.from_hu_conv is not None:
801 from_hu_conv = from_hu_conv + conv_map.from_hu_conv[0].replace(ty_info.var_name + "_" + chr(idx + ord("a")), ty_info.var_name + "." + chr(idx + ord("a")))
802 if conv_map.from_hu_conv[1] != "":
803 from_hu_conv = from_hu_conv + "/*XXX: " + conv_map.from_hu_conv[1] + "*/"
805 from_hu_conv = from_hu_conv + ty_info.var_name + "." + chr(idx + ord("a"))
807 if not ty_info.is_ptr and not holds_ref:
808 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
809 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
811 ret_conv = (ty_info.rust_obj + "* " + ty_info.var_name + "_ref = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*" + ty_info.var_name + "_ref = ", ";"),
812 ret_conv_name = "(long)" + ty_info.var_name + "_ref",
813 to_hu_conv = to_hu_conv_pfx + to_hu_conv_sfx + ");", to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (from_hu_conv + ")", ""))
814 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
815 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
816 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
817 to_hu_conv = to_hu_conv_pfx + to_hu_conv_sfx + ");", to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (from_hu_conv + ")", ""))
819 # The manually-defined types - TxOut and Transaction
820 assert ty_info.rust_obj == "LDKTxOut"
821 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
822 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
823 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
824 to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " +ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
825 to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
828 if ty_info.rust_obj in complex_enums:
829 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
830 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
831 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
832 ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
833 to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(" + ty_info.var_name + ");",
834 to_hu_conv_name = ty_info.var_name + "_hu_conv",
835 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
836 elif ty_info.rust_obj in trait_structs:
837 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
838 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
839 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
840 ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
841 to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, ret);\nret_hu_conv.ptrs_to.add(this);",
842 to_hu_conv_name = "ret_hu_conv",
843 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
844 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
845 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
846 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
847 ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
848 to_hu_conv = "TODO 3", to_hu_conv_name = None, from_hu_conv = None) # its a pointer, no conv needed
849 assert False # We should have handled every case by now.
851 def map_fn(line, re_match, ret_arr_len, c_call_string):
852 out_java.write("\t// " + line)
853 out_java.write("\tpublic static native ")
854 write_c("JNIEXPORT ")
856 is_free = re_match.group(2).endswith("_free")
857 struct_meth = re_match.group(2).split("_")[0]
859 ret_info = map_type(re_match.group(1), True, ret_arr_len, False, False)
862 if ret_info.ret_conv is not None:
863 ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
865 out_java.write(" " + re_match.group(2) + "(")
866 write_c(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
869 default_constructor_args = {}
871 args_known = not ret_info.passed_as_ptr or ret_info.rust_obj in opaque_structs or ret_info.rust_obj in trait_structs or ret_info.rust_obj in complex_enums or ret_info.rust_obj in result_types
872 for idx, arg in enumerate(re_match.group(3).split(',')):
877 arg_conv_info = map_type(arg, False, None, is_free, True)
878 if arg_conv_info.c_ty != "void":
879 arg_conv_info.print_ty()
880 arg_conv_info.print_name()
881 if arg_conv_info.arg_name == "this_ptr" or arg_conv_info.arg_name == "this_arg":
883 if arg_conv_info.arg_conv is not None and "Warning" in arg_conv_info.arg_conv:
884 if arg_conv_info.rust_obj in constructor_fns:
886 for explode_arg in constructor_fns[arg_conv_info.rust_obj].split(','):
887 explode_arg_conv = map_type(explode_arg, False, None, False, True)
888 if explode_arg_conv.c_ty == "void":
889 # We actually want to handle this case, but for now its only used in NetGraphMsgHandler::new()
890 # which ends up resulting in a redundant constructor - both without arguments for the NetworkGraph.
892 assert explode_arg_conv.arg_name != "this_ptr"
893 assert explode_arg_conv.arg_name != "this_arg"
894 if explode_arg_conv.passed_as_ptr and not explode_arg_conv.rust_obj in trait_structs:
896 if not arg_conv_info.arg_name in default_constructor_args:
897 default_constructor_args[arg_conv_info.arg_name] = []
898 default_constructor_args[arg_conv_info.arg_name].append(explode_arg_conv)
901 arg_names.append(arg_conv_info)
903 out_java_struct = None
904 if ("LDK" + struct_meth in opaque_structs or "LDK" + struct_meth in trait_structs) and not is_free:
905 out_java_struct = open(sys.argv[3] + "/structs/" + struct_meth + ".java", "a")
907 out_java_struct.write("\t// Skipped " + re_match.group(2) + "\n")
908 out_java_struct.close()
909 out_java_struct = None
911 meth_n = re_match.group(2)[len(struct_meth) + 1:]
912 if ret_info.rust_obj == "LDK" + struct_meth:
913 out_java_struct.write("\tpublic static " + ret_info.java_hu_ty + " constructor_" + meth_n + "(")
915 out_java_struct.write("\tpublic " + ret_info.java_hu_ty + " " + meth_n + "(")
916 for idx, arg in enumerate(arg_names):
918 if not takes_self or idx > 1:
919 out_java_struct.write(", ")
920 if arg.java_ty != "void" and arg.arg_name != "this_ptr" and arg.arg_name != "this_arg":
921 if arg.arg_name in default_constructor_args:
922 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
924 out_java_struct.write(", ")
925 assert explode_arg.rust_obj in opaque_structs or explode_arg.rust_obj in trait_structs
926 out_java_struct.write(explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
928 out_java_struct.write(arg.java_hu_ty + " " + arg.arg_name)
931 out_java.write(");\n")
933 if out_java_struct is not None:
934 out_java_struct.write(") {\n")
936 for info in arg_names:
937 if info.arg_conv is not None:
938 write_c("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
940 if ret_info.ret_conv is not None:
941 write_c("\t" + ret_conv_pfx.replace('\n', '\n\t'))
942 elif ret_info.c_ty != "void":
943 write_c("\t" + ret_info.c_ty + " ret_val = ")
947 if c_call_string is None:
948 write_c(re_match.group(2) + "(")
950 write_c(c_call_string)
951 for idx, info in enumerate(arg_names):
952 if info.arg_conv_name is not None:
955 elif c_call_string is not None:
957 write_c(info.arg_conv_name)
959 if ret_info.ret_conv is not None:
960 write_c(ret_conv_sfx.replace('\n', '\n\t'))
963 for info in arg_names:
964 if info.arg_conv_cleanup is not None:
965 write_c("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
966 if ret_info.ret_conv is not None:
967 write_c("\n\treturn " + ret_info.ret_conv_name + ";")
968 elif ret_info.c_ty != "void":
969 write_c("\n\treturn ret_val;")
971 if out_java_struct is not None:
972 out_java_struct.write("\t\t")
973 if ret_info.java_ty != "void":
974 out_java_struct.write(ret_info.java_ty + " ret = ")
975 out_java_struct.write("bindings." + re_match.group(2) + "(")
976 for idx, info in enumerate(arg_names):
978 out_java_struct.write(", ")
979 if info.arg_name == "this_ptr" or info.arg_name == "this_arg":
980 out_java_struct.write("this.ptr")
981 elif info.arg_name in default_constructor_args:
982 out_java_struct.write("bindings." + info.java_hu_ty + "_new(")
983 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
985 out_java_struct.write(", ")
986 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
987 out_java_struct.write(explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
988 out_java_struct.write(")")
989 elif info.from_hu_conv is not None:
990 out_java_struct.write(info.from_hu_conv[0])
992 out_java_struct.write(info.arg_name)
993 out_java_struct.write(");\n")
994 if ret_info.to_hu_conv is not None:
995 out_java_struct.write("\t\t" + ret_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
997 for info in arg_names:
998 if info.arg_name == "this_ptr" or info.arg_name == "this_arg":
1000 elif info.arg_name in default_constructor_args:
1001 for explode_arg in default_constructor_args[info.arg_name]:
1002 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1003 out_java_struct.write("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name, expl_arg_name).replace("this", ret_info.to_hu_conv_name) + ";\n")
1004 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1005 if ret_info.rust_obj == "LDK" + struct_meth and ret_info.to_hu_conv_name is not None:
1006 out_java_struct.write("\t\t" + info.from_hu_conv[1].replace("this", ret_info.to_hu_conv_name) + ";\n")
1008 out_java_struct.write("\t\t" + info.from_hu_conv[1] + ";\n")
1010 if ret_info.to_hu_conv_name is not None:
1011 out_java_struct.write("\t\treturn " + ret_info.to_hu_conv_name + ";\n")
1012 elif ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
1013 out_java_struct.write("\t\treturn ret;\n")
1014 out_java_struct.write("\t}\n\n")
1015 out_java_struct.close()
1017 def map_unitary_enum(struct_name, field_lines):
1018 with open(sys.argv[3] + "/enums/" + struct_name + ".java", "w") as out_java_enum:
1019 out_java_enum.write("package org.ldk.enums;\n\n")
1020 unitary_enums.add(struct_name)
1021 write_c("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
1022 write_c("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
1024 for idx, struct_line in enumerate(field_lines):
1026 out_java_enum.write("public enum " + struct_name + " {\n")
1027 elif idx == len(field_lines) - 3:
1028 assert(struct_line.endswith("_Sentinel,"))
1029 elif idx == len(field_lines) - 2:
1030 out_java_enum.write("\t; static native void init();\n")
1031 out_java_enum.write("\tstatic { init(); }\n")
1032 out_java_enum.write("}")
1033 out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
1034 elif idx == len(field_lines) - 1:
1035 assert(struct_line == "")
1037 out_java_enum.write(struct_line + "\n")
1038 write_c("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
1041 write_c("\tabort();\n")
1045 write_c("static jclass " + struct_name + "_class = NULL;\n")
1046 for idx, struct_line in enumerate(field_lines):
1047 if idx > 0 and idx < len(field_lines) - 3:
1048 variant = struct_line.strip().strip(",")
1049 write_c("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
1050 write_c("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
1051 write_c("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
1052 write_c("\tCHECK(" + struct_name + "_class != NULL);\n")
1053 for idx, struct_line in enumerate(field_lines):
1054 if idx > 0 and idx < len(field_lines) - 3:
1055 variant = struct_line.strip().strip(",")
1056 write_c("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
1057 write_c("\tCHECK(" + struct_name + "_" + variant + " != NULL);\n")
1059 write_c("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
1060 write_c("\tswitch (val) {\n")
1061 for idx, struct_line in enumerate(field_lines):
1062 if idx > 0 and idx < len(field_lines) - 3:
1063 variant = struct_line.strip().strip(",")
1064 write_c("\t\tcase " + variant + ":\n")
1065 write_c("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
1067 write_c("\t\tdefault: abort();\n")
1071 def map_complex_enum(struct_name, union_enum_items):
1072 java_hu_type = struct_name.replace("LDK", "")
1073 complex_enums.add(struct_name)
1074 with open(sys.argv[3] + "/structs/" + java_hu_type + ".java", "w") as out_java_enum:
1075 out_java_enum.write(hu_struct_file_prefix)
1076 out_java_enum.write("public class " + java_hu_type + " extends CommonBase {\n")
1077 out_java_enum.write("\tprivate " + java_hu_type + "(Object _dummy, long ptr) { super(ptr); }\n")
1078 out_java_enum.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1079 out_java_enum.write("\tprotected void finalize() throws Throwable {\n")
1080 out_java_enum.write("\t\tsuper.finalize();\n")
1081 out_java_enum.write("\t\tif (ptr != 0) { bindings." + java_hu_type + "_free(ptr); }\n")
1082 out_java_enum.write("\t}\n")
1083 out_java_enum.write("\tstatic " + java_hu_type + " constr_from_ptr(long ptr) {\n")
1084 out_java_enum.write("\t\tbindings." + struct_name + " raw_val = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
1085 java_hu_subclasses = ""
1087 tag_field_lines = union_enum_items["field_lines"]
1088 init_meth_jty_strs = {}
1089 for idx, struct_line in enumerate(tag_field_lines):
1091 out_java.write("\tpublic static class " + struct_name + " {\n")
1092 out_java.write("\t\tprivate " + struct_name + "() {}\n")
1093 elif idx == len(tag_field_lines) - 3:
1094 assert(struct_line.endswith("_Sentinel,"))
1095 elif idx == len(tag_field_lines) - 2:
1096 out_java.write("\t\tstatic native void init();\n")
1097 out_java.write("\t}\n")
1098 elif idx == len(tag_field_lines) - 1:
1099 assert(struct_line == "")
1101 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1102 out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
1103 java_hu_subclasses = java_hu_subclasses + "\tpublic final static class " + var_name + " extends " + java_hu_type + " {\n"
1104 out_java_enum.write("\t\tif (raw_val.getClass() == bindings." + struct_name + "." + var_name + ".class) {\n")
1105 out_java_enum.write("\t\t\treturn new " + var_name + "(ptr, (bindings." + struct_name + "." + var_name + ")raw_val);\n")
1106 write_c("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
1107 write_c("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
1108 init_meth_jty_str = ""
1109 init_meth_params = ""
1112 if "LDK" + var_name in union_enum_items:
1113 enum_var_lines = union_enum_items["LDK" + var_name]
1114 for idx, field in enumerate(enum_var_lines):
1115 if idx != 0 and idx < len(enum_var_lines) - 2:
1116 field_ty = map_type(field.strip(' ;'), False, None, False, True)
1117 out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
1118 java_hu_subclasses = java_hu_subclasses + "\t\tpublic final " + field_ty.java_hu_ty + " " + field_ty.arg_name + ";\n"
1119 if field_ty.to_hu_conv is not None:
1120 hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.java_ty + " " + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1121 hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1122 hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1124 hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1125 init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
1127 init_meth_params = init_meth_params + ", "
1128 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
1129 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
1130 out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
1131 out_java.write(init_meth_body)
1132 out_java.write("}\n")
1133 out_java.write("\t\t}\n")
1134 out_java_enum.write("\t\t}\n")
1135 java_hu_subclasses = java_hu_subclasses + "\t\tprivate " + var_name + "(long ptr, bindings." + struct_name + "." + var_name + " obj) {\n\t\t\tsuper(null, ptr);\n"
1136 java_hu_subclasses = java_hu_subclasses + hu_conv_body
1137 java_hu_subclasses = java_hu_subclasses + "\t\t}\n\t}\n"
1138 init_meth_jty_strs[var_name] = init_meth_jty_str
1139 out_java_enum.write("\t\tassert false; return null; // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
1140 out_java_enum.write(java_hu_subclasses)
1141 out_java.write("\tstatic { " + struct_name + ".init(); }\n")
1142 out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
1144 write_c("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
1145 for idx, struct_line in enumerate(tag_field_lines):
1146 if idx != 0 and idx < len(tag_field_lines) - 3:
1147 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1148 write_c("\t" + struct_name + "_" + var_name + "_class =\n")
1149 write_c("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
1150 write_c("\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n")
1151 write_c("\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n")
1152 write_c("\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n")
1154 write_c("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (JNIEnv * _env, jclass _c, jlong ptr) {\n")
1155 write_c("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
1156 write_c("\tswitch(obj->tag) {\n")
1157 for idx, struct_line in enumerate(tag_field_lines):
1158 if idx != 0 and idx < len(tag_field_lines) - 3:
1159 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1160 write_c("\t\tcase " + struct_name + "_" + var_name + ": {\n")
1162 if "LDK" + var_name in union_enum_items:
1163 enum_var_lines = union_enum_items["LDK" + var_name]
1164 for idx, field in enumerate(enum_var_lines):
1165 if idx != 0 and idx < len(enum_var_lines) - 2:
1166 field_map = map_type(field.strip(' ;'), False, None, False, True)
1167 if field_map.ret_conv is not None:
1168 write_c("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1169 write_c("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
1170 write_c(field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1171 c_params_text = c_params_text + ", " + field_map.ret_conv_name
1173 c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
1174 write_c("\t\t\treturn (*_env)->NewObject(_env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
1176 write_c("\t\tdefault: abort();\n")
1178 out_java_enum.write("}\n")
1180 def map_trait(struct_name, field_var_lines, trait_fn_lines):
1181 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_trait:
1182 write_c("typedef struct " + struct_name + "_JCalls {\n")
1183 write_c("\tatomic_size_t refcnt;\n")
1184 write_c("\tJavaVM *vm;\n")
1185 write_c("\tjweak o;\n")
1186 field_var_convs = []
1187 for var_line in field_var_lines:
1188 if var_line.group(1) in trait_structs:
1189 write_c("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
1190 field_var_convs.append(None)
1192 field_var_convs.append(map_type(var_line.group(1) + " " + var_line.group(2), False, None, False, False))
1193 for fn_line in trait_fn_lines:
1194 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1195 write_c("\tjmethodID " + fn_line.group(2) + "_meth;\n")
1196 write_c("} " + struct_name + "_JCalls;\n")
1198 out_java_trait.write(hu_struct_file_prefix)
1199 out_java_trait.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
1200 out_java_trait.write("\tfinal bindings." + struct_name + " bindings_instance;\n")
1201 out_java_trait.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); bindings_instance = null; }\n")
1202 out_java_trait.write("\tprivate " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg")
1203 for idx, var_line in enumerate(field_var_lines):
1204 if var_line.group(1) in trait_structs:
1205 out_java_trait.write(", bindings." + var_line.group(1) + " " + var_line.group(2))
1207 out_java_trait.write(", " + field_var_convs[idx].java_hu_ty + " " + var_line.group(2))
1208 out_java_trait.write(") {\n")
1209 out_java_trait.write("\t\tsuper(bindings." + struct_name + "_new(arg")
1210 for idx, var_line in enumerate(field_var_lines):
1211 if var_line.group(1) in trait_structs:
1212 out_java_trait.write(", " + var_line.group(2))
1213 elif field_var_convs[idx].from_hu_conv is not None:
1214 out_java_trait.write(", " + field_var_convs[idx].from_hu_conv[0])
1216 out_java_trait.write(", " + var_line.group(2))
1217 out_java_trait.write("));\n")
1218 out_java_trait.write("\t\tthis.ptrs_to.add(arg);\n")
1219 for idx, var_line in enumerate(field_var_lines):
1220 if var_line.group(1) in trait_structs:
1221 out_java_trait.write("\t\tthis.ptrs_to.add(" + var_line.group(2) + ");\n")
1222 elif field_var_convs[idx].from_hu_conv is not None and field_var_convs[idx].from_hu_conv[1] != "":
1223 out_java_trait.write("\t\t" + field_var_convs[idx].from_hu_conv[1] + ";\n")
1224 out_java_trait.write("\t\tthis.bindings_instance = arg;\n")
1225 out_java_trait.write("\t}\n")
1226 out_java_trait.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1227 out_java_trait.write("\tprotected void finalize() throws Throwable {\n")
1228 out_java_trait.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
1229 out_java_trait.write("\t}\n\n")
1231 java_trait_constr = "\tprivate static class " + struct_name + "Holder { " + struct_name.replace("LDK", "") + " held; }\n"
1232 java_trait_constr = java_trait_constr + "\tpublic static " + struct_name.replace("LDK", "") + " new_impl(" + struct_name.replace("LDK", "") + "Interface arg"
1233 for idx, var_line in enumerate(field_var_lines):
1234 if var_line.group(1) in trait_structs:
1235 # Ideally we'd be able to take any instance of the interface, but our C code can only represent
1236 # Java-implemented version, so we require users pass a Java implementation here :/
1237 java_trait_constr = java_trait_constr + ", " + var_line.group(1).replace("LDK", "") + "." + var_line.group(1).replace("LDK", "") + "Interface " + var_line.group(2) + "_impl"
1239 java_trait_constr = java_trait_constr + ", " + field_var_convs[idx].java_hu_ty + " " + var_line.group(2)
1240 java_trait_constr = java_trait_constr + ") {\n\t\tfinal " + struct_name + "Holder impl_holder = new " + struct_name + "Holder();\n"
1241 java_trait_constr = java_trait_constr + "\t\timpl_holder.held = new " + struct_name.replace("LDK", "") + "(new bindings." + struct_name + "() {\n"
1242 out_java_trait.write("\tpublic static interface " + struct_name.replace("LDK", "") + "Interface {\n")
1243 out_java.write("\tpublic interface " + struct_name + " {\n")
1245 for fn_line in trait_fn_lines:
1246 java_meth_descr = "("
1247 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1248 ret_ty_info = map_type(fn_line.group(1), True, None, False, False)
1250 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
1251 java_trait_constr = java_trait_constr + "\t\t\t@Override public " + ret_ty_info.java_ty + " " + fn_line.group(2) + "("
1252 out_java_trait.write("\t\t" + ret_ty_info.java_hu_ty + " " + fn_line.group(2) + "(")
1253 is_const = fn_line.group(3) is not None
1254 write_c(fn_line.group(1) + fn_line.group(2) + "_jcall(")
1256 write_c("const void* this_arg")
1258 write_c("void* this_arg")
1261 for idx, arg in enumerate(fn_line.group(4).split(',')):
1265 out_java.write(", ")
1266 java_trait_constr = java_trait_constr + ", "
1267 out_java_trait.write(", ")
1269 arg_conv_info = map_type(arg, True, None, False, False)
1270 write_c(arg.strip())
1271 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
1272 out_java_trait.write(arg_conv_info.java_hu_ty + " " + arg_conv_info.arg_name)
1273 java_trait_constr = java_trait_constr + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
1274 arg_names.append(arg_conv_info)
1275 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
1276 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
1277 java_meths.append(java_meth_descr)
1279 out_java.write(");\n")
1280 out_java_trait.write(");\n")
1281 java_trait_constr = java_trait_constr + ") {\n"
1283 write_c("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1284 write_c("\tJNIEnv *_env;\n")
1285 write_c("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&_env, JNI_VERSION_1_8) == JNI_OK);\n")
1287 for arg_info in arg_names:
1288 if arg_info.ret_conv is not None:
1289 write_c("\t" + arg_info.ret_conv[0].replace('\n', '\n\t'));
1290 write_c(arg_info.arg_name)
1291 write_c(arg_info.ret_conv[1].replace('\n', '\n\t') + "\n")
1292 if arg_info.to_hu_conv is not None:
1293 java_trait_constr = java_trait_constr + "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
1295 write_c("\tjobject obj = (*_env)->NewLocalRef(_env, j_calls->o);\n\tCHECK(obj != NULL);\n")
1296 if ret_ty_info.c_ty.endswith("Array"):
1297 write_c("\t" + ret_ty_info.c_ty + " arg = (*_env)->CallObjectMethod(_env, obj, j_calls->" + fn_line.group(2) + "_meth")
1298 elif not ret_ty_info.passed_as_ptr:
1299 write_c("\treturn (*_env)->Call" + ret_ty_info.java_ty.title() + "Method(_env, obj, j_calls->" + fn_line.group(2) + "_meth")
1301 write_c("\t" + fn_line.group(1).strip() + "* ret = (" + fn_line.group(1).strip() + "*)(*_env)->CallLongMethod(_env, obj, j_calls->" + fn_line.group(2) + "_meth");
1302 if ret_ty_info.java_ty != "void":
1303 java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.java_hu_ty + " ret = arg." + fn_line.group(2) + "("
1305 java_trait_constr = java_trait_constr + "\t\t\t\targ." + fn_line.group(2) + "("
1307 for idx, arg_info in enumerate(arg_names):
1308 if arg_info.ret_conv is not None:
1309 write_c(", " + arg_info.ret_conv_name)
1311 write_c(", " + arg_info.arg_name)
1313 java_trait_constr = java_trait_constr + ", "
1314 if arg_info.to_hu_conv_name is not None:
1315 java_trait_constr = java_trait_constr + arg_info.to_hu_conv_name
1317 java_trait_constr = java_trait_constr + arg_info.arg_name
1319 if ret_ty_info.arg_conv is not None:
1320 write_c("\t" + ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + ret_ty_info.arg_conv_name + ";\n")
1323 java_trait_constr = java_trait_constr + ");\n"
1324 if ret_ty_info.java_ty != "void":
1325 if ret_ty_info.from_hu_conv is not None:
1326 java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.java_ty + " result = " + ret_ty_info.from_hu_conv[0] + ";\n"
1327 if ret_ty_info.from_hu_conv[1] != "":
1328 java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
1329 if is_common_base_ext(ret_ty_info.rust_obj):
1330 java_trait_constr = java_trait_constr + "\t\t\t\tret.ptr = 0;\n"
1331 java_trait_constr = java_trait_constr + "\t\t\t\treturn result;\n"
1333 java_trait_constr = java_trait_constr + "\t\t\t\treturn ret;\n"
1334 java_trait_constr = java_trait_constr + "\t\t\t}\n"
1335 elif fn_line.group(2) == "free":
1336 write_c("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
1337 write_c("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1338 write_c("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
1339 write_c("\t\tJNIEnv *env;\n")
1340 write_c("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
1341 write_c("\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n")
1342 write_c("\t\tFREE(j_calls);\n")
1344 java_trait_constr = java_trait_constr + "\t\t}"
1345 for var_line in field_var_lines:
1346 if var_line.group(1) in trait_structs:
1347 java_trait_constr = java_trait_constr + ", " + var_line.group(2) + ".new_impl(" + var_line.group(2) + "_impl).bindings_instance"
1349 java_trait_constr = java_trait_constr + ", " + var_line.group(2)
1350 out_java_trait.write("\t}\n")
1351 out_java_trait.write(java_trait_constr + ");\n\t\treturn impl_holder.held;\n\t}\n")
1353 # Write out a clone function whether we need one or not, as we use them in moving to rust
1354 write_c("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
1355 write_c("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1356 write_c("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
1357 for var_line in field_var_lines:
1358 if var_line.group(1) in trait_structs:
1359 write_c("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
1360 write_c("\treturn (void*) this_arg;\n")
1363 out_java.write("\t}\n")
1365 out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
1366 write_c("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
1367 for idx, var_line in enumerate(field_var_lines):
1368 if var_line.group(1) in trait_structs:
1369 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
1370 write_c(", jobject " + var_line.group(2))
1372 out_java.write(", " + field_var_convs[idx].java_ty + " " + var_line.group(2))
1373 write_c(", " + field_var_convs[idx].c_ty + " " + var_line.group(2))
1374 out_java.write(");\n")
1377 write_c("\tjclass c = (*env)->GetObjectClass(env, o);\n")
1378 write_c("\tCHECK(c != NULL);\n")
1379 write_c("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
1380 write_c("\tatomic_init(&calls->refcnt, 1);\n")
1381 write_c("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
1382 write_c("\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n")
1383 for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
1384 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1385 write_c("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
1386 write_c("\tCHECK(calls->" + fn_line.group(2) + "_meth != NULL);\n")
1387 for idx, var_line in enumerate(field_var_lines):
1388 if field_var_convs[idx] is not None and field_var_convs[idx].arg_conv is not None:
1389 write_c("\n\t" + field_var_convs[idx].arg_conv.replace("\n", "\n\t") +"\n")
1390 write_c("\n\t" + struct_name + " ret = {\n")
1391 write_c("\t\t.this_arg = (void*) calls,\n")
1392 for fn_line in trait_fn_lines:
1393 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1394 write_c("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
1395 elif fn_line.group(2) == "free":
1396 write_c("\t\t.free = " + struct_name + "_JCalls_free,\n")
1398 clone_fns.add(struct_name + "_clone")
1399 write_c("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
1400 for idx, var_line in enumerate(field_var_lines):
1401 if var_line.group(1) in trait_structs:
1402 write_c("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
1403 elif field_var_convs[idx].arg_conv_name is not None:
1404 write_c("\t\t." + var_line.group(2) + " = " + field_var_convs[idx].arg_conv_name + ",\n")
1405 write_c("\t\t.set_" + var_line.group(2) + " = NULL,\n")
1407 write_c("\t\t." + var_line.group(2) + " = " + var_line.group(2) + ",\n")
1408 write_c("\t\t.set_" + var_line.group(2) + " = NULL,\n")
1410 for var_line in field_var_lines:
1411 if var_line.group(1) in trait_structs:
1412 write_c("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
1413 write_c("\treturn ret;\n")
1416 write_c("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
1417 for idx, var_line in enumerate(field_var_lines):
1418 if var_line.group(1) in trait_structs:
1419 write_c(", jobject " + var_line.group(2))
1421 write_c(", " + field_var_convs[idx].c_ty + " " + var_line.group(2))
1423 write_c("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1424 write_c("\t*res_ptr = " + struct_name + "_init(env, _a, o")
1425 for var_line in field_var_lines:
1426 write_c(", " + var_line.group(2))
1428 write_c("\treturn (long)res_ptr;\n")
1431 out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
1432 write_c("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1get_1obj_1from_1jcalls (JNIEnv * env, jclass _a, jlong val) {\n")
1433 write_c("\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n")
1434 write_c("\tCHECK(ret != NULL);\n")
1435 write_c("\treturn ret;\n")
1438 for fn_line in trait_fn_lines:
1439 # For now, just disable enabling the _call_log - we don't know how to inverse-map String
1440 is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
1441 if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
1442 dummy_line = fn_line.group(1) + struct_name.replace("LDK", "") + "_" + fn_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
1443 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(2) + ")(this_arg_conv->this_arg")
1444 for idx, var_line in enumerate(field_var_lines):
1445 if var_line.group(1) not in trait_structs:
1446 write_c(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
1447 write_c("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
1448 write_c("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
1449 write_c("\treturn this_arg->" + var_line.group(2) + ";\n")
1451 dummy_line = var_line.group(1) + " " + struct_name.replace("LDK", "") + "_get_" + var_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
1452 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")
1454 out_java.write("""package org.ldk.impl;
1455 import org.ldk.enums.*;
1457 public class bindings {
1458 public static class VecOrSliceDef {
1459 public long dataptr;
1460 public long datalen;
1462 public VecOrSliceDef(long dataptr, long datalen, long stride) {
1463 this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
1467 System.loadLibrary(\"lightningjni\");
1468 init(java.lang.Enum.class, VecOrSliceDef.class);
1471 static native void init(java.lang.Class c, java.lang.Class slicedef);
1472 static native void init_class_cache();
1474 public static native boolean deref_bool(long ptr);
1475 public static native long deref_long(long ptr);
1476 public static native void free_heap_ptr(long ptr);
1477 public static native byte[] read_bytes(long ptr, long len);
1478 public static native byte[] get_u8_slice_bytes(long slice_ptr);
1479 public static native long bytes_to_u8_vec(byte[] bytes);
1480 public static native long new_txpointer_copy_data(byte[] txdata);
1481 public static native void txpointer_free(long ptr);
1482 public static native byte[] txpointer_get_buffer(long ptr);
1483 public static native long vec_slice_len(long vec);
1484 public static native long new_empty_slice_vec();
1488 static jmethodID ordinal_meth = NULL;
1489 static jmethodID slicedef_meth = NULL;
1490 static jclass slicedef_cls = NULL;
1491 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
1492 ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
1493 CHECK(ordinal_meth != NULL);
1494 slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
1495 CHECK(slicedef_meth != NULL);
1496 slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
1497 CHECK(slicedef_cls != NULL);
1500 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
1501 return *((bool*)ptr);
1503 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
1504 return *((long*)ptr);
1506 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
1509 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
1510 jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
1511 (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
1514 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
1515 LDKu8slice *slice = (LDKu8slice*)slice_ptr;
1516 jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
1517 (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
1520 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
1521 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
1522 vec->datalen = (*_env)->GetArrayLength(_env, bytes);
1523 vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
1524 (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
1527 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_txpointer_1get_1buffer (JNIEnv * env, jclass _b, jlong ptr) {
1528 LDKTransaction *txdata = (LDKTransaction*)ptr;
1530 slice.data = txdata->data;
1531 slice.datalen = txdata->datalen;
1532 return Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes(env, _b, (long)&slice);
1534 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
1535 LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
1536 txdata->datalen = (*env)->GetArrayLength(env, bytes);
1537 txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
1538 txdata->data_is_owned = false;
1539 (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
1540 return (long)txdata;
1542 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_txpointer_1free (JNIEnv * env, jclass _b, jlong ptr) {
1543 LDKTransaction *tx = (LDKTransaction*)ptr;
1544 tx->data_is_owned = true;
1545 Transaction_free(*tx);
1548 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
1549 // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
1550 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
1551 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
1552 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
1553 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
1554 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
1555 return (long)vec->datalen;
1557 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
1558 // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
1559 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
1560 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
1561 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
1562 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
1563 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
1569 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
1570 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
1571 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
1572 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
1576 with open(sys.argv[3] + "/structs/CommonBase.java", "a") as out_java_struct:
1577 out_java_struct.write("""package org.ldk.structs;
1578 import java.util.LinkedList;
1581 LinkedList<Object> ptrs_to = new LinkedList();
1582 protected CommonBase(long ptr) { this.ptr = ptr; }
1583 public long _test_only_get_ptr() { return this.ptr; }
1587 in_block_comment = False
1588 cur_block_obj = None
1590 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1592 line_indicates_result_regex = re.compile("^ (LDKCResultPtr_[A-Za-z_0-9]*) contents;$")
1593 line_indicates_vec_regex = re.compile("^ ([A-Za-z_0-9]*) \*data;$")
1594 line_indicates_opaque_regex = re.compile("^ bool is_owned;$")
1595 line_indicates_trait_regex = re.compile("^ ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
1596 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
1597 assert(line_indicates_trait_regex.match(" LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
1598 assert(line_indicates_trait_regex.match(" void *(*clone)(const void *this_arg);"))
1599 line_field_var_regex = re.compile("^ ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1600 assert(line_field_var_regex.match(" LDKMessageSendEventsProvider MessageSendEventsProvider;"))
1601 assert(line_field_var_regex.match(" LDKChannelPublicKeys pubkeys;"))
1602 struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
1603 assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
1604 assert(struct_name_regex.match("typedef enum LDKNetwork {"))
1605 struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
1606 assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
1608 result_templ_structs = set()
1609 union_enum_items = {}
1610 result_ptr_struct_items = {}
1612 if in_block_comment:
1613 if line.endswith("*/\n"):
1614 in_block_comment = False
1615 elif cur_block_obj is not None:
1616 cur_block_obj = cur_block_obj + line
1617 if line.startswith("} "):
1621 obj_lines = cur_block_obj.split("\n")
1623 result_contents = None
1624 is_unitary_enum = False
1625 is_union_enum = False
1629 field_var_lines = []
1631 for idx, struct_line in enumerate(obj_lines):
1632 if struct_line.strip().startswith("/*"):
1633 in_block_comment = True
1634 if in_block_comment:
1635 if struct_line.endswith("*/"):
1636 in_block_comment = False
1638 struct_name_match = struct_name_regex.match(struct_line)
1639 if struct_name_match is not None:
1640 struct_name = struct_name_match.group(3)
1641 if struct_name_match.group(1) == "enum":
1642 if not struct_name.endswith("_Tag"):
1643 is_unitary_enum = True
1645 is_union_enum = True
1646 elif struct_name_match.group(1) == "union":
1648 if line_indicates_opaque_regex.match(struct_line):
1650 result_match = line_indicates_result_regex.match(struct_line)
1651 if result_match is not None:
1652 result_contents = result_match.group(1)
1653 vec_ty_match = line_indicates_vec_regex.match(struct_line)
1654 if vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
1655 vec_ty = vec_ty_match.group(1)
1656 elif struct_name.startswith("LDKC2TupleTempl_") or struct_name.startswith("LDKC3TupleTempl_"):
1658 trait_fn_match = line_indicates_trait_regex.match(struct_line)
1659 if trait_fn_match is not None:
1660 trait_fn_lines.append(trait_fn_match)
1661 field_var_match = line_field_var_regex.match(struct_line)
1662 if field_var_match is not None:
1663 field_var_lines.append(field_var_match)
1664 field_lines.append(struct_line)
1666 assert(struct_name is not None)
1667 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))
1668 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))
1669 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))
1670 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))
1671 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))
1672 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))
1673 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))
1676 opaque_structs.add(struct_name)
1677 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_struct:
1678 out_java_struct.write(hu_struct_file_prefix)
1679 out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase")
1680 if struct_name.startswith("LDKLocked"):
1681 out_java_struct.write(" implements AutoCloseable")
1682 out_java_struct.write(" {\n")
1683 out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
1684 if struct_name.startswith("LDKLocked"):
1685 out_java_struct.write("\t@Override public void close() {\n")
1687 out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1688 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1689 out_java_struct.write("\t\tsuper.finalize();\n")
1690 out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1691 out_java_struct.write("\t}\n\n")
1692 elif result_contents is not None:
1693 result_templ_structs.add(struct_name)
1694 assert result_contents in result_ptr_struct_items
1695 elif struct_name.startswith("LDKCResultPtr_"):
1696 for line in field_lines:
1697 if line.endswith("*result;"):
1698 res_ty = line[:-8].strip()
1699 elif line.endswith("*err;"):
1700 err_ty = line[:-5].strip()
1701 result_ptr_struct_items[struct_name] = (res_ty, err_ty)
1703 out_java.write("\tpublic static native long " + struct_name + "_new(")
1704 write_c("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *_env, jclass _b")
1706 for idx, line in enumerate(field_lines):
1707 if idx != 0 and idx < len(field_lines) - 2:
1708 ty_info = java_c_types(line.strip(';'), None)
1710 out_java.write(", ")
1711 e = chr(ord('a') + idx - 1)
1712 out_java.write(ty_info.java_ty + " " + e)
1713 write_c(", " + ty_info.c_ty + " " + e)
1714 ty_list.append(ty_info)
1715 tuple_types[struct_name] = (ty_list, struct_name)
1716 out_java.write(");\n")
1718 write_c("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1719 for idx, line in enumerate(field_lines):
1720 if idx != 0 and idx < len(field_lines) - 2:
1721 ty_info = map_type(line.strip(';'), False, None, False, False)
1722 e = chr(ord('a') + idx - 1)
1723 if ty_info.arg_conv is not None:
1724 write_c("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
1725 write_c("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
1727 write_c("\tret->" + e + " = " + e + ";\n")
1728 if ty_info.arg_conv_cleanup is not None:
1729 write_c("\t//TODO: Really need to call " + ty_info.arg_conv_cleanup + " here\n")
1730 write_c("\treturn (long)ret;\n")
1732 elif vec_ty is not None:
1733 if vec_ty in opaque_structs:
1734 out_java.write("\tpublic static native long[] " + struct_name + "_arr_info(long vec_ptr);\n")
1735 write_c("JNIEXPORT jlongArray JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1737 out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
1738 write_c("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1739 write_c("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
1740 if vec_ty in opaque_structs:
1741 write_c("\tjlongArray ret = (*env)->NewLongArray(env, vec->datalen);\n")
1742 write_c("\tjlong *ret_elems = (*env)->GetPrimitiveArrayCritical(env, ret, NULL);\n")
1743 write_c("\tfor (size_t i = 0; i < vec->datalen; i++) {\n")
1744 write_c("\t\tCHECK((((long)vec->data[i].inner) & 1) == 0);\n")
1745 write_c("\t\tret_elems[i] = (long)vec->data[i].inner | (vec->data[i].is_owned ? 1 : 0);\n")
1747 write_c("\t(*env)->ReleasePrimitiveArrayCritical(env, ret, ret_elems, 0);\n")
1748 write_c("\treturn ret;\n")
1750 write_c("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
1753 ty_info = map_type(vec_ty + " arr_elem", False, None, False, False)
1754 if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
1755 out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
1756 write_c("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *env, jclass _b, j" + ty_info.java_ty + "Array elems){\n")
1757 write_c("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1758 write_c("\tret->datalen = (*env)->GetArrayLength(env, elems);\n")
1759 write_c("\tif (ret->datalen == 0) {\n")
1760 write_c("\t\tret->data = NULL;\n")
1761 write_c("\t} else {\n")
1762 write_c("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1763 write_c("\t\t" + ty_info.c_ty + " *java_elems = (*env)->GetPrimitiveArrayCritical(env, elems, NULL);\n")
1764 write_c("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1765 if ty_info.arg_conv is not None:
1766 write_c("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1767 write_c("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1768 write_c("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1769 assert ty_info.arg_conv_cleanup is None
1771 write_c("\t\t\tret->data[i] = java_elems[i];\n")
1773 write_c("\t\t(*env)->ReleasePrimitiveArrayCritical(env, elems, java_elems, 0);\n")
1775 write_c("\treturn (long)ret;\n")
1778 assert(struct_name.endswith("_Tag"))
1779 struct_name = struct_name[:-4]
1780 union_enum_items[struct_name] = {"field_lines": field_lines}
1781 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
1782 enum_var_name = struct_name.split("_")
1783 union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
1784 elif struct_name in union_enum_items:
1785 map_complex_enum(struct_name, union_enum_items[struct_name])
1786 elif is_unitary_enum:
1787 map_unitary_enum(struct_name, field_lines)
1788 elif len(trait_fn_lines) > 0:
1789 trait_structs.add(struct_name)
1790 map_trait(struct_name, field_var_lines, trait_fn_lines)
1791 elif struct_name == "LDKTxOut":
1792 with open(sys.argv[3] + "/structs/TxOut.java", "w") as out_java_struct:
1793 out_java_struct.write(hu_struct_file_prefix)
1794 out_java_struct.write("public class TxOut extends CommonBase{\n")
1795 out_java_struct.write("\tTxOut(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
1796 out_java_struct.write("\tlong to_c_ptr() { return 0; }\n")
1798 out_java_struct.write("}")
1800 pass # Everything remaining is a byte[] or some form
1801 cur_block_obj = None
1803 fn_ptr = fn_ptr_regex.match(line)
1804 fn_ret_arr = fn_ret_arr_regex.match(line)
1805 reg_fn = reg_fn_regex.match(line)
1806 const_val = const_val_regex.match(line)
1808 if line.startswith("#include <"):
1810 elif line.startswith("/*"):
1811 #out_java.write("\t" + line)
1812 if not line.endswith("*/\n"):
1813 in_block_comment = True
1814 elif line.startswith("typedef enum "):
1815 cur_block_obj = line
1816 elif line.startswith("typedef struct "):
1817 cur_block_obj = line
1818 elif line.startswith("typedef union "):
1819 cur_block_obj = line
1820 elif line.startswith("typedef "):
1821 alias_match = struct_alias_regex.match(line)
1822 if alias_match.group(1) in tuple_types:
1823 tuple_types[alias_match.group(2)] = (tuple_types[alias_match.group(1)][0], alias_match.group(2))
1824 tuple_types[alias_match.group(1)] = (tuple_types[alias_match.group(1)][0], alias_match.group(2))
1825 for idx, ty_info in enumerate(tuple_types[alias_match.group(1)][0]):
1826 e = chr(ord('a') + idx)
1827 out_java.write("\tpublic static native " + ty_info.java_ty + " " + alias_match.group(2) + "_get_" + e + "(long ptr);\n")
1828 write_c("JNIEXPORT " + ty_info.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1" + e + "(JNIEnv *_env, jclass _b, jlong ptr) {\n")
1829 write_c("\t" + alias_match.group(1) + " *tuple = (" + alias_match.group(1) + "*)ptr;\n")
1830 conv_info = map_type_with_info(ty_info, False, None, False, True)
1831 if conv_info.ret_conv is not None:
1832 write_c("\t" + conv_info.ret_conv[0].replace("\n", "\n\t") + "tuple->" + e + conv_info.ret_conv[1].replace("\n", "\n\t") + "\n")
1833 write_c("\treturn " + conv_info.ret_conv_name + ";\n")
1835 write_c("\treturn tuple->" + e + ";\n")
1837 elif alias_match.group(1) in result_templ_structs:
1838 result_types.add(alias_match.group(2))
1839 human_ty = alias_match.group(2).replace("LDKCResult", "Result")
1840 with open(sys.argv[3] + "/structs/" + human_ty + ".java", "w") as out_java_struct:
1841 out_java_struct.write(hu_struct_file_prefix)
1842 out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
1843 out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
1844 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1845 out_java_struct.write("\t\tif (ptr != 0) { bindings." + alias_match.group(2).replace("LDK","") + "_free(ptr); } super.finalize();\n")
1846 out_java_struct.write("\t}\n\n")
1847 out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
1848 out_java_struct.write("\t\tif (bindings." + alias_match.group(2) + "_result_ok(ptr)) {\n")
1849 out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
1850 out_java_struct.write("\t\t} else {\n")
1851 out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
1852 out_java_struct.write("\t\t}\n")
1853 out_java_struct.write("\t}\n")
1855 contents_ty = alias_match.group(1).replace("LDKCResultTempl", "LDKCResultPtr")
1856 res_ty, err_ty = result_ptr_struct_items[contents_ty]
1857 res_map = map_type(res_ty + " res", True, None, False, True)
1858 err_map = map_type(err_ty + " err", True, None, False, True)
1860 out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
1861 write_c("JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1result_1ok (JNIEnv * env, jclass _a, jlong arg) {\n")
1862 write_c("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
1865 out_java.write("\tpublic static native " + res_map.java_ty + " " + alias_match.group(2) + "_get_ok(long arg);\n")
1866 write_c("JNIEXPORT " + res_map.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1ok (JNIEnv * _env, jclass _a, jlong arg) {\n")
1867 write_c("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
1868 write_c("\tCHECK(val->result_ok);\n\t")
1869 out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
1870 if res_map.ret_conv is not None:
1871 write_c(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
1872 write_c(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
1874 write_c("return *val->contents.result")
1877 out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
1878 out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
1879 out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1880 if res_map.to_hu_conv is not None:
1881 out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + alias_match.group(2) + "_get_ok(ptr);\n")
1882 out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1883 out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
1885 out_java_struct.write("\t\t\tthis.res = bindings." + alias_match.group(2) + "_get_ok(ptr);\n")
1886 out_java_struct.write("\t\t}\n")
1887 if alias_match.group(2).startswith("LDKCResult_None"):
1888 out_java_struct.write("\t\tpublic " + human_ty + "_OK() {\n\t\t\tthis(null, bindings.C" + human_ty + "_ok());\n")
1890 out_java_struct.write("\t\tpublic " + human_ty + "_OK(" + res_map.java_hu_ty + " res) {\n")
1891 if res_map.from_hu_conv is not None:
1892 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(" + res_map.from_hu_conv[0] + "));\n")
1893 if res_map.from_hu_conv[1] != "":
1894 out_java_struct.write("\t\t\t" + res_map.from_hu_conv[1] + ";\n")
1896 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(res));\n")
1897 out_java_struct.write("\t\t}\n\t}\n\n")
1899 out_java.write("\tpublic static native " + err_map.java_ty + " " + alias_match.group(2) + "_get_err(long arg);\n")
1900 write_c("JNIEXPORT " + err_map.c_ty + " JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1get_1err (JNIEnv * _env, jclass _a, jlong arg) {\n")
1901 write_c("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
1902 write_c("\tCHECK(!val->result_ok);\n\t")
1903 out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
1904 if err_map.ret_conv is not None:
1905 write_c(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
1906 write_c(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
1908 write_c("return *val->contents.err")
1911 out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
1912 out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
1913 out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1914 if err_map.to_hu_conv is not None:
1915 out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + alias_match.group(2) + "_get_err(ptr);\n")
1916 out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1917 out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
1919 out_java_struct.write("\t\t\tthis.err = bindings." + alias_match.group(2) + "_get_err(ptr);\n")
1920 out_java_struct.write("\t\t}\n")
1922 if alias_match.group(2).endswith("NoneZ"):
1923 out_java_struct.write("\t\tpublic " + human_ty + "_Err() {\n\t\t\tthis(null, bindings.C" + human_ty + "_err());\n")
1925 out_java_struct.write("\t\tpublic " + human_ty + "_Err(" + err_map.java_hu_ty + " err) {\n")
1926 if err_map.from_hu_conv is not None:
1927 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(" + err_map.from_hu_conv[0] + "));\n")
1928 if err_map.from_hu_conv[1] != "":
1929 out_java_struct.write("\t\t\t" + err_map.from_hu_conv[1] + ";\n")
1931 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(err));\n")
1932 out_java_struct.write("\t\t}\n\t}\n}\n")
1933 elif fn_ptr is not None:
1934 map_fn(line, fn_ptr, None, None)
1935 elif fn_ret_arr is not None:
1936 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1937 elif reg_fn is not None:
1938 map_fn(line, reg_fn, None, None)
1939 elif const_val_regex is not None:
1940 # TODO Map const variables
1943 assert(line == "\n")
1945 out_java.write("}\n")
1946 for struct_name in opaque_structs:
1947 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1948 out_java_struct.write("}\n")
1949 for struct_name in trait_structs:
1950 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1951 out_java_struct.write("}\n")
1952 with open(sys.argv[4], "w") as out_c:
1953 out_c.write(c_file_pfx)
1954 for ty in c_array_class_caches:
1955 if ty + "_clz" in c_file:
1956 out_c.write("static jclass " + ty + "_clz = NULL;\n")
1957 out_c.write("JNIEXPORT void Java_org_ldk_impl_bindings_init_1class_1cache(JNIEnv * env, jclass _b) {\n")
1958 for ty in c_array_class_caches:
1959 if ty + "_clz" in c_file:
1960 out_c.write("\t" + ty + "_clz = (*env)->FindClass(env, \"" + ty.replace("arr_of_", "[") + "\");\n")
1961 out_c.write("\tCHECK(" + ty + "_clz != NULL);\n")
1962 out_c.write("\t" + ty + "_clz = (*env)->NewGlobalRef(env, " + ty + "_clz);\n")