5 print("USAGE: /path/to/lightning.h /path/to/bindings/output /path/to/bindings/ /path/to/bindings/output.c debug lang")
8 if sys.argv[5] == "false":
10 elif sys.argv[5] == "true":
13 print("debug should be true or false and indicates whether to track allocations and ensure we don't leak")
16 if sys.argv[6] == "java":
17 from java_strings import Consts
18 elif sys.argv[6] == "typescript":
19 from typescript_strings import Consts
21 print("Only java or typescript can be set for lang")
23 consts = Consts(DEBUG)
25 from bindingstypes import *
32 def camel_to_snake(s):
33 # Convert camel case to snake case, in a way that appears to match cbindgen
39 if lastchar.isupper():
40 if not char.isupper() and not lastund:
45 ret = ret + lastchar.lower()
48 if char.isupper() and not lastund:
56 return (ret + lastchar.lower()).strip("_")
60 opaque_structs = set()
65 var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([a-z0-9]*)\]")
66 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
67 java_c_types_none_allowed = True # Unset when we do the real pass that populates the above sets
68 def java_c_types(fn_arg, ret_arr_len):
69 fn_arg = fn_arg.strip()
70 if fn_arg.startswith("MUST_USE_RES "):
73 if fn_arg.startswith("const "):
76 if fn_arg.startswith("struct "):
78 if fn_arg.startswith("enum "):
80 fn_arg = fn_arg.replace("NONNULL_PTR", "")
87 if fn_arg.startswith("LDKThirtyTwoBytes"):
88 fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
89 assert var_is_arr_regex.match(fn_arg[8:])
90 rust_obj = "LDKThirtyTwoBytes"
92 elif fn_arg.startswith("LDKPublicKey"):
93 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
94 assert var_is_arr_regex.match(fn_arg[8:])
95 rust_obj = "LDKPublicKey"
96 arr_access = "compressed_form"
97 elif fn_arg.startswith("LDKSecretKey"):
98 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
99 assert var_is_arr_regex.match(fn_arg[8:])
100 rust_obj = "LDKSecretKey"
102 elif fn_arg.startswith("LDKSignature"):
103 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
104 assert var_is_arr_regex.match(fn_arg[8:])
105 rust_obj = "LDKSignature"
106 arr_access = "compact_form"
107 elif fn_arg.startswith("LDKThreeBytes"):
108 fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
109 assert var_is_arr_regex.match(fn_arg[8:])
110 rust_obj = "LDKThreeBytes"
112 elif fn_arg.startswith("LDKFourBytes"):
113 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[4]"
114 assert var_is_arr_regex.match(fn_arg[8:])
115 rust_obj = "LDKFourBytes"
117 elif fn_arg.startswith("LDKSixteenBytes"):
118 fn_arg = "uint8_t (*" + fn_arg[16:] + ")[16]"
119 assert var_is_arr_regex.match(fn_arg[8:])
120 rust_obj = "LDKSixteenBytes"
122 elif fn_arg.startswith("LDKTenBytes"):
123 fn_arg = "uint8_t (*" + fn_arg[12:] + ")[10]"
124 assert var_is_arr_regex.match(fn_arg[8:])
125 rust_obj = "LDKTenBytes"
127 elif fn_arg.startswith("LDKu8slice"):
128 fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
129 assert var_is_arr_regex.match(fn_arg[8:])
130 rust_obj = "LDKu8slice"
132 elif fn_arg.startswith("LDKCVec_u8Z"):
133 fn_arg = "uint8_t (*" + fn_arg[12:] + ")[datalen]"
134 rust_obj = "LDKCVec_u8Z"
135 assert var_is_arr_regex.match(fn_arg[8:])
137 elif fn_arg.startswith("LDKTransaction"):
138 fn_arg = "uint8_t (*" + fn_arg[15:] + ")[datalen]"
139 rust_obj = "LDKTransaction"
140 assert var_is_arr_regex.match(fn_arg[8:])
142 elif fn_arg.startswith("LDKCVec_"):
145 fn_arg = fn_arg.replace("*", "")
148 tyn = fn_arg[8:].split(" ")
149 assert tyn[0].endswith("Z")
153 new_arg = "LDK" + tyn[0][:-1]
155 new_arg = new_arg + " " + a
156 res = java_c_types(new_arg, ret_arr_len)
158 assert java_c_types_none_allowed
161 res.pass_by_ref = True
162 if res.is_native_primitive or res.passed_as_ptr:
163 return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
164 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=res.c_ty + "Array", passed_as_ptr=False, is_ptr=is_ptr, is_const=is_const,
165 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
167 return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
168 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=consts.ptr_arr, passed_as_ptr=False, is_ptr=is_ptr, is_const=is_const,
169 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
174 java_type_plural = None
175 if fn_arg.startswith("void"):
179 fn_arg = fn_arg[4:].strip()
181 elif fn_arg.startswith("bool"):
185 fn_arg = fn_arg[4:].strip()
187 elif fn_arg.startswith("uint8_t"):
188 mapped_type = consts.c_type_map['uint8_t']
189 java_ty = mapped_type[0]
192 fn_arg = fn_arg[7:].strip()
194 elif fn_arg.startswith("uint16_t"):
195 mapped_type = consts.c_type_map['uint16_t']
196 java_ty = mapped_type[0]
199 fn_arg = fn_arg[8:].strip()
201 elif fn_arg.startswith("uint32_t"):
202 mapped_type = consts.c_type_map['uint32_t']
203 java_ty = mapped_type[0]
206 fn_arg = fn_arg[8:].strip()
208 elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
209 # TODO: uintptr_t is arch-dependent :(
210 mapped_type = consts.c_type_map['long']
211 java_ty = mapped_type[0]
214 if fn_arg.startswith("uint64_t"):
215 fn_arg = fn_arg[8:].strip()
217 fn_arg = fn_arg[9:].strip()
219 elif is_const and fn_arg.startswith("char *"):
222 fn_ty_arg = "Ljava/lang/String;"
223 fn_arg = fn_arg[6:].strip()
224 elif fn_arg.startswith("LDKStr"):
227 fn_ty_arg = "Ljava/lang/String;"
228 fn_arg = fn_arg[6:].strip()
232 ma = var_ty_regex.match(fn_arg)
233 if ma.group(1).strip() in unitary_enums:
234 java_ty = ma.group(1).strip()
235 c_ty = consts.result_c_ty
236 fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
237 fn_arg = ma.group(2).strip()
238 rust_obj = ma.group(1).strip()
239 elif ma.group(1).strip().startswith("LDKC2Tuple"):
240 c_ty = consts.ptr_c_ty
241 java_ty = consts.ptr_native_ty
242 java_hu_ty = "TwoTuple<"
243 if not ma.group(1).strip() in tuple_types:
244 assert java_c_types_none_allowed
246 for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
248 java_hu_ty = java_hu_ty + ", "
249 if ty_info.is_native_primitive:
250 if ty_info.java_hu_ty == "int":
251 java_hu_ty = java_hu_ty + "Integer" # Java concrete integer type is Integer, not Int
253 java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
255 java_hu_ty = java_hu_ty + ty_info.java_hu_ty
256 java_hu_ty = java_hu_ty + ">"
258 fn_arg = ma.group(2).strip()
259 rust_obj = ma.group(1).strip()
261 elif ma.group(1).strip().startswith("LDKC3Tuple"):
262 c_ty = consts.ptr_c_ty
263 java_ty = consts.ptr_native_ty
264 java_hu_ty = "ThreeTuple<"
265 if not ma.group(1).strip() in tuple_types:
266 assert java_c_types_none_allowed
268 for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
270 java_hu_ty = java_hu_ty + ", "
271 if ty_info.is_native_primitive:
272 if ty_info.java_hu_ty == "int":
273 java_hu_ty = java_hu_ty + "Integer" # Java concrete integer type is Integer, not Int
275 java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
277 java_hu_ty = java_hu_ty + ty_info.java_hu_ty
278 java_hu_ty = java_hu_ty + ">"
280 fn_arg = ma.group(2).strip()
281 rust_obj = ma.group(1).strip()
284 c_ty = consts.ptr_c_ty
285 java_ty = consts.ptr_native_ty
286 java_hu_ty = ma.group(1).strip().replace("LDKCResult", "Result").replace("LDK", "")
288 fn_arg = ma.group(2).strip()
289 rust_obj = ma.group(1).strip()
292 if fn_arg.startswith(" *") or fn_arg.startswith("*"):
293 fn_arg = fn_arg.replace("*", "").strip()
295 c_ty = consts.ptr_c_ty
296 java_ty = consts.ptr_native_ty
300 var_is_arr = var_is_arr_regex.match(fn_arg)
301 if var_is_arr is not None or ret_arr_len is not None:
302 assert(not take_by_ptr)
304 # is there a special case for plurals?
305 if len(mapped_type) == 2:
306 java_ty = mapped_type[1]
308 java_ty = java_ty + "[]"
309 c_ty = c_ty + "Array"
310 if var_is_arr is not None:
311 if var_is_arr.group(1) == "":
312 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty, is_const=is_const,
313 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)
314 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty, is_const=is_const,
315 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)
317 if java_hu_ty is None:
319 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,
320 is_const=is_const, is_ptr=is_ptr, var_name=fn_arg, arr_len=arr_len, arr_access=arr_access, is_native_primitive=is_primitive)
322 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
323 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
324 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
327 c_array_class_caches = set()
328 with open(sys.argv[1]) as in_h:
330 reg_fn = reg_fn_regex.match(line)
331 if reg_fn is not None:
332 if reg_fn.group(2).endswith("_clone"):
333 clone_fns.add(reg_fn.group(2))
335 rty = java_c_types(reg_fn.group(1), None)
336 if rty is not None and rty.rust_obj is not None and reg_fn.group(2) == rty.java_hu_ty + "_new":
337 constructor_fns[rty.rust_obj] = reg_fn.group(3)
339 arr_fn = fn_ret_arr_regex.match(line)
340 if arr_fn is not None:
341 if arr_fn.group(2).endswith("_clone"):
342 clone_fns.add(arr_fn.group(2))
343 # No object constructors return arrays, as then they wouldn't be an object constructor
346 # Define some manual clones...
347 clone_fns.add("ThirtyTwoBytes_clone")
348 write_c("static inline struct LDKThirtyTwoBytes ThirtyTwoBytes_clone(const struct LDKThirtyTwoBytes *orig) { struct LDKThirtyTwoBytes ret; memcpy(ret.data, orig->data, 32); return ret; }\n")
350 java_c_types_none_allowed = False # C structs created by cbindgen are declared in dependency order
352 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java:
353 def map_type(fn_arg, print_void, ret_arr_len, is_free, holds_ref):
354 ty_info = java_c_types(fn_arg, ret_arr_len)
355 return map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref)
357 def map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref):
358 if ty_info.c_ty == "void":
360 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
361 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
362 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
363 if ty_info.c_ty.endswith("Array"):
364 arr_len = ty_info.arr_len
365 if arr_len is not None:
366 arr_name = ty_info.var_name
369 arr_len = ret_arr_len
370 if ty_info.c_ty == "int8_tArray":
371 (set_pfx, set_sfx) = consts.set_native_arr_contents(arr_name + "_arr", arr_len, ty_info)
372 ret_conv = ("int8_tArray " + arr_name + "_arr = " + consts.create_native_arr_call(arr_len, ty_info) + ";\n" + set_pfx, "")
373 arg_conv_cleanup = None
374 if not arr_len.isdigit():
375 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
376 arg_conv = arg_conv + arr_name + "_ref." + arr_len + " = " + consts.get_native_arr_len_call[0] + arr_name + consts.get_native_arr_len_call[1] + ";\n"
377 if (not ty_info.is_ptr or not holds_ref) and ty_info.rust_obj != "LDKu8slice":
378 arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = MALLOC(" + arr_name + "_ref." + arr_len + ", \"" + ty_info.rust_obj + " Bytes\");\n"
379 arg_conv = arg_conv + consts.get_native_arr_contents(arr_name, arr_name + "_ref." + ty_info.arr_access, arr_name + "_ref." + arr_len, ty_info, True) + ";"
381 arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = " + consts.get_native_arr_contents(arr_name, "NO_DEST", arr_name + "_ref." + arr_len, ty_info, False) + ";"
382 arg_conv_cleanup = consts.cleanup_native_arr_ref_contents(arr_name, arr_name + "_ref." + ty_info.arr_access, arr_name + "_ref." + arr_len, ty_info)
383 if ty_info.rust_obj == "LDKTransaction":
384 arg_conv = arg_conv + "\n" + arr_name + "_ref.data_is_owned = " + str(holds_ref).lower() + ";"
385 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
386 ret_conv = (ret_conv[0], ";\nint8_tArray " + arr_name + "_arr = " + consts.create_native_arr_call(arr_name + "_var." + arr_len, ty_info) + ";\n")
387 (pfx, sfx) = consts.set_native_arr_contents(arr_name + "_arr", arr_name + "_var." + arr_len, ty_info)
388 ret_conv = (ret_conv[0], ret_conv[1] + pfx + arr_name + "_var." + ty_info.arr_access + sfx + ";")
389 if not holds_ref and ty_info.rust_obj != "LDKu8slice":
390 ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
391 elif ty_info.rust_obj is not None:
392 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
393 arg_conv = arg_conv + "CHECK(" + consts.get_native_arr_len_call[0] + arr_name + consts.get_native_arr_len_call[1] + " == " + arr_len + ");\n"
394 arg_conv = arg_conv + consts.get_native_arr_contents(arr_name, arr_name + "_ref." + ty_info.arr_access, arr_len, ty_info, True) + ";"
395 ret_conv = (ret_conv[0], "." + ty_info.arr_access + set_sfx + ";")
397 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n"
398 arg_conv = arg_conv + "CHECK(" + consts.get_native_arr_len_call[0] + arr_name + consts.get_native_arr_len_call[1] + " == " + arr_len + ");\n"
399 arg_conv = arg_conv + consts.get_native_arr_contents(arr_name, arr_name + "_arr", arr_len, ty_info, True) + ";\n"
400 arg_conv = arg_conv + "unsigned char (*" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;"
401 ret_conv = (ret_conv[0] + "*", set_sfx + ";")
402 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
403 arg_conv = arg_conv, arg_conv_name = arr_name + "_ref", arg_conv_cleanup = arg_conv_cleanup,
404 ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
406 assert not arr_len.isdigit() # fixed length arrays not implemented
407 assert ty_info.java_ty[len(ty_info.java_ty) - 2:] == "[]"
408 conv_name = "arr_conv_" + str(len(ty_info.java_hu_ty))
409 idxc = chr(ord('a') + (len(ty_info.java_hu_ty) % 26))
410 ty_info.subty.var_name = conv_name
411 #XXX: We'd really prefer to only ever set to False, avoiding lots of clone, but need smarter free logic
412 #if ty_info.is_ptr or holds_ref:
413 # ty_info.subty.requires_clone = False
414 ty_info.subty.requires_clone = not ty_info.is_ptr or not holds_ref
415 subty = map_type_with_info(ty_info.subty, False, None, is_free, holds_ref)
418 arg_conv = ty_info.rust_obj + " " + arr_name + "_constr;\n"
419 arg_conv = arg_conv + arr_name + "_constr." + arr_len + " = " + consts.get_native_arr_len_call[0] + arr_name + consts.get_native_arr_len_call[1] + ";\n"
420 arg_conv = arg_conv + "if (" + arr_name + "_constr." + arr_len + " > 0)\n"
421 if subty.rust_obj is None:
424 szof = subty.rust_obj
425 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"
426 arg_conv = arg_conv + "else\n"
427 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = NULL;\n"
428 get_arr = consts.get_native_arr_contents(arr_name, "NO_DEST", arr_name + "_constr." + arr_len, ty_info, False)
430 arg_conv = arg_conv + subty.c_ty + "* " + arr_name + "_vals = " + get_arr + ";\n"
431 arg_conv = arg_conv + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_constr." + arr_len + "; " + idxc + "++) {\n"
433 arg_conv = arg_conv + "\t" + subty.c_ty + " " + conv_name + " = " + arr_name + "_vals[" + idxc + "];"
434 if subty.arg_conv is not None:
435 arg_conv = arg_conv + "\n\t" + subty.arg_conv.replace("\n", "\n\t")
437 arg_conv = arg_conv + "\t" + subty.c_ty + " " + conv_name + " = " + consts.get_native_arr_elem(arr_name, idxc, ty_info) + ";\n"
438 arg_conv = arg_conv + "\t" + subty.arg_conv.replace("\n", "\n\t")
439 arg_conv = arg_conv + "\n\t" + arr_name + "_constr." + ty_info.arr_access + "[" + idxc + "] = " + subty.arg_conv_name + ";\n}"
441 cleanup = consts.cleanup_native_arr_ref_contents(arr_name, arr_name + "_vals", arr_name + "_constr." + arr_len, ty_info)
442 if cleanup is not None:
443 arg_conv = arg_conv + "\n" + cleanup + ";"
445 arg_conv_name = "&" + arr_name + "_constr"
447 arg_conv_name = arr_name + "_constr"
448 arg_conv_cleanup = None
450 arg_conv_cleanup = "FREE(" + arr_name + "_constr." + ty_info.arr_access + ");"
452 if arr_name == "arg":
454 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
455 if subty.ret_conv is None:
456 ret_conv = ("DUMMY", "DUMMY")
457 elif not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
458 ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = " + consts.create_native_arr_call(arr_name + "_var." + arr_len, ty_info) + ";\n")
459 ret_conv = (ret_conv[0], ret_conv[1] + subty.c_ty + " *" + arr_name + "_arr_ptr = " + consts.get_native_arr_ptr_call[0] + arr_name + "_arr" + consts.get_native_arr_ptr_call[1] + ";\n")
460 ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
461 ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
462 ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
463 ret_conv = (ret_conv[0], ret_conv[1] + "\n\t" + arr_name + "_arr_ptr[" + idxc + "] = " + subty.ret_conv_name + ";\n}")
464 cleanup = consts.release_native_arr_ptr_call(arr_name + "_arr", arr_name + "_arr_ptr")
465 if cleanup is not None:
466 ret_conv = (ret_conv[0], ret_conv[1] + "\n" + cleanup + ";")
468 assert ty_info.java_fn_ty_arg.startswith("[")
469 clz_var = ty_info.java_fn_ty_arg[1:].replace("[", "arr_of_")
470 c_array_class_caches.add(clz_var)
471 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")
472 ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
473 ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
474 ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
475 ret_conv = (ret_conv[0], ret_conv[1] + "\n\t(*env)->SetObjectArrayElement(env, " + arr_name + "_arr, " + idxc + ", " + subty.ret_conv_name + ");\n")
476 ret_conv = (ret_conv[0], ret_conv[1] + "}")
478 # XXX: The commented if's are a bit smarter freeing, but we need to be a nudge smarter still
479 # Note that we don't drop the full vec here - we're passing ownership to java (or have cloned) or free'd by now!
480 ret_conv = (ret_conv[0], ret_conv[1] + "\nFREE(" + arr_name + "_var." + ty_info.arr_access + ");")
481 #if subty.rust_obj is not None and subty.rust_obj in opaque_structs:
482 # ret_conv = (ret_conv[0], ret_conv[1] + "\nFREE(" + arr_name + "_var." + ty_info.arr_access + ");")
484 # ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
487 to_hu_conv_name = None
488 if subty.to_hu_conv is not None:
489 to_hu_conv = ty_info.java_hu_ty + " " + conv_name + "_arr = new " + ty_info.subty.java_hu_ty.split("<")[0] + "[" + arr_name + ".length];\n"
490 to_hu_conv = to_hu_conv + "for (int " + idxc + " = 0; " + idxc + " < " + arr_name + ".length; " + idxc + "++) {\n"
491 to_hu_conv = to_hu_conv + "\t" + subty.java_ty + " " + conv_name + " = " + arr_name + "[" + idxc + "];\n"
492 to_hu_conv = to_hu_conv + "\t" + subty.to_hu_conv.replace("\n", "\n\t") + "\n"
493 to_hu_conv = to_hu_conv + "\t" + conv_name + "_arr[" + idxc + "] = " + subty.to_hu_conv_name + ";\n}"
494 to_hu_conv_name = conv_name + "_arr"
496 if subty.from_hu_conv is not None:
497 if subty.java_ty == "long" and subty.java_hu_ty != "long":
498 from_hu_conv = ("Arrays.stream(" + arr_name + ").mapToLong(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + " */")
499 elif subty.java_ty == "long":
500 from_hu_conv = ("Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + " */")
502 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 + " */")
504 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
505 arg_conv = arg_conv, arg_conv_name = arg_conv_name, arg_conv_cleanup = arg_conv_cleanup,
506 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)
507 elif ty_info.java_ty == "String":
508 if ty_info.arr_access is None:
509 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
510 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
511 ret_conv = ("jstring " + ty_info.var_name + "_conv = (*env)->NewStringUTF(env, ", ");"), ret_conv_name = ty_info.var_name + "_conv",
512 to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
514 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
515 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
516 ret_conv = ("LDKStr " + ty_info.var_name + "_str = ",
517 ";\nchar* " + ty_info.var_name + "_buf = MALLOC(" + ty_info.var_name + "_str." + ty_info.arr_len + " + 1, \"str conv buf\");\n" +
518 "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" +
519 ty_info.var_name + "_buf[" + ty_info.var_name + "_str." + ty_info.arr_len + "] = 0;\n" +
520 "jstring " + ty_info.var_name + "_conv = (*env)->NewStringUTF(env, " + ty_info.var_name + "_str." + ty_info.arr_access + ");\n" +
521 "FREE(" + ty_info.var_name + "_buf);"),
522 ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
523 elif ty_info.var_name == "" and not print_void:
524 # We don't have a parameter name, and want one, just call it arg
525 if ty_info.rust_obj is not None:
526 assert(not is_free or ty_info.rust_obj not in opaque_structs)
527 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
528 arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
529 arg_conv_name = "arg_conv", arg_conv_cleanup = None,
530 ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 7", to_hu_conv_name = None, from_hu_conv = None)
533 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
534 arg_conv = None, arg_conv_name = "arg", arg_conv_cleanup = None,
535 ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 8", to_hu_conv_name = None, from_hu_conv = None)
536 elif ty_info.rust_obj is None:
537 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
538 arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None,
539 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
541 if ty_info.var_name == "":
542 ty_info.var_name = "ret"
544 if ty_info.rust_obj in opaque_structs:
545 opaque_arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv;\n"
546 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
547 if ty_info.is_ptr and holds_ref:
548 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = false;"
550 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
551 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:
552 if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
553 # 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.
554 opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
555 opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&" + ty_info.var_name + "_conv);"
556 elif ty_info.passed_as_ptr:
557 opaque_arg_conv = opaque_arg_conv + "\n// Warning: we may need a move here but can't clone!"
559 opaque_ret_conv_suf = ";\n"
560 if not holds_ref and ty_info.is_ptr and (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns: # is_ptr, not holds_ref implies passing a pointed-to value to java, which needs copied
561 opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "->inner != NULL)\n"
562 opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_var = " + ty_info.rust_obj.replace("LDK", "") + "_clone(" + ty_info.var_name + ");\n"
563 elif not holds_ref and ty_info.is_ptr:
564 opaque_ret_conv_suf = opaque_ret_conv_suf + "// Warning: we may need a move here but can't clone!\n"
566 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"
567 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"
569 opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner & ~1;"
571 opaque_ret_conv_suf = opaque_ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner;\n"
572 opaque_ret_conv_suf = opaque_ret_conv_suf + "if (" + ty_info.var_name + "_var.is_owned) {\n"
573 opaque_ret_conv_suf = opaque_ret_conv_suf + "\t" + ty_info.var_name + "_ref |= 1;\n"
574 opaque_ret_conv_suf = opaque_ret_conv_suf + "}"
577 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
578 arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv", arg_conv_cleanup = None,
579 ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = *", opaque_ret_conv_suf),
580 ret_conv_name = ty_info.var_name + "_ref",
581 # 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 + ");",
582 to_hu_conv = consts.to_hu_conv_templates['ptr'].replace('{human_type}', ty_info.java_hu_ty).replace('{var_name}', ty_info.var_name),
583 to_hu_conv_name = ty_info.var_name + "_hu_conv",
584 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
586 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
587 arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
588 ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", opaque_ret_conv_suf),
589 ret_conv_name = ty_info.var_name + "_ref",
590 # 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 + ");",
591 to_hu_conv = consts.to_hu_conv_templates['default'].replace('{human_type}', ty_info.java_hu_ty).replace('{var_name}', ty_info.var_name),
592 to_hu_conv_name = ty_info.var_name + "_hu_conv",
593 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
595 if not ty_info.is_ptr:
596 if ty_info.rust_obj in unitary_enums:
597 (ret_pfx, ret_sfx) = consts.c_unitary_enum_to_native_call(ty_info)
598 (arg_pfx, arg_sfx) = consts.native_unitary_enum_to_c_call(ty_info)
599 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
600 arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + arg_pfx + ty_info.var_name + arg_sfx + ";",
601 arg_conv_name = ty_info.var_name + "_conv",
602 arg_conv_cleanup = None,
603 ret_conv = (ty_info.c_ty + " " + ty_info.var_name + "_conv = " + ret_pfx, ret_sfx + ";"),
604 ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
605 base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";"
606 if ty_info.rust_obj in trait_structs:
608 needs_full_clone = not is_free and (not ty_info.is_ptr and not holds_ref or ty_info.requires_clone == True) and ty_info.requires_clone != False
609 if needs_full_clone and (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
610 base_conv = base_conv + "\n" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(" + ty_info.var_name + ");"
612 base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
613 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
614 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
616 base_conv = base_conv + "// Warning: we may need a move here but can't do a full clone!\n"
619 base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
620 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
621 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
622 ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
623 ret_conv_name = "(long)ret",
624 to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");\nret_hu_conv.ptrs_to.add(this);",
625 to_hu_conv_name = "ret_hu_conv",
626 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
627 if ty_info.rust_obj != "LDKu8slice":
628 # Don't bother free'ing slices passed in - Rust doesn't auto-free the
629 # underlying unlike Vecs, and it gives Java more freedom.
630 base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
631 if ty_info.rust_obj in complex_enums:
632 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";")
634 ret_conv = (ty_info.rust_obj + " *" + ty_info.var_name + "_copy = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n", "")
635 if ty_info.requires_clone == True: # Set in object array mapping
636 if (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
637 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&", ");\n")
639 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", "; // XXX: We likely need to clone here, but no _clone fn is available!\n")
641 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = ", ";\n")
642 ret_conv = (ret_conv[0], ret_conv[1] + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_copy;")
643 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
644 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
645 ret_conv = ret_conv, ret_conv_name = ty_info.var_name + "_ref",
646 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);",
647 to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
648 if ty_info.rust_obj in result_types:
650 # If we're trying to return a ref, we have to clone.
651 # We just blindly assume its implemented and let the compiler fail if its not.
652 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 = ", ";")
653 ret_conv = (ret_conv[0], ret_conv[1] + "\n*" + ty_info.var_name + "_conv = " + ty_info.rust_obj.replace("LDK", "") + "_clone(" + ty_info.var_name + "_conv);")
655 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 = ", ";")
656 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
657 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
658 ret_conv = ret_conv, ret_conv_name = "(long)" + ty_info.var_name + "_conv",
659 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 + ");",
660 to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + " != null ? " + ty_info.var_name + ".ptr : 0", ""))
661 if ty_info.rust_obj in tuple_types:
662 from_hu_conv = "bindings." + tuple_types[ty_info.rust_obj][1].replace("LDK", "") + "_new("
664 to_hu_conv_sfx = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " + ty_info.java_hu_ty + "("
666 for idx, conv in enumerate(tuple_types[ty_info.rust_obj][0]):
668 to_hu_conv_sfx = to_hu_conv_sfx + ", "
669 from_hu_conv = from_hu_conv + ", "
670 conv.var_name = ty_info.var_name + "_" + chr(idx + ord("a"))
671 conv_map = map_type_with_info(conv, False, None, is_free, holds_ref)
672 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"
673 if conv_map.to_hu_conv is not None:
674 to_hu_conv_pfx = to_hu_conv_pfx + conv_map.to_hu_conv + ";\n"
675 to_hu_conv_sfx = to_hu_conv_sfx + conv_map.to_hu_conv_name
677 to_hu_conv_sfx = to_hu_conv_sfx + ty_info.var_name + "_" + chr(idx + ord("a"))
678 if conv_map.from_hu_conv is not None:
679 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")))
680 if conv_map.from_hu_conv[1] != "":
681 from_hu_conv = from_hu_conv + "/*XXX: " + conv_map.from_hu_conv[1] + "*/"
683 from_hu_conv = from_hu_conv + ty_info.var_name + "." + chr(idx + ord("a"))
685 if conv.is_native_primitive:
687 elif (conv_map.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
688 accessor = ty_info.var_name + "_ref->" + chr(idx + ord("a"))
689 clone_ret_str = clone_ret_str + "\n" + accessor + " = " + conv_map.rust_obj.replace("LDK", "") + "_clone(&" + accessor + ");"
691 clone_ret_str = clone_ret_str + "\n// XXX: We likely need to clone here, but no _clone fn is available for " + conv_map.java_hu_ty
692 if not ty_info.is_ptr and not holds_ref:
693 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 = ", ";")
694 if not is_free and (not ty_info.is_ptr and not holds_ref or ty_info.requires_clone == True) and ty_info.requires_clone != False:
695 ret_conv = (ret_conv[0], ret_conv[1] + clone_ret_str)
696 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
697 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
699 ret_conv_name = "(long)" + ty_info.var_name + "_ref",
700 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 + ")", ""))
701 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
702 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
703 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
704 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 + ")", ""))
706 # The manually-defined types - TxOut and Transaction
707 assert ty_info.rust_obj == "LDKTxOut"
708 if not ty_info.is_ptr and not holds_ref:
709 ret_conv = ("LDKTxOut* " + ty_info.var_name + "_ref = MALLOC(sizeof(LDKTxOut), \"LDKTxOut\");\n*" + ty_info.var_name + "_ref = ", ";")
711 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";")
712 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
713 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
714 ret_conv = ret_conv, ret_conv_name = "(long)" + ty_info.var_name + "_ref",
715 to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " +ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
716 to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
719 if ty_info.rust_obj in complex_enums:
720 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
721 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
722 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
723 ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
724 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 + ");",
725 to_hu_conv_name = ty_info.var_name + "_hu_conv",
726 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
727 elif ty_info.rust_obj in trait_structs:
728 if ty_info.rust_obj.replace("LDK", "") + "_clone" in clone_fns:
729 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
730 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
731 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
732 ret_conv = (ty_info.rust_obj + " *" + ty_info.var_name + "_clone = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n" +
733 "*" + ty_info.var_name + "_clone = " + ty_info.rust_obj.replace("LDK", "") + "_clone(", ");"),
734 ret_conv_name = "(long)" + ty_info.var_name + "_clone",
735 to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");\nret_hu_conv.ptrs_to.add(this);",
736 to_hu_conv_name = "ret_hu_conv",
737 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
739 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
740 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
741 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
742 ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
743 to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");\nret_hu_conv.ptrs_to.add(this);",
744 to_hu_conv_name = "ret_hu_conv",
745 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
746 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
747 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
748 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
749 ret_conv = ("long ret_" + ty_info.var_name + " = (long)", ";"), ret_conv_name = "ret_" + ty_info.var_name,
750 to_hu_conv = "TODO 3", to_hu_conv_name = None, from_hu_conv = None) # its a pointer, no conv needed
751 assert False # We should have handled every case by now.
753 def map_fn(line, re_match, ret_arr_len, c_call_string):
754 out_java.write("\t// " + line)
755 out_java.write("\tpublic static native ")
756 write_c(consts.c_fn_ty_pfx)
758 is_free = re_match.group(2).endswith("_free")
759 struct_meth = re_match.group(2).split("_")[0]
761 ret_info = map_type(re_match.group(1), True, ret_arr_len, False, False)
762 write_c(ret_info.c_ty)
763 out_java.write(ret_info.java_ty)
765 if ret_info.ret_conv is not None:
766 ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
768 out_java.write(" " + re_match.group(2) + "(")
769 write_c(" " + consts.c_fn_name_pfx + re_match.group(2).replace('_', '_1') + "(" + consts.c_fn_args_pfx)
772 default_constructor_args = {}
775 for idx, arg in enumerate(re_match.group(3).split(',')):
780 arg_conv_info = map_type(arg, False, None, is_free, True)
781 if arg_conv_info.c_ty != "void":
782 write_c(arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
783 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
784 if idx == 0 and arg_conv_info.java_hu_ty == struct_meth:
786 if arg_conv_info.arg_conv is not None and "Warning" in arg_conv_info.arg_conv:
787 if arg_conv_info.rust_obj in constructor_fns:
789 for explode_arg in constructor_fns[arg_conv_info.rust_obj].split(','):
790 explode_arg_conv = map_type(explode_arg, False, None, False, True)
791 if explode_arg_conv.c_ty == "void":
792 # We actually want to handle this case, but for now its only used in NetGraphMsgHandler::new()
793 # which ends up resulting in a redundant constructor - both without arguments for the NetworkGraph.
796 if not arg_conv_info.arg_name in default_constructor_args:
797 default_constructor_args[arg_conv_info.arg_name] = []
798 default_constructor_args[arg_conv_info.arg_name].append(explode_arg_conv)
799 arg_names.append(arg_conv_info)
801 out_java_struct = None
802 if ("LDK" + struct_meth in opaque_structs or "LDK" + struct_meth in trait_structs) and not is_free:
803 out_java_struct = open(f"{sys.argv[3]}/structs/{struct_meth}{consts.file_ext}", "a")
805 out_java_struct.write("\t// Skipped " + re_match.group(2) + "\n")
806 out_java_struct.close()
807 out_java_struct = None
809 meth_n = re_match.group(2)[len(struct_meth) + 1:]
811 out_java_struct.write("\tpublic static " + ret_info.java_hu_ty + " constructor_" + meth_n + "(")
813 out_java_struct.write("\tpublic " + ret_info.java_hu_ty + " " + meth_n + "(")
814 for idx, arg in enumerate(arg_names):
816 if not takes_self or idx > 1:
817 out_java_struct.write(", ")
820 if arg.java_ty != "void":
821 if arg.arg_name in default_constructor_args:
822 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
824 out_java_struct.write(", ")
825 out_java_struct.write(explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
827 out_java_struct.write(arg.java_hu_ty + " " + arg.arg_name)
830 out_java.write(");\n")
832 if out_java_struct is not None:
833 out_java_struct.write(") {\n")
835 for info in arg_names:
836 if info.arg_conv is not None:
837 write_c("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
839 if ret_info.ret_conv is not None:
840 write_c("\t" + ret_conv_pfx.replace('\n', '\n\t'))
841 elif ret_info.c_ty != "void":
842 write_c("\t" + ret_info.c_ty + " ret_val = ")
846 if c_call_string is None:
847 write_c(re_match.group(2) + "(")
849 write_c(c_call_string)
850 for idx, info in enumerate(arg_names):
851 if info.arg_conv_name is not None:
854 elif c_call_string is not None:
856 write_c(info.arg_conv_name)
858 if ret_info.ret_conv is not None:
859 write_c(ret_conv_sfx.replace('\n', '\n\t'))
862 for info in arg_names:
863 if info.arg_conv_cleanup is not None:
864 write_c("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
865 if ret_info.ret_conv is not None:
866 write_c("\n\treturn " + ret_info.ret_conv_name + ";")
867 elif ret_info.c_ty != "void":
868 write_c("\n\treturn ret_val;")
870 if out_java_struct is not None:
871 out_java_struct.write("\t\t")
872 if ret_info.java_ty != "void":
873 out_java_struct.write(ret_info.java_ty + " ret = ")
874 out_java_struct.write("bindings." + re_match.group(2) + "(")
875 for idx, info in enumerate(arg_names):
877 out_java_struct.write(", ")
878 if idx == 0 and takes_self:
879 out_java_struct.write("this.ptr")
880 elif info.arg_name in default_constructor_args:
881 out_java_struct.write("bindings." + info.java_hu_ty + "_new(")
882 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
884 out_java_struct.write(", ")
885 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
886 if explode_arg.from_hu_conv is not None:
887 out_java_struct.write(explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
889 out_java_struct.write(expl_arg_name)
890 out_java_struct.write(")")
891 elif info.from_hu_conv is not None:
892 out_java_struct.write(info.from_hu_conv[0])
894 out_java_struct.write(info.arg_name)
895 out_java_struct.write(");\n")
896 if ret_info.to_hu_conv is not None:
898 out_java_struct.write("\t\t" + ret_info.to_hu_conv.replace("\n", "\n\t\t").replace("this", ret_info.to_hu_conv_name) + "\n")
900 out_java_struct.write("\t\t" + ret_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
902 for idx, info in enumerate(arg_names):
903 if idx == 0 and takes_self:
905 elif info.arg_name in default_constructor_args:
906 for explode_arg in default_constructor_args[info.arg_name]:
907 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
908 if explode_arg.from_hu_conv is not None and ret_info.to_hu_conv_name:
909 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")
910 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
911 if not takes_self and ret_info.to_hu_conv_name is not None:
912 out_java_struct.write("\t\t" + info.from_hu_conv[1].replace("this", ret_info.to_hu_conv_name) + ";\n")
914 out_java_struct.write("\t\t" + info.from_hu_conv[1] + ";\n")
916 if ret_info.to_hu_conv_name is not None:
917 out_java_struct.write("\t\treturn " + ret_info.to_hu_conv_name + ";\n")
918 elif ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
919 out_java_struct.write("\t\treturn ret;\n")
920 out_java_struct.write("\t}\n\n")
921 out_java_struct.close()
923 def map_unitary_enum(struct_name, field_lines):
924 with open(f"{sys.argv[3]}/enums/{struct_name}{consts.file_ext}", "w") as out_java_enum:
925 unitary_enums.add(struct_name)
926 for idx, struct_line in enumerate(field_lines):
928 assert(struct_line == "typedef enum %s {" % struct_name)
929 elif idx == len(field_lines) - 3:
930 assert(struct_line.endswith("_Sentinel,"))
931 elif idx == len(field_lines) - 2:
932 assert(struct_line == "} %s;" % struct_name)
933 elif idx == len(field_lines) - 1:
934 assert(struct_line == "")
935 (c_out, native_file_out, native_out) = consts.native_c_unitary_enum_map(struct_name, [x.strip().strip(",") for x in field_lines[1:-3]])
937 out_java_enum.write(native_file_out)
938 out_java.write(native_out)
940 def map_complex_enum(struct_name, union_enum_items):
941 java_hu_type = struct_name.replace("LDK", "")
942 complex_enums.add(struct_name)
945 tag_field_lines = union_enum_items["field_lines"]
946 for idx, struct_line in enumerate(tag_field_lines):
948 assert(struct_line == "typedef enum %s_Tag {" % struct_name)
949 elif idx == len(tag_field_lines) - 3:
950 assert(struct_line.endswith("_Sentinel,"))
951 elif idx == len(tag_field_lines) - 2:
952 assert(struct_line == "} %s_Tag;" % struct_name)
953 elif idx == len(tag_field_lines) - 1:
954 assert(struct_line == "")
956 variant_name = struct_line.strip(' ,')[len(struct_name) + 1:]
958 if "LDK" + variant_name in union_enum_items:
959 enum_var_lines = union_enum_items["LDK" + variant_name]
960 for idx, field in enumerate(enum_var_lines):
961 if idx != 0 and idx < len(enum_var_lines) - 2:
962 fields.append(map_type(field.strip(' ;'), False, None, False, True))
964 # TODO: Assert line format
967 # TODO: Assert line format
969 enum_variants.append(ComplexEnumVariantInfo(variant_name, fields))
971 with open(f"{sys.argv[3]}/structs/{java_hu_type}{consts.file_ext}", "w") as out_java_enum:
972 (out_java_addendum, out_java_enum_addendum, out_c_addendum) = consts.map_complex_enum(struct_name, enum_variants, camel_to_snake)
974 out_java_enum.write(out_java_enum_addendum)
975 out_java.write(out_java_addendum)
976 write_c(out_c_addendum)
978 def map_trait(struct_name, field_var_lines, trait_fn_lines):
979 with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "w") as out_java_trait:
981 for var_line in field_var_lines:
982 if var_line.group(1) in trait_structs:
983 field_var_convs.append((var_line.group(1), var_line.group(2)))
985 field_var_convs.append(map_type(var_line.group(1) + " " + var_line.group(2), False, None, False, False))
988 for fn_line in trait_fn_lines:
989 ret_ty_info = map_type(fn_line.group(2), True, None, False, False)
990 is_const = fn_line.group(4) is not None
993 for idx, arg in enumerate(fn_line.group(5).split(',')):
996 arg_conv_info = map_type(arg, True, None, False, False)
997 arg_tys.append(arg_conv_info)
998 field_fns.append(TraitMethInfo(fn_line.group(3), is_const, ret_ty_info, arg_tys))
1000 (out_java_addendum, out_java_trait_addendum, out_c_addendum) = consts.native_c_map_trait(struct_name, field_var_convs, field_fns)
1001 write_c(out_c_addendum)
1002 out_java_trait.write(out_java_trait_addendum)
1003 out_java.write(out_java_addendum)
1005 for fn_line in trait_fn_lines:
1006 # For now, just disable enabling the _call_log - we don't know how to inverse-map String
1007 is_log = fn_line.group(3) == "log" and struct_name == "LDKLogger"
1008 if fn_line.group(3) != "free" and fn_line.group(3) != "clone" and fn_line.group(3) != "eq" and not is_log:
1009 dummy_line = fn_line.group(2) + struct_name.replace("LDK", "") + "_" + fn_line.group(3) + " " + struct_name + "* this_arg" + fn_line.group(5) + "\n"
1010 map_fn(dummy_line, re.compile("([A-Za-z_0-9]*) *([A-Za-z_0-9]*) *(.*)").match(dummy_line), None, "(this_arg_conv->" + fn_line.group(3) + ")(this_arg_conv->this_arg")
1011 for idx, var_line in enumerate(field_var_lines):
1012 if var_line.group(1) not in trait_structs:
1013 write_c(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
1014 write_c("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
1015 write_c("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
1016 write_c("\treturn this_arg->" + var_line.group(2) + ";\n")
1018 dummy_line = var_line.group(1) + " " + struct_name.replace("LDK", "") + "_get_" + var_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(5) + "\n"
1019 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")
1021 def map_result(struct_name, res_ty, err_ty):
1022 result_types.add(struct_name)
1023 human_ty = struct_name.replace("LDKCResult", "Result")
1024 with open(f"{sys.argv[3]}/structs/{human_ty}{consts.file_ext}", "w") as out_java_struct:
1025 out_java_struct.write(consts.hu_struct_file_prefix)
1026 out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
1027 out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
1028 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1029 out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
1030 out_java_struct.write("\t}\n\n")
1031 out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
1032 out_java_struct.write("\t\tif (bindings." + struct_name + "_result_ok(ptr)) {\n")
1033 out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
1034 out_java_struct.write("\t\t} else {\n")
1035 out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
1036 out_java_struct.write("\t\t}\n")
1037 out_java_struct.write("\t}\n")
1039 res_map = map_type(res_ty + " res", True, None, False, True)
1040 err_map = map_type(err_ty + " err", True, None, False, True)
1042 if not res_map.is_native_primitive and (res_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
1044 if not err_map.is_native_primitive and (err_map.rust_obj.replace("LDK", "") + "_clone" not in clone_fns):
1047 out_java.write("\tpublic static native boolean " + struct_name + "_result_ok(long arg);\n")
1048 write_c(consts.c_fn_ty_pfx + "jboolean " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1result_1ok (" + consts.c_fn_args_pfx + ", " + consts.ptr_c_ty + " arg) {\n")
1049 write_c("\treturn ((" + struct_name + "*)arg)->result_ok;\n")
1052 out_java.write("\tpublic static native " + res_map.java_ty + " " + struct_name + "_get_ok(long arg);\n")
1053 write_c(consts.c_fn_ty_pfx + res_map.c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1ok (" + consts.c_fn_args_pfx + ", " + consts.ptr_c_ty + " arg) {\n")
1054 write_c("\t" + struct_name + " *val = (" + struct_name + "*)arg;\n")
1055 write_c("\tCHECK(val->result_ok);\n\t")
1056 out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
1057 if res_map.ret_conv is not None:
1058 write_c(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
1059 write_c(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
1061 write_c("return *val->contents.result")
1064 if res_map.java_hu_ty != "void":
1065 out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
1066 out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
1067 out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1068 if res_map.java_hu_ty == "void":
1070 elif res_map.to_hu_conv is not None:
1071 out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + struct_name + "_get_ok(ptr);\n")
1072 out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1073 out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
1075 out_java_struct.write("\t\t\tthis.res = bindings." + struct_name + "_get_ok(ptr);\n")
1076 out_java_struct.write("\t\t}\n")
1077 if struct_name.startswith("LDKCResult_None"):
1078 out_java_struct.write("\t\tpublic " + human_ty + "_OK() {\n\t\t\tthis(null, bindings.C" + human_ty + "_ok());\n")
1080 out_java_struct.write("\t\tpublic " + human_ty + "_OK(" + res_map.java_hu_ty + " res) {\n")
1081 if res_map.from_hu_conv is not None:
1082 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(" + res_map.from_hu_conv[0] + "));\n")
1083 if res_map.from_hu_conv[1] != "":
1084 out_java_struct.write("\t\t\t" + res_map.from_hu_conv[1] + ";\n")
1086 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(res));\n")
1087 out_java_struct.write("\t\t}\n\t}\n\n")
1089 out_java.write("\tpublic static native " + err_map.java_ty + " " + struct_name + "_get_err(long arg);\n")
1090 write_c(consts.c_fn_ty_pfx + err_map.c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1err (" + consts.c_fn_args_pfx + ", " + consts.ptr_c_ty + " arg) {\n")
1091 write_c("\t" + struct_name + " *val = (" + struct_name + "*)arg;\n")
1092 write_c("\tCHECK(!val->result_ok);\n\t")
1093 out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
1094 if err_map.ret_conv is not None:
1095 write_c(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
1096 write_c(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
1098 write_c("return *val->contents.err")
1101 if err_map.java_hu_ty != "void":
1102 out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
1103 out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
1104 out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1105 if err_map.java_hu_ty == "void":
1107 elif err_map.to_hu_conv is not None:
1108 out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + struct_name + "_get_err(ptr);\n")
1109 out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1110 out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
1112 out_java_struct.write("\t\t\tthis.err = bindings." + struct_name + "_get_err(ptr);\n")
1113 out_java_struct.write("\t\t}\n")
1115 if struct_name.endswith("NoneZ"):
1116 out_java_struct.write("\t\tpublic " + human_ty + "_Err() {\n\t\t\tthis(null, bindings.C" + human_ty + "_err());\n")
1118 out_java_struct.write("\t\tpublic " + human_ty + "_Err(" + err_map.java_hu_ty + " err) {\n")
1119 if err_map.from_hu_conv is not None:
1120 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(" + err_map.from_hu_conv[0] + "));\n")
1121 if err_map.from_hu_conv[1] != "":
1122 out_java_struct.write("\t\t\t" + err_map.from_hu_conv[1] + ";\n")
1124 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(err));\n")
1125 out_java_struct.write("\t\t}\n\t}\n}\n")
1128 clone_fns.add(struct_name.replace("LDK", "") + "_clone")
1129 write_c("static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n")
1130 write_c("\t" + struct_name + " res = { .result_ok = orig->result_ok };\n")
1131 write_c("\tif (orig->result_ok) {\n")
1132 if res_map.c_ty == "void":
1133 write_c("\t\tres.contents.result = NULL;\n")
1135 if res_map.is_native_primitive:
1136 write_c("\t\t" + res_map.c_ty + "* contents = MALLOC(sizeof(" + res_map.c_ty + "), \"" + res_map.c_ty + " result OK clone\");\n")
1137 write_c("\t\t*contents = *orig->contents.result;\n")
1139 write_c("\t\t" + res_map.rust_obj + "* contents = MALLOC(sizeof(" + res_map.rust_obj + "), \"" + res_map.rust_obj + " result OK clone\");\n")
1140 write_c("\t\t*contents = " + res_map.rust_obj.replace("LDK", "") + "_clone(orig->contents.result);\n")
1141 write_c("\t\tres.contents.result = contents;\n")
1142 write_c("\t} else {\n")
1143 if err_map.c_ty == "void":
1144 write_c("\t\tres.contents.err = NULL;\n")
1146 if err_map.is_native_primitive:
1147 write_c("\t\t" + err_map.c_ty + "* contents = MALLOC(sizeof(" + err_map.c_ty + "), \"" + err_map.c_ty + " result Err clone\");\n")
1148 write_c("\t\t*contents = *orig->contents.err;\n")
1150 write_c("\t\t" + err_map.rust_obj + "* contents = MALLOC(sizeof(" + err_map.rust_obj + "), \"" + err_map.rust_obj + " result Err clone\");\n")
1151 write_c("\t\t*contents = " + err_map.rust_obj.replace("LDK", "") + "_clone(orig->contents.err);\n")
1152 write_c("\t\tres.contents.err = contents;\n")
1153 write_c("\t}\n\treturn res;\n}\n")
1155 def map_tuple(struct_name, field_lines):
1156 out_java.write("\tpublic static native long " + struct_name + "_new(")
1157 write_c(consts.c_fn_ty_pfx + consts.ptr_c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1new(" + consts.c_fn_args_pfx)
1159 for idx, line in enumerate(field_lines):
1160 if idx != 0 and idx < len(field_lines) - 2:
1161 ty_info = java_c_types(line.strip(';'), None)
1163 out_java.write(", ")
1164 e = chr(ord('a') + idx - 1)
1165 out_java.write(ty_info.java_ty + " " + e)
1166 write_c(", " + ty_info.c_ty + " " + e)
1167 ty_list.append(ty_info)
1168 tuple_types[struct_name] = (ty_list, struct_name)
1169 out_java.write(");\n")
1171 write_c("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1173 clone_str = "static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n"
1174 clone_str = clone_str + "\t" + struct_name + " ret = {\n"
1175 for idx, line in enumerate(field_lines):
1176 if idx != 0 and idx < len(field_lines) - 2:
1177 ty_info = map_type(line.strip(';'), False, None, False, False)
1178 e = chr(ord('a') + idx - 1)
1179 if ty_info.arg_conv is not None:
1180 write_c("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
1181 write_c("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
1183 write_c("\tret->" + e + " = " + e + ";\n")
1184 if ty_info.arg_conv_cleanup is not None:
1185 write_c("\t//TODO: Really need to call " + ty_info.arg_conv_cleanup + " here\n")
1186 if not ty_info.is_native_primitive and (ty_info.rust_obj.replace("LDK", "") + "_clone") not in clone_fns:
1188 elif can_clone and ty_info.is_native_primitive:
1189 clone_str = clone_str + "\t\t." + chr(ord('a') + idx - 1) + " = orig->" + chr(ord('a') + idx - 1) + ",\n"
1191 clone_str = clone_str + "\t\t." + chr(ord('a') + idx - 1) + " = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&orig->" + chr(ord('a') + idx - 1) + "),\n"
1192 write_c("\treturn (long)ret;\n")
1196 clone_fns.add(struct_name.replace("LDK", "") + "_clone")
1198 write_c("\t};\n\treturn ret;\n}\n")
1200 for idx, ty_info in enumerate(ty_list):
1201 e = chr(ord('a') + idx)
1202 out_java.write("\tpublic static native " + ty_info.java_ty + " " + struct_name + "_get_" + e + "(long ptr);\n")
1203 write_c(consts.c_fn_ty_pfx + ty_info.c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1" + e + "(" + consts.c_fn_args_pfx + ", " + consts.ptr_c_ty + " ptr) {\n")
1204 write_c("\t" + struct_name + " *tuple = (" + struct_name + "*)ptr;\n")
1205 conv_info = map_type_with_info(ty_info, False, None, False, True)
1206 if conv_info.ret_conv is not None:
1207 write_c("\t" + conv_info.ret_conv[0].replace("\n", "\n\t") + "tuple->" + e + conv_info.ret_conv[1].replace("\n", "\n\t") + "\n")
1208 write_c("\treturn " + conv_info.ret_conv_name + ";\n")
1210 write_c("\treturn tuple->" + e + ";\n")
1213 out_java.write("""package org.ldk.impl;
1214 import org.ldk.enums.*;
1216 public class bindings {
1217 public static class VecOrSliceDef {
1218 public long dataptr;
1219 public long datalen;
1221 public VecOrSliceDef(long dataptr, long datalen, long stride) {
1222 this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
1226 System.loadLibrary(\"lightningjni\");
1227 init(java.lang.Enum.class, VecOrSliceDef.class);
1230 static native void init(java.lang.Class c, java.lang.Class slicedef);
1231 static native void init_class_cache();
1233 public static native boolean deref_bool(long ptr);
1234 public static native long deref_long(long ptr);
1235 public static native void free_heap_ptr(long ptr);
1236 public static native byte[] read_bytes(long ptr, long len);
1237 public static native byte[] get_u8_slice_bytes(long slice_ptr);
1238 public static native long bytes_to_u8_vec(byte[] bytes);
1239 public static native long new_txpointer_copy_data(byte[] txdata);
1240 public static native void txpointer_free(long ptr);
1241 public static native byte[] txpointer_get_buffer(long ptr);
1242 public static native long vec_slice_len(long vec);
1243 public static native long new_empty_slice_vec();
1247 with open(f"{sys.argv[3]}/structs/CommonBase{consts.file_ext}", "w") as out_java_struct:
1248 out_java_struct.write(consts.common_base)
1250 in_block_comment = False
1251 cur_block_obj = None
1253 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1255 line_indicates_result_regex = re.compile("^ union (LDKCResult_[A-Za-z_0-9]*Ptr) contents;$")
1256 line_indicates_vec_regex = re.compile("^ (struct |enum |union )?([A-Za-z_0-9]*) \*data;$")
1257 line_indicates_opaque_regex = re.compile("^ bool is_owned;$")
1258 line_indicates_trait_regex = re.compile("^ (struct |enum |union )?([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
1259 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
1260 assert(line_indicates_trait_regex.match(" struct LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
1261 assert(line_indicates_trait_regex.match(" void *(*clone)(const void *this_arg);"))
1262 assert(line_indicates_trait_regex.match(" struct LDKCVec_u8Z (*write)(const void *this_arg);"))
1263 line_field_var_regex = re.compile("^ struct ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1264 assert(line_field_var_regex.match(" struct LDKMessageSendEventsProvider MessageSendEventsProvider;"))
1265 assert(line_field_var_regex.match(" struct LDKChannelPublicKeys pubkeys;"))
1266 struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
1267 assert(struct_name_regex.match("typedef struct LDKCVec_u8Z {"))
1268 assert(struct_name_regex.match("typedef enum LDKNetwork {"))
1270 union_enum_items = {}
1271 result_ptr_struct_items = {}
1273 if in_block_comment:
1274 if line.endswith("*/\n"):
1275 in_block_comment = False
1276 elif cur_block_obj is not None:
1277 cur_block_obj = cur_block_obj + line
1278 if line.startswith("} "):
1282 obj_lines = cur_block_obj.split("\n")
1284 result_contents = None
1285 is_unitary_enum = False
1286 is_union_enum = False
1290 field_var_lines = []
1292 for idx, struct_line in enumerate(obj_lines):
1293 if struct_line.strip().startswith("/*"):
1294 in_block_comment = True
1295 if in_block_comment:
1296 if struct_line.endswith("*/"):
1297 in_block_comment = False
1299 struct_name_match = struct_name_regex.match(struct_line)
1300 if struct_name_match is not None:
1301 struct_name = struct_name_match.group(3)
1302 if struct_name_match.group(1) == "enum":
1303 if not struct_name.endswith("_Tag"):
1304 is_unitary_enum = True
1306 is_union_enum = True
1307 elif struct_name_match.group(1) == "union":
1309 if line_indicates_opaque_regex.match(struct_line):
1311 result_match = line_indicates_result_regex.match(struct_line)
1312 if result_match is not None:
1313 result_contents = result_match.group(1)
1314 vec_ty_match = line_indicates_vec_regex.match(struct_line)
1315 if vec_ty_match is not None and struct_name.startswith("LDKCVec_"):
1316 vec_ty = vec_ty_match.group(2)
1317 elif struct_name.startswith("LDKC2Tuple_") or struct_name.startswith("LDKC3Tuple_"):
1319 trait_fn_match = line_indicates_trait_regex.match(struct_line)
1320 if trait_fn_match is not None:
1321 trait_fn_lines.append(trait_fn_match)
1322 field_var_match = line_field_var_regex.match(struct_line)
1323 if field_var_match is not None:
1324 field_var_lines.append(field_var_match)
1325 field_lines.append(struct_line)
1327 assert(struct_name is not None)
1328 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))
1329 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))
1330 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))
1331 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))
1332 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))
1333 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))
1334 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))
1337 opaque_structs.add(struct_name)
1338 with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "w") as out_java_struct:
1339 out_java_struct.write(consts.hu_struct_file_prefix)
1340 out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase")
1341 if struct_name.startswith("LDKLocked"):
1342 out_java_struct.write(" implements AutoCloseable")
1343 out_java_struct.write(" {\n")
1344 out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
1345 if struct_name.startswith("LDKLocked"):
1346 out_java_struct.write("\t@Override public void close() {\n")
1348 out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1349 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1350 out_java_struct.write("\t\tsuper.finalize();\n")
1351 out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1352 out_java_struct.write("\t}\n\n")
1353 elif result_contents is not None:
1354 assert result_contents in result_ptr_struct_items
1355 res_ty, err_ty = result_ptr_struct_items[result_contents]
1356 map_result(struct_name, res_ty, err_ty)
1357 elif struct_name.startswith("LDKCResult_") and struct_name.endswith("ZPtr"):
1358 for line in field_lines:
1359 if line.endswith("*result;"):
1360 res_ty = line[:-8].strip()
1361 elif line.endswith("*err;"):
1362 err_ty = line[:-5].strip()
1363 result_ptr_struct_items[struct_name] = (res_ty, err_ty)
1364 result_types.add(struct_name[:-3])
1366 map_tuple(struct_name, field_lines)
1367 elif vec_ty is not None:
1368 ty_info = map_type(vec_ty + " arr_elem", False, None, False, False)
1369 if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
1370 out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
1371 write_c(consts.c_fn_ty_pfx + consts.ptr_c_ty + " " + consts.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1new(" + consts.c_fn_args_pfx + ", " + ty_info.c_ty + "Array elems) {\n")
1372 write_c("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1373 write_c("\tret->datalen = " + consts.get_native_arr_len_call[0] + "elems" + consts.get_native_arr_len_call[1] + ";\n")
1374 write_c("\tif (ret->datalen == 0) {\n")
1375 write_c("\t\tret->data = NULL;\n")
1376 write_c("\t} else {\n")
1377 write_c("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1378 write_c("\t\t" + ty_info.c_ty + " *java_elems = " + consts.get_native_arr_ptr_call[0] + "elems" + consts.get_native_arr_ptr_call[1] + ";\n")
1379 write_c("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1380 if ty_info.arg_conv is not None:
1381 write_c("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1382 write_c("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1383 write_c("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1384 assert ty_info.arg_conv_cleanup is None
1386 write_c("\t\t\tret->data[i] = java_elems[i];\n")
1388 cleanup = consts.release_native_arr_ptr_call("elems", "java_elems")
1389 if cleanup is not None:
1390 write_c("\t\t" + cleanup + ";\n")
1392 write_c("\treturn (long)ret;\n")
1395 if ty_info.is_native_primitive:
1396 clone_fns.add(struct_name.replace("LDK", "") + "_clone")
1397 write_c("static inline " + struct_name + " " + struct_name.replace("LDK", "") + "_clone(const " + struct_name + " *orig) {\n")
1398 write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.c_ty + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
1399 write_c("\tmemcpy(ret.data, orig->data, sizeof(" + ty_info.c_ty + ") * ret.datalen);\n")
1400 write_c("\treturn ret;\n}\n")
1401 elif (ty_info.rust_obj.replace("LDK", "") + "_clone") in clone_fns:
1402 ty_name = "CVec_" + ty_info.rust_obj.replace("LDK", "") + "Z";
1403 clone_fns.add(ty_name + "_clone")
1404 write_c("static inline " + struct_name + " " + ty_name + "_clone(const " + struct_name + " *orig) {\n")
1405 write_c("\t" + struct_name + " ret = { .data = MALLOC(sizeof(" + ty_info.rust_obj + ") * orig->datalen, \"" + struct_name + " clone bytes\"), .datalen = orig->datalen };\n")
1406 write_c("\tfor (size_t i = 0; i < ret.datalen; i++) {\n")
1407 write_c("\t\tret.data[i] = " + ty_info.rust_obj.replace("LDK", "") + "_clone(&orig->data[i]);\n")
1408 write_c("\t}\n\treturn ret;\n}\n")
1410 assert(struct_name.endswith("_Tag"))
1411 struct_name = struct_name[:-4]
1412 union_enum_items[struct_name] = {"field_lines": field_lines}
1413 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
1414 enum_var_name = struct_name.split("_")
1415 union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
1416 elif struct_name in union_enum_items:
1417 map_complex_enum(struct_name, union_enum_items[struct_name])
1418 elif is_unitary_enum:
1419 map_unitary_enum(struct_name, field_lines)
1420 elif len(trait_fn_lines) > 0:
1421 trait_structs.add(struct_name)
1422 map_trait(struct_name, field_var_lines, trait_fn_lines)
1423 elif struct_name == "LDKTxOut":
1424 with open(f"{sys.argv[3]}/structs/TxOut{consts.file_ext}", "w") as out_java_struct:
1425 out_java_struct.write(consts.hu_struct_file_prefix)
1426 out_java_struct.write("public class TxOut extends CommonBase{\n")
1427 out_java_struct.write("\tTxOut(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
1428 out_java_struct.write("\tlong to_c_ptr() { return 0; }\n")
1429 out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1430 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1431 out_java_struct.write("\t\tsuper.finalize();\n")
1432 out_java_struct.write("\t\tif (ptr != 0) { bindings.TxOut_free(ptr); }\n")
1433 out_java_struct.write("\t}\n")
1435 out_java_struct.write("}")
1437 pass # Everything remaining is a byte[] or some form
1438 cur_block_obj = None
1440 fn_ptr = fn_ptr_regex.match(line)
1441 fn_ret_arr = fn_ret_arr_regex.match(line)
1442 reg_fn = reg_fn_regex.match(line)
1443 const_val = const_val_regex.match(line)
1445 if line.startswith("#include <"):
1447 elif line.startswith("/*"):
1448 #out_java.write("\t" + line)
1449 if not line.endswith("*/\n"):
1450 in_block_comment = True
1451 elif line.startswith("typedef enum "):
1452 cur_block_obj = line
1453 elif line.startswith("typedef struct "):
1454 cur_block_obj = line
1455 elif line.startswith("typedef union "):
1456 cur_block_obj = line
1457 elif fn_ptr is not None:
1458 map_fn(line, fn_ptr, None, None)
1459 elif fn_ret_arr is not None:
1460 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1461 elif reg_fn is not None:
1462 map_fn(line, reg_fn, None, None)
1463 elif const_val_regex is not None:
1464 # TODO Map const variables
1467 assert(line == "\n")
1469 out_java.write("}\n")
1470 for struct_name in opaque_structs:
1471 with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1472 out_java_struct.write("}\n")
1473 for struct_name in trait_structs:
1474 with open(f"{sys.argv[3]}/structs/{struct_name.replace('LDK', '')}{consts.file_ext}", "a") as out_java_struct:
1475 out_java_struct.write("}\n")
1476 with open(sys.argv[4], "w") as out_c:
1477 out_c.write(consts.c_file_pfx)
1478 out_c.write(consts.init_str(c_array_class_caches))