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
20 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):
21 self.is_native_primitive = is_native_primitive
22 self.rust_obj = rust_obj
23 self.java_ty = java_ty
24 self.java_hu_ty = java_hu_ty
25 self.java_fn_ty_arg = java_fn_ty_arg
27 self.passed_as_ptr = passed_as_ptr
29 self.var_name = var_name
30 self.arr_len = arr_len
31 self.arr_access = arr_access
33 self.pass_by_ref = is_ptr
36 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):
37 assert(ty_info.c_ty is not None)
38 assert(ty_info.java_ty is not None)
39 assert(arg_name is not None)
40 self.passed_as_ptr = ty_info.passed_as_ptr
41 self.rust_obj = ty_info.rust_obj
42 self.c_ty = ty_info.c_ty
43 self.java_ty = ty_info.java_ty
44 self.java_hu_ty = ty_info.java_hu_ty
45 self.java_fn_ty_arg = ty_info.java_fn_ty_arg
46 self.arg_name = arg_name
47 self.arg_conv = arg_conv
48 self.arg_conv_name = arg_conv_name
49 self.arg_conv_cleanup = arg_conv_cleanup
50 self.ret_conv = ret_conv
51 self.ret_conv_name = ret_conv_name
52 self.to_hu_conv = to_hu_conv
53 self.to_hu_conv_name = to_hu_conv_name
54 self.from_hu_conv = from_hu_conv
57 out_c.write(self.c_ty)
58 out_java.write(self.java_ty)
61 if self.arg_name != "":
62 out_java.write(" " + self.arg_name)
63 out_c.write(" " + self.arg_name)
65 out_java.write(" arg")
68 def camel_to_snake(s):
69 # Convert camel case to snake case, in a way that appears to match cbindgen
75 if lastchar.isupper():
76 if not char.isupper() and not lastund:
81 ret = ret + lastchar.lower()
84 if char.isupper() and not lastund:
92 return (ret + lastchar.lower()).strip("_")
96 opaque_structs = set()
101 def is_common_base_ext(struct_name):
102 return struct_name in complex_enums or struct_name in opaque_structs or struct_name in trait_structs or struct_name in result_types
104 var_is_arr_regex = re.compile("\(\*([A-za-z0-9_]*)\)\[([a-z0-9]*)\]")
105 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
106 java_c_types_none_allowed = True # Unset when we do the real pass that populates the above sets
107 def java_c_types(fn_arg, ret_arr_len):
108 fn_arg = fn_arg.strip()
109 if fn_arg.startswith("MUST_USE_RES "):
112 if fn_arg.startswith("const "):
121 if fn_arg.startswith("LDKThirtyTwoBytes"):
122 fn_arg = "uint8_t (*" + fn_arg[18:] + ")[32]"
123 assert var_is_arr_regex.match(fn_arg[8:])
124 rust_obj = "LDKThirtyTwoBytes"
126 elif fn_arg.startswith("LDKPublicKey"):
127 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[33]"
128 assert var_is_arr_regex.match(fn_arg[8:])
129 rust_obj = "LDKPublicKey"
130 arr_access = "compressed_form"
131 elif fn_arg.startswith("LDKSecretKey"):
132 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[32]"
133 assert var_is_arr_regex.match(fn_arg[8:])
134 rust_obj = "LDKSecretKey"
136 elif fn_arg.startswith("LDKSignature"):
137 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[64]"
138 assert var_is_arr_regex.match(fn_arg[8:])
139 rust_obj = "LDKSignature"
140 arr_access = "compact_form"
141 elif fn_arg.startswith("LDKThreeBytes"):
142 fn_arg = "uint8_t (*" + fn_arg[14:] + ")[3]"
143 assert var_is_arr_regex.match(fn_arg[8:])
144 rust_obj = "LDKThreeBytes"
146 elif fn_arg.startswith("LDKFourBytes"):
147 fn_arg = "uint8_t (*" + fn_arg[13:] + ")[4]"
148 assert var_is_arr_regex.match(fn_arg[8:])
149 rust_obj = "LDKFourBytes"
151 elif fn_arg.startswith("LDKSixteenBytes"):
152 fn_arg = "uint8_t (*" + fn_arg[16:] + ")[16]"
153 assert var_is_arr_regex.match(fn_arg[8:])
154 rust_obj = "LDKSixteenBytes"
156 elif fn_arg.startswith("LDKTenBytes"):
157 fn_arg = "uint8_t (*" + fn_arg[12:] + ")[10]"
158 assert var_is_arr_regex.match(fn_arg[8:])
159 rust_obj = "LDKTenBytes"
161 elif fn_arg.startswith("LDKu8slice"):
162 fn_arg = "uint8_t (*" + fn_arg[11:] + ")[datalen]"
163 assert var_is_arr_regex.match(fn_arg[8:])
164 rust_obj = "LDKu8slice"
166 elif fn_arg.startswith("LDKCVecTempl_u8") or fn_arg.startswith("LDKCVec_u8Z"):
167 if fn_arg.startswith("LDKCVecTempl_u8"):
168 fn_arg = "uint8_t (*" + fn_arg[16:] + ")[datalen]"
169 rust_obj = "LDKCVecTempl_u8"
170 assert var_is_arr_regex.match(fn_arg[8:])
172 fn_arg = "uint8_t (*" + fn_arg[12:] + ")[datalen]"
173 rust_obj = "LDKCVec_u8Z"
174 assert var_is_arr_regex.match(fn_arg[8:])
176 elif fn_arg.startswith("LDKCVecTempl_") or fn_arg.startswith("LDKCVec_"):
179 fn_arg = fn_arg.replace("*", "")
182 if fn_arg.startswith("LDKCVec_"):
183 tyn = fn_arg[8:].split(" ")
184 assert tyn[0].endswith("Z")
188 new_arg = "LDK" + tyn[0][:-1]
190 new_arg = new_arg + " " + a
191 res = java_c_types(new_arg, ret_arr_len)
193 res = java_c_types("LDK" + fn_arg[13:], ret_arr_len)
195 assert java_c_types_none_allowed
198 res.pass_by_ref = True
199 if res.is_native_primitive or res.passed_as_ptr:
200 return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
201 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty=res.c_ty + "Array", passed_as_ptr=False, is_ptr=is_ptr,
202 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
204 return TypeInfo(rust_obj=fn_arg.split(" ")[0], java_ty=res.java_ty + "[]", java_hu_ty=res.java_hu_ty + "[]",
205 java_fn_ty_arg="[" + res.java_fn_ty_arg, c_ty="jobjectArray", passed_as_ptr=False, is_ptr=is_ptr,
206 var_name=res.var_name, arr_len="datalen", arr_access="data", subty=res, is_native_primitive=False)
210 if fn_arg.startswith("void"):
214 fn_arg = fn_arg[4:].strip()
216 elif fn_arg.startswith("bool"):
220 fn_arg = fn_arg[4:].strip()
222 elif fn_arg.startswith("uint8_t"):
226 fn_arg = fn_arg[7:].strip()
228 elif fn_arg.startswith("uint16_t"):
232 fn_arg = fn_arg[8:].strip()
234 elif fn_arg.startswith("uint32_t"):
238 fn_arg = fn_arg[8:].strip()
240 elif fn_arg.startswith("uint64_t") or fn_arg.startswith("uintptr_t"):
244 if fn_arg.startswith("uint64_t"):
245 fn_arg = fn_arg[8:].strip()
247 fn_arg = fn_arg[9:].strip()
249 elif is_const and fn_arg.startswith("char *"):
252 fn_ty_arg = "Ljava/lang/String;"
253 fn_arg = fn_arg[6:].strip()
254 elif fn_arg.startswith("LDKStr"):
257 fn_ty_arg = "Ljava/lang/String;"
258 fn_arg = fn_arg[6:].strip()
262 ma = var_ty_regex.match(fn_arg)
263 if ma.group(1).strip() in unitary_enums:
264 java_ty = ma.group(1).strip()
266 fn_ty_arg = "Lorg/ldk/enums/" + ma.group(1).strip() + ";"
267 fn_arg = ma.group(2).strip()
268 rust_obj = ma.group(1).strip()
270 elif ma.group(1).strip().startswith("LDKC2Tuple"):
272 java_hu_ty = "TwoTuple<"
273 if not ma.group(1).strip() in tuple_types:
274 assert java_c_types_none_allowed
276 for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
278 java_hu_ty = java_hu_ty + ", "
279 if ty_info.is_native_primitive:
280 java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
282 java_hu_ty = java_hu_ty + ty_info.java_hu_ty
283 java_hu_ty = java_hu_ty + ">"
286 fn_arg = ma.group(2).strip()
287 rust_obj = ma.group(1).strip()
289 elif ma.group(1).strip().startswith("LDKC3Tuple"):
291 java_hu_ty = "ThreeTuple<"
292 if not ma.group(1).strip() in tuple_types:
293 assert java_c_types_none_allowed
295 for idx, ty_info in enumerate(tuple_types[ma.group(1).strip()][0]):
297 java_hu_ty = java_hu_ty + ", "
298 if ty_info.is_native_primitive:
299 java_hu_ty = java_hu_ty + ty_info.java_hu_ty.title() # If we're a primitive, capitalize the first letter
301 java_hu_ty = java_hu_ty + ty_info.java_hu_ty
302 java_hu_ty = java_hu_ty + ">"
305 fn_arg = ma.group(2).strip()
306 rust_obj = ma.group(1).strip()
310 java_hu_ty = ma.group(1).strip().replace("LDKCResult", "Result").replace("LDK", "")
313 fn_arg = ma.group(2).strip()
314 rust_obj = ma.group(1).strip()
317 if fn_arg.startswith(" *") or fn_arg.startswith("*"):
318 fn_arg = fn_arg.replace("*", "").strip()
325 var_is_arr = var_is_arr_regex.match(fn_arg)
326 if var_is_arr is not None or ret_arr_len is not None:
327 assert(not take_by_ptr)
329 java_ty = java_ty + "[]"
330 c_ty = c_ty + "Array"
331 if var_is_arr is not None:
332 if var_is_arr.group(1) == "":
333 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,
334 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)
335 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_hu_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
336 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)
338 if java_hu_ty is None:
340 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,
341 is_ptr=is_ptr, var_name=fn_arg, arr_len=arr_len, arr_access=arr_access, is_native_primitive=is_primitive)
343 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
344 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
345 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
348 with open(sys.argv[1]) as in_h:
350 reg_fn = reg_fn_regex.match(line)
351 if reg_fn is not None:
352 if reg_fn.group(2).endswith("_clone"):
353 clone_fns.add(reg_fn.group(2))
355 rty = java_c_types(reg_fn.group(1), None)
356 if rty is not None and rty.rust_obj is not None and reg_fn.group(2) == rty.java_hu_ty + "_new":
357 constructor_fns[rty.rust_obj] = reg_fn.group(3)
359 arr_fn = fn_ret_arr_regex.match(line)
360 if arr_fn is not None:
361 if arr_fn.group(2).endswith("_clone"):
362 clone_fns.add(arr_fn.group(2))
363 # No object constructors return arrays, as then they wouldn't be an object constructor
365 java_c_types_none_allowed = False # C structs created by cbindgen are declared in dependency order
367 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[4], "w") as out_c:
368 def map_type(fn_arg, print_void, ret_arr_len, is_free, holds_ref):
369 ty_info = java_c_types(fn_arg, ret_arr_len)
370 return map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref)
372 def map_type_with_info(ty_info, print_void, ret_arr_len, is_free, holds_ref):
373 if ty_info.c_ty == "void":
375 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
376 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
377 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
378 if ty_info.c_ty.endswith("Array"):
379 arr_len = ty_info.arr_len
380 if arr_len is not None:
381 arr_name = ty_info.var_name
384 arr_len = ret_arr_len
385 if ty_info.c_ty == "jbyteArray":
386 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" + "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", ", "")
387 arg_conv_cleanup = None
388 if not arr_len.isdigit():
389 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
390 arg_conv = arg_conv + arr_name + "_ref." + ty_info.arr_access + " = (*_env)->GetByteArrayElements (_env, " + arr_name + ", NULL);\n"
391 arg_conv = arg_conv + arr_name + "_ref." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");"
392 arg_conv_cleanup = "(*_env)->ReleaseByteArrayElements(_env, " + arr_name + ", (int8_t*)" + arr_name + "_ref." + ty_info.arr_access + ", 0);"
393 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
394 ret_conv = (ret_conv[0], ";\njbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_name + "_var." + arr_len + ");\n")
395 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 + ");")
396 if not holds_ref and ty_info.rust_obj == "LDKCVec_u8Z":
397 ret_conv = (ret_conv[0], ret_conv[1] + "\nCVec_u8Z_free(" + arr_name + "_var);")
398 elif ty_info.rust_obj is not None:
399 arg_conv = ty_info.rust_obj + " " + arr_name + "_ref;\n"
400 arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
401 arg_conv = arg_conv + "(*_env)->GetByteArrayRegion (_env, " + arr_name + ", 0, " + arr_len + ", " + arr_name + "_ref." + ty_info.arr_access + ");"
402 ret_conv = (ret_conv[0], "." + ty_info.arr_access + ");")
404 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n"
405 arg_conv = arg_conv + "CHECK((*_env)->GetArrayLength (_env, " + arr_name + ") == " + arr_len + ");\n"
406 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;"
407 ret_conv = (ret_conv[0] + "*", ");")
408 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
409 arg_conv = arg_conv, arg_conv_name = arr_name + "_ref", arg_conv_cleanup = arg_conv_cleanup,
410 ret_conv = ret_conv, ret_conv_name = arr_name + "_arr", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
412 assert not arr_len.isdigit() # fixed length arrays not implemented
413 assert ty_info.java_ty[len(ty_info.java_ty) - 2:] == "[]"
414 conv_name = "arr_conv_" + str(len(ty_info.java_hu_ty))
415 idxc = chr(ord('a') + (len(ty_info.java_hu_ty) % 26))
416 ty_info.subty.var_name = conv_name
417 subty = map_type_with_info(ty_info.subty, False, None, is_free, holds_ref)
420 arg_conv = ty_info.rust_obj + " " + arr_name + "_constr;\n"
421 arg_conv = arg_conv + arr_name + "_constr." + arr_len + " = (*_env)->GetArrayLength (_env, " + arr_name + ");\n"
422 arg_conv = arg_conv + "if (" + arr_name + "_constr." + arr_len + " > 0)\n"
423 if subty.rust_obj is None:
426 szof = subty.rust_obj
427 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"
428 arg_conv = arg_conv + "else\n"
429 arg_conv = arg_conv + "\t" + arr_name + "_constr." + ty_info.arr_access + " = NULL;\n"
430 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
431 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"
432 arg_conv = arg_conv + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_constr." + arr_len + "; " + idxc + "++) {\n"
433 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
434 arg_conv = arg_conv + "\t" + ty_info.java_ty.strip("[]") + " " + conv_name + " = " + arr_name + "_vals[" + idxc + "];"
435 if subty.arg_conv is not None:
436 arg_conv = arg_conv + "\n\t" + subty.arg_conv.replace("\n", "\n\t")
438 arg_conv = arg_conv + "\tjobject " + conv_name + " = (*_env)->GetObjectArrayElement(_env, " + arr_name + ", " + idxc + ");\n"
439 arg_conv = arg_conv + "\t" + subty.arg_conv.replace("\n", "\n\t")
440 arg_conv = arg_conv + "\n\t" + arr_name + "_constr." + ty_info.arr_access + "[" + idxc + "] = " + subty.arg_conv_name + ";\n}"
441 if not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
442 arg_conv = arg_conv + "\n(*_env)->Release" + ty_info.java_ty.strip("[]").title() + "ArrayElements (_env, " + arr_name + ", " + arr_name + "_vals, 0);"
444 arg_conv_name = "&" + arr_name + "_constr"
446 arg_conv_name = arr_name + "_constr"
447 arg_conv_cleanup = None
449 arg_conv_cleanup = "FREE(" + arr_name + "_constr." + ty_info.arr_access + ");"
451 if arr_name == "arg":
453 ret_conv = (ty_info.rust_obj + " " + arr_name + "_var = ", "")
454 if subty.ret_conv is None:
455 ret_conv = ("DUMMY", "DUMMY")
456 elif not ty_info.java_ty[:len(ty_info.java_ty) - 2].endswith("[]"):
457 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")
458 ret_conv = (ret_conv[0], ret_conv[1] + subty.c_ty + " *" + arr_name + "_arr_ptr = (*_env)->GetPrimitiveArrayCritical(_env, " + arr_name + "_arr, NULL);\n")
459 ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
460 ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
461 ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
462 ret_conv = (ret_conv[0], ret_conv[1] + "\n\t" + arr_name + "_arr_ptr[" + idxc + "] = " + subty.ret_conv_name + ";\n")
463 ret_conv = (ret_conv[0], ret_conv[1] + "}\n(*_env)->ReleasePrimitiveArrayCritical(_env, " + arr_name + "_arr, " + arr_name + "_arr_ptr, 0);")
465 ret_conv = (ret_conv[0], ";\n" + ty_info.c_ty + " " + arr_name + "_arr = (*_env)->NewObjectArray(_env, " + arr_name + "_var." + arr_len + ", NULL, NULL);\n") # XXX: second arg needs to be a clazz!
466 ret_conv = (ret_conv[0], ret_conv[1] + "for (size_t " + idxc + " = 0; " + idxc + " < " + arr_name + "_var." + arr_len + "; " + idxc + "++) {\n")
467 ret_conv = (ret_conv[0], ret_conv[1] + "\t" + subty.ret_conv[0].replace("\n", "\n\t"))
468 ret_conv = (ret_conv[0], ret_conv[1] + arr_name + "_var." + ty_info.arr_access + "[" + idxc + "]" + subty.ret_conv[1].replace("\n", "\n\t"))
469 ret_conv = (ret_conv[0], ret_conv[1] + "\n\t(*_env)->SetObjectArrayElement(_env, " + arr_name + "_arr, " + idxc + ", " + subty.ret_conv_name + ");\n")
470 ret_conv = (ret_conv[0], ret_conv[1] + "}")
472 if subty.rust_obj is not None and subty.rust_obj in opaque_structs:
473 ret_conv = (ret_conv[0], ret_conv[1] + "\nFREE(" + arr_name + "_var." + ty_info.arr_access + ");")
475 ret_conv = (ret_conv[0], ret_conv[1] + "\n" + ty_info.rust_obj.replace("LDK", "") + "_free(" + arr_name + "_var);")
478 to_hu_conv_name = None
479 if subty.to_hu_conv is not None:
480 to_hu_conv = ty_info.java_hu_ty + " " + conv_name + "_arr = new " + ty_info.subty.java_hu_ty.split("<")[0] + "[" + arr_name + ".length];\n"
481 to_hu_conv = to_hu_conv + "for (int " + idxc + " = 0; " + idxc + " < " + arr_name + ".length; " + idxc + "++) {\n"
482 to_hu_conv = to_hu_conv + "\t" + subty.java_ty + " " + conv_name + " = " + arr_name + "[" + idxc + "];\n"
483 to_hu_conv = to_hu_conv + "\t" + subty.to_hu_conv.replace("\n", "\n\t") + "\n"
484 to_hu_conv = to_hu_conv + "\t" + conv_name + "_arr[" + idxc + "] = " + subty.to_hu_conv_name + ";\n}"
485 to_hu_conv_name = conv_name + "_arr"
487 if subty.from_hu_conv is not None:
488 if subty.java_ty == "long" and subty.java_hu_ty != "long":
489 from_hu_conv = ("Arrays.stream(" + arr_name + ").mapToLong(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + " */")
490 elif subty.java_ty == "long":
491 from_hu_conv = ("Arrays.stream(" + arr_name + ").map(" + conv_name + " -> " + subty.from_hu_conv[0] + ").toArray()", "/* TODO 2 " + subty.java_hu_ty + " */")
493 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 + " */")
495 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
496 arg_conv = arg_conv, arg_conv_name = arg_conv_name, arg_conv_cleanup = arg_conv_cleanup,
497 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)
498 elif ty_info.java_ty == "String":
499 if ty_info.arr_access is None:
500 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
501 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
502 ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv",
503 to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
505 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
506 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
507 ret_conv = ("LDKStr " + ty_info.var_name + "_str = ",
508 ";\nchar* " + ty_info.var_name + "_buf = MALLOC(" + ty_info.var_name + "_str." + ty_info.arr_len + " + 1, \"str conv buf\");\n" +
509 "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" +
510 ty_info.var_name + "_buf[" + ty_info.var_name + "_str." + ty_info.arr_len + "] = 0;\n" +
511 "jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, " + ty_info.var_name + "_str." + ty_info.arr_access + ");\n" +
512 "FREE(" + ty_info.var_name + "_buf);"),
513 ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
514 elif ty_info.var_name != "":
515 # If we have a parameter name, print it (noting that it may indicate its a pointer)
516 if ty_info.rust_obj is not None:
517 assert(ty_info.passed_as_ptr)
518 opaque_arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv;\n"
519 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.inner = (void*)(" + ty_info.var_name + " & (~1));\n"
520 opaque_arg_conv = opaque_arg_conv + ty_info.var_name + "_conv.is_owned = (" + ty_info.var_name + " & 1) || (" + ty_info.var_name + " == 0);"
521 if not ty_info.is_ptr and not is_free and not ty_info.pass_by_ref:
522 if (ty_info.java_hu_ty + "_clone") in clone_fns:
523 # 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.
524 opaque_arg_conv = opaque_arg_conv + "\nif (" + ty_info.var_name + "_conv.inner != NULL)\n"
525 opaque_arg_conv = opaque_arg_conv + "\t" + ty_info.var_name + "_conv = " + ty_info.java_hu_ty + "_clone(&" + ty_info.var_name + "_conv);"
526 elif ty_info.passed_as_ptr:
527 opaque_arg_conv = opaque_arg_conv + "\n// Warning: we may need a move here but can't clone!"
528 if not ty_info.is_ptr:
529 if ty_info.rust_obj in unitary_enums:
530 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
531 arg_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_from_java(_env, " + ty_info.var_name + ");",
532 arg_conv_name = ty_info.var_name + "_conv",
533 arg_conv_cleanup = None,
534 ret_conv = ("jclass " + ty_info.var_name + "_conv = " + ty_info.rust_obj + "_to_java(_env, ", ");"),
535 ret_conv_name = ty_info.var_name + "_conv", to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
536 if ty_info.rust_obj in opaque_structs:
537 ret_conv_suf = ";\nCHECK((((long)" + ty_info.var_name + "_var.inner) & 1) == 0); // We rely on a free low bit, malloc guarantees this.\n"
538 ret_conv_suf = ret_conv_suf + "CHECK((((long)&" + ty_info.var_name + "_var) & 1) == 0); // We rely on a free low bit, pointer alignment guarantees this.\n"
540 ret_conv_suf = ret_conv_suf + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner & ~1;"
542 ret_conv_suf = ret_conv_suf + "long " + ty_info.var_name + "_ref;\n"
543 ret_conv_suf = ret_conv_suf + "if (" + ty_info.var_name + "_var.is_owned) {\n"
544 ret_conv_suf = ret_conv_suf + "\t" + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner | 1;\n"
545 ret_conv_suf = ret_conv_suf + "} else {\n"
546 ret_conv_suf = ret_conv_suf + "\t" + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_var.inner & ~1;\n"
547 ret_conv_suf = ret_conv_suf + "}"
548 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
549 arg_conv = opaque_arg_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
550 ret_conv = (ty_info.rust_obj + " " + ty_info.var_name + "_var = ", ret_conv_suf),
551 ret_conv_name = ty_info.var_name + "_ref",
552 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 + ");",
553 to_hu_conv_name = ty_info.var_name + "_hu_conv",
554 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")"))
555 base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";";
556 if ty_info.rust_obj in trait_structs:
558 base_conv = base_conv + "\nif (" + ty_info.var_name + "_conv.free == " + ty_info.rust_obj + "_JCalls_free) {\n"
559 base_conv = base_conv + "\t// If this_arg is a JCalls struct, then we need to increment the refcnt in it.\n"
560 base_conv = base_conv + "\t" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv.this_arg);\n}"
562 base_conv = base_conv + "\n" + "FREE((void*)" + ty_info.var_name + ");"
563 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
564 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
565 ret_conv = ("CANT PASS TRAIT TO Java?", ""), ret_conv_name = "NO CONV POSSIBLE",
566 to_hu_conv = "DUMMY", to_hu_conv_name = None,
567 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")"))
568 if ty_info.rust_obj != "LDKu8slice" and ty_info.rust_obj != "LDKTransaction":
569 # Don't bother free'ing slices passed in - Rust doesn't auto-free the
570 # underlying unlike Vecs, and it gives Java more freedom.
571 base_conv = base_conv + "\nFREE((void*)" + ty_info.var_name + ");";
572 if ty_info.rust_obj in complex_enums:
573 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";")
574 if not ty_info.is_ptr and not holds_ref and (ty_info.java_hu_ty + "_clone") in clone_fns:
575 ret_conv = (ty_info.rust_obj + " *" + ty_info.var_name + "_copy = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n", "")
576 ret_conv = (ret_conv[0] + "*" + ty_info.var_name + "_copy = " + ty_info.java_hu_ty + "_clone(&", ");\n")
577 ret_conv = (ret_conv[0], ret_conv[1] + "long " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_copy;")
578 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
579 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
580 ret_conv = ret_conv, ret_conv_name = ty_info.var_name + "_ref",
581 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 + ");",
582 to_hu_conv_name = ty_info.var_name + "_hu_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
583 if ty_info.rust_obj in tuple_types:
584 from_hu_conv = "bindings." + tuple_types[ty_info.rust_obj][1].replace("LDK", "") + "_new("
586 to_hu_conv_sfx = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " + ty_info.java_hu_ty + "("
587 for idx, conv in enumerate(tuple_types[ty_info.rust_obj][0]):
589 to_hu_conv_sfx = to_hu_conv_sfx + ", "
590 from_hu_conv = from_hu_conv + ", "
591 conv.var_name = ty_info.var_name + "_" + chr(idx + ord("a"))
592 conv_map = map_type_with_info(conv, False, None, is_free, holds_ref)
593 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"
594 if conv_map.to_hu_conv is not None:
595 to_hu_conv_pfx = to_hu_conv_pfx + conv_map.to_hu_conv + ";\n"
596 to_hu_conv_sfx = to_hu_conv_sfx + conv_map.to_hu_conv_name
598 to_hu_conv_sfx = to_hu_conv_sfx + ty_info.var_name + "_" + chr(idx + ord("a"))
599 if conv_map.from_hu_conv is not None:
600 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")))
601 if conv_map.from_hu_conv[1] != "":
602 from_hu_conv = from_hu_conv + "/*XXX: Need to call " + conv_map.from_hu_conv[1] + "*/"
604 from_hu_conv = from_hu_conv + ty_info.var_name + "." + chr(idx + ord("a"))
605 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
606 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
607 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
608 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 + ")", ""))
610 # The manually-defined types - TxOut and Transaction
611 assert ty_info.rust_obj == "LDKTransaction" or ty_info.rust_obj == "LDKTxOut"
612 if ty_info.rust_obj == "LDKTransaction":
613 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
614 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
615 ret_conv = ("LDKTransaction *" + ty_info.var_name + "_copy = MALLOC(sizeof(LDKTransaction), \"LDKTransaction\");\n*" + ty_info.var_name + "_copy = ", ";\nlong " + ty_info.var_name + "_ref = (long)" + ty_info.var_name + "_copy;"),
616 ret_conv_name = ty_info.var_name + "_ref",
617 to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " +ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
618 to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
619 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
620 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
621 ret_conv = ("long " + ty_info.var_name + "_ref = (long)&", ";"), ret_conv_name = ty_info.var_name + "_ref",
622 to_hu_conv = ty_info.java_hu_ty + " " + ty_info.var_name + "_conv = new " +ty_info.java_hu_ty + "(null, " + ty_info.var_name + ");",
623 to_hu_conv_name = ty_info.var_name + "_conv", from_hu_conv = (ty_info.var_name + ".ptr", ""))
626 if ty_info.rust_obj in opaque_structs:
627 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
628 arg_conv = opaque_arg_conv, arg_conv_name = "&" + ty_info.var_name + "_conv", arg_conv_cleanup = None,
629 ret_conv = None, ret_conv_name = None,
630 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 + ");",
631 to_hu_conv_name = ty_info.var_name + "_hu_conv",
632 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")")) # its a pointer, no conv needed
633 elif ty_info.rust_obj in complex_enums:
634 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
635 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
636 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
637 ret_conv = None, ret_conv_name = None,
638 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 + ");",
639 to_hu_conv_name = ty_info.var_name + "_hu_conv",
640 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr & ~1", "this.ptrs_to.add(" + ty_info.var_name + ")")) # its a pointer, no conv needed
641 elif ty_info.rust_obj in trait_structs:
642 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
643 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
644 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
645 ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 2.5", to_hu_conv_name = None,
646 from_hu_conv = (ty_info.var_name + " == null ? 0 : " + ty_info.var_name + ".ptr", "this.ptrs_to.add(" + ty_info.var_name + ")")) # its a pointer, no conv needed
647 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
648 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
649 arg_conv_name = ty_info.var_name + "_conv", arg_conv_cleanup = None,
650 ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 3", to_hu_conv_name = None, from_hu_conv = None) # its a pointer, no conv needed
652 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
653 arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None,
654 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
656 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
657 arg_conv = None, arg_conv_name = ty_info.var_name, arg_conv_cleanup = None,
658 ret_conv = None, ret_conv_name = None, to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
660 # We don't have a parameter name, and want one, just call it arg
661 if ty_info.rust_obj is not None:
662 assert(not is_free or ty_info.rust_obj not in opaque_structs)
663 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
664 arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nFREE((void*)arg);",
665 arg_conv_name = "arg_conv", arg_conv_cleanup = None,
666 ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 7", to_hu_conv_name = None, from_hu_conv = None)
669 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
670 arg_conv = None, arg_conv_name = "arg", arg_conv_cleanup = None,
671 ret_conv = None, ret_conv_name = None, to_hu_conv = "TODO 8", to_hu_conv_name = None, from_hu_conv = None)
673 # We don't have a parameter name, and don't want one (cause we're returning)
674 if ty_info.rust_obj is not None:
675 if not ty_info.is_ptr:
676 if ty_info.rust_obj in unitary_enums:
677 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
678 arg_conv = ty_info.rust_obj + " ret_conv = " + ty_info.rust_obj + "_from_java(_env, ret);",
679 arg_conv_name = "ret_conv", arg_conv_cleanup = None,
680 ret_conv = ("jclass ret = " + ty_info.rust_obj + "_to_java(_env, ", ");"), ret_conv_name = "ret",
681 to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
682 if ty_info.rust_obj in complex_enums or ty_info.rust_obj in result_types:
683 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
684 ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
685 ret_conv_name = "(long)ret",
686 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
687 to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = " + ty_info.java_hu_ty + ".constr_from_ptr(ret);\nret_hu_conv.ptrs_to.add(this);",
688 to_hu_conv_name = "ret_hu_conv", from_hu_conv = ("ret != null ? ret.ptr : 0", ""))
689 if ty_info.rust_obj in opaque_structs:
690 # If we're returning a newly-allocated struct, we don't want Rust to ever
691 # free, instead relying on the Java GC to lose the ref. We undo this in
692 # any _free function.
693 # To avoid any issues, we first assert that the incoming object is non-ref.
694 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
695 ret_conv = (ty_info.rust_obj + " ret = ", ";"),
696 ret_conv_name = "((long)ret.inner) | (ret.is_owned ? 1 : 0)",
697 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
698 to_hu_conv = ty_info.java_hu_ty + " ret_hu_conv = new " + ty_info.java_hu_ty + "(null, ret);",
699 to_hu_conv_name = "ret_hu_conv", from_hu_conv = None)
700 elif ty_info.rust_obj in trait_structs:
701 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
702 ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
703 ret_conv_name = "(long)ret",
704 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
705 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);",
706 to_hu_conv_name = "ret_hu_conv", from_hu_conv = ("ret.ptr", ""))
707 elif ty_info.rust_obj in tuple_types:
708 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
709 ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
710 ret_conv_name = "(long)ret",
711 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
712 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);",
713 to_hu_conv_name = "ret_hu_conv", from_hu_conv = ("bindings." + ty_info.rust_obj.replace("LDK", "") + "_new(ret.a, ret.b)", ""))
715 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
716 ret_conv = (ty_info.rust_obj + "* ret = MALLOC(sizeof(" + ty_info.rust_obj + "), \"" + ty_info.rust_obj + "\");\n*ret = ", ";"),
717 ret_conv_name = "(long)ret",
718 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
719 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);",
720 to_hu_conv_name = "ret_hu_conv", from_hu_conv = None)
721 elif ty_info.rust_obj in trait_structs:
722 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
723 ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
724 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
725 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);",
726 to_hu_conv_name = "ret_hu_conv", from_hu_conv = None)
728 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
729 ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
730 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
731 to_hu_conv = "TODO c", to_hu_conv_name = None, from_hu_conv = None)
733 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
734 arg_conv = None, arg_conv_name = None, arg_conv_cleanup = None,
735 ret_conv = None, ret_conv_name = None,
736 to_hu_conv = None, to_hu_conv_name = None, from_hu_conv = None)
738 def map_fn(line, re_match, ret_arr_len, c_call_string):
739 out_java.write("\t// " + line)
740 out_java.write("\tpublic static native ")
741 out_c.write("JNIEXPORT ")
743 is_free = re_match.group(2).endswith("_free")
744 struct_meth = re_match.group(2).split("_")[0]
746 ret_info = map_type(re_match.group(1), True, ret_arr_len, False, False)
749 if ret_info.ret_conv is not None:
750 ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
752 out_java.write(" " + re_match.group(2) + "(")
753 out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
756 default_constructor_args = {}
758 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
759 for idx, arg in enumerate(re_match.group(3).split(',')):
764 arg_conv_info = map_type(arg, False, None, is_free, False)
765 if arg_conv_info.c_ty != "void":
766 arg_conv_info.print_ty()
767 arg_conv_info.print_name()
768 if arg_conv_info.arg_name == "this_ptr" or arg_conv_info.arg_name == "this_arg":
770 if arg_conv_info.arg_conv is not None and "Warning" in arg_conv_info.arg_conv:
771 if arg_conv_info.rust_obj in constructor_fns:
773 for explode_arg in constructor_fns[arg_conv_info.rust_obj].split(','):
774 explode_arg_conv = map_type(explode_arg, False, None, False, False)
775 if explode_arg_conv.c_ty == "void":
776 # We actually want to handle this case, but for now its only used in NetGraphMsgHandler::new()
777 # which ends up resulting in a redundant constructor - both without arguments for the NetworkGraph.
779 assert explode_arg_conv.arg_name != "this_ptr"
780 assert explode_arg_conv.arg_name != "this_arg"
781 if explode_arg_conv.passed_as_ptr and not explode_arg_conv.rust_obj in trait_structs:
783 if not arg_conv_info.arg_name in default_constructor_args:
784 default_constructor_args[arg_conv_info.arg_name] = []
785 default_constructor_args[arg_conv_info.arg_name].append(explode_arg_conv)
788 arg_names.append(arg_conv_info)
790 out_java_struct = None
791 if ("LDK" + struct_meth in opaque_structs or "LDK" + struct_meth in trait_structs) and not is_free:
792 out_java_struct = open(sys.argv[3] + "/structs/" + struct_meth + ".java", "a")
794 out_java_struct.write("\t// Skipped " + re_match.group(2) + "\n")
795 out_java_struct.close()
796 out_java_struct = None
798 meth_n = re_match.group(2)[len(struct_meth) + 1:]
799 if ret_info.rust_obj == "LDK" + struct_meth:
800 out_java_struct.write("\tpublic static " + ret_info.java_hu_ty + " constructor_" + meth_n + "(")
802 out_java_struct.write("\tpublic " + ret_info.java_hu_ty + " " + meth_n + "(")
803 for idx, arg in enumerate(arg_names):
805 if not takes_self or idx > 1:
806 out_java_struct.write(", ")
807 if arg.java_ty != "void" and arg.arg_name != "this_ptr" and arg.arg_name != "this_arg":
808 if arg.arg_name in default_constructor_args:
809 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
811 out_java_struct.write(", ")
812 assert explode_arg.rust_obj in opaque_structs or explode_arg.rust_obj in trait_structs
813 out_java_struct.write(explode_arg.java_hu_ty + " " + arg.arg_name + "_" + explode_arg.arg_name)
815 out_java_struct.write(arg.java_hu_ty + " " + arg.arg_name)
818 out_java.write(");\n")
820 if out_java_struct is not None:
821 out_java_struct.write(") {\n")
823 for info in arg_names:
824 if info.arg_conv is not None:
825 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
827 if ret_info.ret_conv is not None:
828 out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'))
829 elif ret_info.c_ty != "void":
830 out_c.write("\t" + ret_info.c_ty + " ret_val = ")
834 if c_call_string is None:
835 out_c.write(re_match.group(2) + "(")
837 out_c.write(c_call_string)
838 for idx, info in enumerate(arg_names):
839 if info.arg_conv_name is not None:
842 elif c_call_string is not None:
844 out_c.write(info.arg_conv_name)
846 if ret_info.ret_conv is not None:
847 out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
850 for info in arg_names:
851 if info.arg_conv_cleanup is not None:
852 out_c.write("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
853 if ret_info.ret_conv is not None:
854 out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
855 elif ret_info.c_ty != "void":
856 out_c.write("\n\treturn ret_val;")
857 out_c.write("\n}\n\n")
858 if out_java_struct is not None:
859 out_java_struct.write("\t\t")
860 if ret_info.java_ty != "void":
861 out_java_struct.write(ret_info.java_ty + " ret = ")
862 out_java_struct.write("bindings." + re_match.group(2) + "(")
863 for idx, info in enumerate(arg_names):
865 out_java_struct.write(", ")
866 if info.arg_name == "this_ptr" or info.arg_name == "this_arg":
867 out_java_struct.write("this.ptr")
868 elif info.arg_name in default_constructor_args:
869 out_java_struct.write("bindings." + info.java_hu_ty + "_new(")
870 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
872 out_java_struct.write(", ")
873 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
874 out_java_struct.write(explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
875 out_java_struct.write(")")
876 elif info.from_hu_conv is not None:
877 out_java_struct.write(info.from_hu_conv[0])
879 out_java_struct.write(info.arg_name)
880 out_java_struct.write(");\n")
881 if ret_info.to_hu_conv is not None:
882 out_java_struct.write("\t\t" + ret_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
884 for info in arg_names:
885 if info.arg_name == "this_ptr" or info.arg_name == "this_arg":
887 elif info.arg_name in default_constructor_args:
888 for explode_arg in default_constructor_args[info.arg_name]:
889 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
890 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")
891 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
892 if ret_info.rust_obj == "LDK" + struct_meth and ret_info.to_hu_conv_name is not None:
893 out_java_struct.write("\t\t" + info.from_hu_conv[1].replace("this", ret_info.to_hu_conv_name) + ";\n")
895 out_java_struct.write("\t\t" + info.from_hu_conv[1] + ";\n")
897 if ret_info.to_hu_conv_name is not None:
898 out_java_struct.write("\t\treturn " + ret_info.to_hu_conv_name + ";\n")
899 elif ret_info.java_ty != "void" and ret_info.rust_obj != "LDK" + struct_meth:
900 out_java_struct.write("\t\treturn ret;\n")
901 out_java_struct.write("\t}\n\n")
902 out_java_struct.close()
904 def map_unitary_enum(struct_name, field_lines):
905 with open(sys.argv[3] + "/enums/" + struct_name + ".java", "w") as out_java_enum:
906 out_java_enum.write("package org.ldk.enums;\n\n")
907 unitary_enums.add(struct_name)
908 out_c.write("static inline " + struct_name + " " + struct_name + "_from_java(JNIEnv *env, jclass val) {\n")
909 out_c.write("\tswitch ((*env)->CallIntMethod(env, val, ordinal_meth)) {\n")
911 for idx, struct_line in enumerate(field_lines):
913 out_java_enum.write("public enum " + struct_name + " {\n")
914 elif idx == len(field_lines) - 3:
915 assert(struct_line.endswith("_Sentinel,"))
916 elif idx == len(field_lines) - 2:
917 out_java_enum.write("\t; static native void init();\n")
918 out_java_enum.write("\tstatic { init(); }\n")
919 out_java_enum.write("}")
920 out_java.write("\tstatic { " + struct_name + ".values(); /* Force enum statics to run */ }\n")
921 elif idx == len(field_lines) - 1:
922 assert(struct_line == "")
924 out_java_enum.write(struct_line + "\n")
925 out_c.write("\t\tcase %d: return %s;\n" % (ord_v, struct_line.strip().strip(",")))
928 out_c.write("\tabort();\n")
932 out_c.write("static jclass " + struct_name + "_class = NULL;\n")
933 for idx, struct_line in enumerate(field_lines):
934 if idx > 0 and idx < len(field_lines) - 3:
935 variant = struct_line.strip().strip(",")
936 out_c.write("static jfieldID " + struct_name + "_" + variant + " = NULL;\n")
937 out_c.write("JNIEXPORT void JNICALL Java_org_ldk_enums_" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass clz) {\n")
938 out_c.write("\t" + struct_name + "_class = (*env)->NewGlobalRef(env, clz);\n")
939 out_c.write("\tCHECK(" + struct_name + "_class != NULL);\n")
940 for idx, struct_line in enumerate(field_lines):
941 if idx > 0 and idx < len(field_lines) - 3:
942 variant = struct_line.strip().strip(",")
943 out_c.write("\t" + struct_name + "_" + variant + " = (*env)->GetStaticFieldID(env, " + struct_name + "_class, \"" + variant + "\", \"Lorg/ldk/enums/" + struct_name + ";\");\n")
944 out_c.write("\tCHECK(" + struct_name + "_" + variant + " != NULL);\n")
946 out_c.write("static inline jclass " + struct_name + "_to_java(JNIEnv *env, " + struct_name + " val) {\n")
947 out_c.write("\tswitch (val) {\n")
948 for idx, struct_line in enumerate(field_lines):
949 if idx > 0 and idx < len(field_lines) - 3:
950 variant = struct_line.strip().strip(",")
951 out_c.write("\t\tcase " + variant + ":\n")
952 out_c.write("\t\t\treturn (*env)->GetStaticObjectField(env, " + struct_name + "_class, " + struct_name + "_" + variant + ");\n")
954 out_c.write("\t\tdefault: abort();\n")
958 def map_complex_enum(struct_name, union_enum_items):
959 java_hu_type = struct_name.replace("LDK", "")
960 complex_enums.add(struct_name)
961 with open(sys.argv[3] + "/structs/" + java_hu_type + ".java", "w") as out_java_enum:
962 out_java_enum.write(hu_struct_file_prefix)
963 out_java_enum.write("public class " + java_hu_type + " extends CommonBase {\n")
964 out_java_enum.write("\tprivate " + java_hu_type + "(Object _dummy, long ptr) { super(ptr); }\n")
965 out_java_enum.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
966 out_java_enum.write("\tprotected void finalize() throws Throwable {\n")
967 out_java_enum.write("\t\tsuper.finalize();\n")
968 out_java_enum.write("\t\tif (ptr != 0) { bindings." + java_hu_type + "_free(ptr); }\n")
969 out_java_enum.write("\t}\n")
970 out_java_enum.write("\tstatic " + java_hu_type + " constr_from_ptr(long ptr) {\n")
971 out_java_enum.write("\t\tbindings." + struct_name + " raw_val = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
972 java_hu_subclasses = ""
974 tag_field_lines = union_enum_items["field_lines"]
975 init_meth_jty_strs = {}
976 for idx, struct_line in enumerate(tag_field_lines):
978 out_java.write("\tpublic static class " + struct_name + " {\n")
979 out_java.write("\t\tprivate " + struct_name + "() {}\n")
980 elif idx == len(tag_field_lines) - 3:
981 assert(struct_line.endswith("_Sentinel,"))
982 elif idx == len(tag_field_lines) - 2:
983 out_java.write("\t\tstatic native void init();\n")
984 out_java.write("\t}\n")
985 elif idx == len(tag_field_lines) - 1:
986 assert(struct_line == "")
988 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
989 out_java.write("\t\tpublic final static class " + var_name + " extends " + struct_name + " {\n")
990 java_hu_subclasses = java_hu_subclasses + "\tpublic final static class " + var_name + " extends " + java_hu_type + " {\n"
991 out_java_enum.write("\t\tif (raw_val.getClass() == bindings." + struct_name + "." + var_name + ".class) {\n")
992 out_java_enum.write("\t\t\treturn new " + var_name + "(ptr, (bindings." + struct_name + "." + var_name + ")raw_val);\n")
993 out_c.write("static jclass " + struct_name + "_" + var_name + "_class = NULL;\n")
994 out_c.write("static jmethodID " + struct_name + "_" + var_name + "_meth = NULL;\n")
995 init_meth_jty_str = ""
996 init_meth_params = ""
999 if "LDK" + var_name in union_enum_items:
1000 enum_var_lines = union_enum_items["LDK" + var_name]
1001 for idx, field in enumerate(enum_var_lines):
1002 if idx != 0 and idx < len(enum_var_lines) - 2:
1003 field_ty = map_type(field.strip(' ;'), False, None, False, True)
1004 out_java.write("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
1005 java_hu_subclasses = java_hu_subclasses + "\t\tpublic final " + field_ty.java_hu_ty + " " + field_ty.arg_name + ";\n"
1006 if field_ty.to_hu_conv is not None:
1007 hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.java_ty + " " + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1008 hu_conv_body = hu_conv_body + "\t\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1009 hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1011 hu_conv_body = hu_conv_body + "\t\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
1012 init_meth_jty_str = init_meth_jty_str + field_ty.java_fn_ty_arg
1014 init_meth_params = init_meth_params + ", "
1015 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
1016 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
1017 out_java.write("\t\t\t" + var_name + "(" + init_meth_params + ") { ")
1018 out_java.write(init_meth_body)
1019 out_java.write("}\n")
1020 out_java.write("\t\t}\n")
1021 out_java_enum.write("\t\t}\n")
1022 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"
1023 java_hu_subclasses = java_hu_subclasses + hu_conv_body
1024 java_hu_subclasses = java_hu_subclasses + "\t\t}\n\t}\n"
1025 init_meth_jty_strs[var_name] = init_meth_jty_str
1026 out_java_enum.write("\t\tassert false; return null; // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
1027 out_java_enum.write(java_hu_subclasses)
1028 out_java.write("\tstatic { " + struct_name + ".init(); }\n")
1029 out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
1031 out_c.write("JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_00024" + struct_name.replace("_", "_1") + "_init (JNIEnv * env, jclass _a) {\n")
1032 for idx, struct_line in enumerate(tag_field_lines):
1033 if idx != 0 and idx < len(tag_field_lines) - 3:
1034 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1035 out_c.write("\t" + struct_name + "_" + var_name + "_class =\n")
1036 out_c.write("\t\t(*env)->NewGlobalRef(env, (*env)->FindClass(env, \"Lorg/ldk/impl/bindings$" + struct_name + "$" + var_name + ";\"));\n")
1037 out_c.write("\tCHECK(" + struct_name + "_" + var_name + "_class != NULL);\n")
1038 out_c.write("\t" + struct_name + "_" + var_name + "_meth = (*env)->GetMethodID(env, " + struct_name + "_" + var_name + "_class, \"<init>\", \"(" + init_meth_jty_strs[var_name] + ")V\");\n")
1039 out_c.write("\tCHECK(" + struct_name + "_" + var_name + "_meth != NULL);\n")
1041 out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (JNIEnv * _env, jclass _c, jlong ptr) {\n")
1042 out_c.write("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
1043 out_c.write("\tswitch(obj->tag) {\n")
1044 for idx, struct_line in enumerate(tag_field_lines):
1045 if idx != 0 and idx < len(tag_field_lines) - 3:
1046 var_name = struct_line.strip(' ,')[len(struct_name) + 1:]
1047 out_c.write("\t\tcase " + struct_name + "_" + var_name + ": {\n")
1049 if "LDK" + var_name in union_enum_items:
1050 enum_var_lines = union_enum_items["LDK" + var_name]
1051 for idx, field in enumerate(enum_var_lines):
1052 if idx != 0 and idx < len(enum_var_lines) - 2:
1053 field_map = map_type(field.strip(' ;'), False, None, False, True)
1054 if field_map.ret_conv is not None:
1055 out_c.write("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1056 out_c.write("obj->" + camel_to_snake(var_name) + "." + field_map.arg_name)
1057 out_c.write(field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1058 c_params_text = c_params_text + ", " + field_map.ret_conv_name
1060 c_params_text = c_params_text + ", obj->" + camel_to_snake(var_name) + "." + field_map.arg_name
1061 out_c.write("\t\t\treturn (*_env)->NewObject(_env, " + struct_name + "_" + var_name + "_class, " + struct_name + "_" + var_name + "_meth" + c_params_text + ");\n")
1062 out_c.write("\t\t}\n")
1063 out_c.write("\t\tdefault: abort();\n")
1064 out_c.write("\t}\n}\n")
1065 out_java_enum.write("}\n")
1067 def map_trait(struct_name, field_var_lines, trait_fn_lines):
1068 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_trait:
1069 out_c.write("typedef struct " + struct_name + "_JCalls {\n")
1070 out_c.write("\tatomic_size_t refcnt;\n")
1071 out_c.write("\tJavaVM *vm;\n")
1072 out_c.write("\tjweak o;\n")
1073 field_var_convs = []
1074 for var_line in field_var_lines:
1075 if var_line.group(1) in trait_structs:
1076 out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
1077 field_var_convs.append(None)
1079 field_var_convs.append(map_type(var_line.group(1) + " " + var_line.group(2), False, None, False, False))
1080 for fn_line in trait_fn_lines:
1081 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1082 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
1083 out_c.write("} " + struct_name + "_JCalls;\n")
1085 out_java_trait.write(hu_struct_file_prefix)
1086 out_java_trait.write("public class " + struct_name.replace("LDK","") + " extends CommonBase {\n")
1087 out_java_trait.write("\tfinal bindings." + struct_name + " bindings_instance;\n")
1088 out_java_trait.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); bindings_instance = null; }\n")
1089 out_java_trait.write("\tprivate " + struct_name.replace("LDK", "") + "(bindings." + struct_name + " arg")
1090 for idx, var_line in enumerate(field_var_lines):
1091 if var_line.group(1) in trait_structs:
1092 out_java_trait.write(", bindings." + var_line.group(1) + " " + var_line.group(2))
1094 out_java_trait.write(", " + field_var_convs[idx].java_hu_ty + " " + var_line.group(2))
1095 out_java_trait.write(") {\n")
1096 out_java_trait.write("\t\tsuper(bindings." + struct_name + "_new(arg")
1097 for idx, var_line in enumerate(field_var_lines):
1098 if var_line.group(1) in trait_structs:
1099 out_java_trait.write(", " + var_line.group(2))
1100 elif field_var_convs[idx].from_hu_conv is not None:
1101 out_java_trait.write(", " + field_var_convs[idx].from_hu_conv[0])
1103 out_java_trait.write(", " + var_line.group(2))
1104 out_java_trait.write("));\n")
1105 out_java_trait.write("\t\tthis.ptrs_to.add(arg);\n")
1106 for idx, var_line in enumerate(field_var_lines):
1107 if var_line.group(1) in trait_structs:
1108 out_java_trait.write("\t\tthis.ptrs_to.add(" + var_line.group(2) + ");\n")
1109 elif field_var_convs[idx].from_hu_conv is not None and field_var_convs[idx].from_hu_conv[1] != "":
1110 out_java_trait.write("\t\t" + field_var_convs[idx].from_hu_conv[1] + ";\n")
1111 out_java_trait.write("\t\tthis.bindings_instance = arg;\n")
1112 out_java_trait.write("\t}\n")
1113 out_java_trait.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1114 out_java_trait.write("\tprotected void finalize() throws Throwable {\n")
1115 out_java_trait.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); } super.finalize();\n")
1116 out_java_trait.write("\t}\n\n")
1118 java_trait_constr = "\tpublic " + struct_name.replace("LDK", "") + "(" + struct_name.replace("LDK", "") + "Interface arg"
1119 for idx, var_line in enumerate(field_var_lines):
1120 if var_line.group(1) in trait_structs:
1121 # Ideally we'd be able to take any instance of the interface, but our C code can only represent
1122 # Java-implemented version, so we require users pass a Java implementation here :/
1123 java_trait_constr = java_trait_constr + ", " + var_line.group(1).replace("LDK", "") + "." + var_line.group(1).replace("LDK", "") + "Interface " + var_line.group(2)
1125 java_trait_constr = java_trait_constr + ", " + field_var_convs[idx].java_hu_ty + " " + var_line.group(2)
1126 java_trait_constr = java_trait_constr + ") {\n\t\tthis(new bindings." + struct_name + "() {\n"
1127 out_java_trait.write("\tpublic static interface " + struct_name.replace("LDK", "") + "Interface {\n")
1128 out_java.write("\tpublic interface " + struct_name + " {\n")
1130 for fn_line in trait_fn_lines:
1131 java_meth_descr = "("
1132 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1133 ret_ty_info = map_type(fn_line.group(1), True, None, False, False)
1135 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
1136 java_trait_constr = java_trait_constr + "\t\t\t@Override public " + ret_ty_info.java_ty + " " + fn_line.group(2) + "("
1137 out_java_trait.write("\t\t" + ret_ty_info.java_hu_ty + " " + fn_line.group(2) + "(")
1138 is_const = fn_line.group(3) is not None
1139 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
1141 out_c.write("const void* this_arg")
1143 out_c.write("void* this_arg")
1146 for idx, arg in enumerate(fn_line.group(4).split(',')):
1150 out_java.write(", ")
1151 java_trait_constr = java_trait_constr + ", "
1152 out_java_trait.write(", ")
1154 arg_conv_info = map_type(arg, True, None, False, False)
1155 out_c.write(arg.strip())
1156 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
1157 out_java_trait.write(arg_conv_info.java_hu_ty + " " + arg_conv_info.arg_name)
1158 java_trait_constr = java_trait_constr + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
1159 arg_names.append(arg_conv_info)
1160 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
1161 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
1162 java_meths.append(java_meth_descr)
1164 out_java.write(");\n")
1165 out_java_trait.write(");\n")
1166 java_trait_constr = java_trait_constr + ") {\n"
1167 out_c.write(") {\n")
1168 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1169 out_c.write("\tJNIEnv *_env;\n")
1170 out_c.write("\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&_env, JNI_VERSION_1_8) == JNI_OK);\n")
1172 for arg_info in arg_names:
1173 if arg_info.ret_conv is not None:
1174 out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t'));
1175 out_c.write(arg_info.arg_name)
1176 out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t') + "\n")
1177 if arg_info.to_hu_conv is not None:
1178 java_trait_constr = java_trait_constr + "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
1180 out_c.write("\tjobject obj = (*_env)->NewLocalRef(_env, j_calls->o);\n\tCHECK(obj != NULL);\n")
1181 if ret_ty_info.c_ty.endswith("Array"):
1182 out_c.write("\t" + ret_ty_info.c_ty + " ret = (*_env)->CallObjectMethod(_env, obj, j_calls->" + fn_line.group(2) + "_meth")
1183 elif not ret_ty_info.passed_as_ptr:
1184 out_c.write("\treturn (*_env)->Call" + ret_ty_info.java_ty.title() + "Method(_env, obj, j_calls->" + fn_line.group(2) + "_meth")
1186 out_c.write("\t" + fn_line.group(1).strip() + "* ret = (" + fn_line.group(1).strip() + "*)(*_env)->CallLongMethod(_env, obj, j_calls->" + fn_line.group(2) + "_meth");
1187 if ret_ty_info.java_ty != "void":
1188 java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.java_hu_ty + " ret = arg." + fn_line.group(2) + "("
1190 java_trait_constr = java_trait_constr + "\t\t\t\targ." + fn_line.group(2) + "("
1192 for idx, arg_info in enumerate(arg_names):
1193 if arg_info.ret_conv is not None:
1194 out_c.write(", " + arg_info.ret_conv_name)
1196 out_c.write(", " + arg_info.arg_name)
1198 java_trait_constr = java_trait_constr + ", "
1199 if arg_info.to_hu_conv_name is not None:
1200 java_trait_constr = java_trait_constr + arg_info.to_hu_conv_name
1202 java_trait_constr = java_trait_constr + arg_info.arg_name
1203 out_c.write(");\n");
1204 if ret_ty_info.arg_conv is not None:
1205 out_c.write("\t" + ret_ty_info.arg_conv.replace("\n", "\n\t").replace("arg", "ret") + "\n\treturn " + ret_ty_info.arg_conv_name.replace("arg", "ret") + ";\n")
1207 if ret_ty_info.passed_as_ptr:
1208 out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
1209 out_c.write("\tFREE(ret);\n")
1210 out_c.write("\treturn res;\n")
1212 java_trait_constr = java_trait_constr + ");\n"
1213 if ret_ty_info.java_ty != "void":
1214 if ret_ty_info.from_hu_conv is not None:
1215 java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.java_ty + " result = " + ret_ty_info.from_hu_conv[0] + ";\n"
1216 if ret_ty_info.from_hu_conv[1] != "":
1217 java_trait_constr = java_trait_constr + "\t\t\t\t" + ret_ty_info.from_hu_conv[1] + "\n"
1218 if is_common_base_ext(ret_ty_info.rust_obj):
1219 java_trait_constr = java_trait_constr + "\t\t\t\tret.ptr = 0;\n"
1220 java_trait_constr = java_trait_constr + "\t\t\t\treturn result;\n"
1222 java_trait_constr = java_trait_constr + "\t\t\t\treturn ret;\n"
1223 java_trait_constr = java_trait_constr + "\t\t\t}\n"
1224 elif fn_line.group(2) == "free":
1225 out_c.write("static void " + struct_name + "_JCalls_free(void* this_arg) {\n")
1226 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1227 out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
1228 out_c.write("\t\tJNIEnv *env;\n")
1229 out_c.write("\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n")
1230 out_c.write("\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n")
1231 out_c.write("\t\tFREE(j_calls);\n")
1232 out_c.write("\t}\n}\n")
1233 java_trait_constr = java_trait_constr + "\t\t}"
1234 for var_line in field_var_lines:
1235 if var_line.group(1) in trait_structs:
1236 java_trait_constr = java_trait_constr + ", new " + var_line.group(2) + "(" + var_line.group(2) + ").bindings_instance"
1238 java_trait_constr = java_trait_constr + ", " + var_line.group(2)
1239 out_java_trait.write("\t}\n")
1240 out_java_trait.write(java_trait_constr + ");\n\t}\n")
1242 # Write out a clone function whether we need one or not, as we use them in moving to rust
1243 out_c.write("static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
1244 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
1245 out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
1246 for var_line in field_var_lines:
1247 if var_line.group(1) in trait_structs:
1248 out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
1249 out_c.write("\treturn (void*) this_arg;\n")
1252 out_java.write("\t}\n")
1254 out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
1255 out_c.write("static inline " + struct_name + " " + struct_name + "_init (JNIEnv * env, jclass _a, jobject o")
1256 for idx, var_line in enumerate(field_var_lines):
1257 if var_line.group(1) in trait_structs:
1258 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
1259 out_c.write(", jobject " + var_line.group(2))
1261 out_java.write(", " + field_var_convs[idx].java_ty + " " + var_line.group(2))
1262 out_c.write(", " + field_var_convs[idx].c_ty + " " + var_line.group(2))
1263 out_java.write(");\n")
1264 out_c.write(") {\n")
1266 out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
1267 out_c.write("\tCHECK(c != NULL);\n")
1268 out_c.write("\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n")
1269 out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
1270 out_c.write("\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n")
1271 out_c.write("\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n")
1272 for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
1273 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1274 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
1275 out_c.write("\tCHECK(calls->" + fn_line.group(2) + "_meth != NULL);\n")
1276 for idx, var_line in enumerate(field_var_lines):
1277 if field_var_convs[idx] is not None and field_var_convs[idx].arg_conv is not None:
1278 out_c.write("\n\t" + field_var_convs[idx].arg_conv.replace("\n", "\n\t") +"\n")
1279 out_c.write("\n\t" + struct_name + " ret = {\n")
1280 out_c.write("\t\t.this_arg = (void*) calls,\n")
1281 for fn_line in trait_fn_lines:
1282 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
1283 out_c.write("\t\t." + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall,\n")
1284 elif fn_line.group(2) == "free":
1285 out_c.write("\t\t.free = " + struct_name + "_JCalls_free,\n")
1287 clone_fns.add(struct_name + "_clone")
1288 out_c.write("\t\t.clone = " + struct_name + "_JCalls_clone,\n")
1289 for idx, var_line in enumerate(field_var_lines):
1290 if var_line.group(1) in trait_structs:
1291 out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(1) + "_init(env, _a, " + var_line.group(2) + "),\n")
1292 elif field_var_convs[idx].arg_conv_name is not None:
1293 out_c.write("\t\t." + var_line.group(2) + " = " + field_var_convs[idx].arg_conv_name + ",\n")
1294 out_c.write("\t\t.set_" + var_line.group(2) + " = NULL,\n")
1296 out_c.write("\t\t." + var_line.group(2) + " = " + var_line.group(2) + ",\n")
1297 out_c.write("\t\t.set_" + var_line.group(2) + " = NULL,\n")
1298 out_c.write("\t};\n")
1299 for var_line in field_var_lines:
1300 if var_line.group(1) in trait_structs:
1301 out_c.write("\tcalls->" + var_line.group(2) + " = ret." + var_line.group(2) + ".this_arg;\n")
1302 out_c.write("\treturn ret;\n")
1305 out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
1306 for idx, var_line in enumerate(field_var_lines):
1307 if var_line.group(1) in trait_structs:
1308 out_c.write(", jobject " + var_line.group(2))
1310 out_c.write(", " + field_var_convs[idx].c_ty + " " + var_line.group(2))
1311 out_c.write(") {\n")
1312 out_c.write("\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1313 out_c.write("\t*res_ptr = " + struct_name + "_init(env, _a, o")
1314 for var_line in field_var_lines:
1315 out_c.write(", " + var_line.group(2))
1317 out_c.write("\treturn (long)res_ptr;\n")
1320 out_java.write("\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n")
1321 out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1get_1obj_1from_1jcalls (JNIEnv * env, jclass _a, jlong val) {\n")
1322 out_c.write("\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n")
1323 out_c.write("\tCHECK(ret != NULL);\n")
1324 out_c.write("\treturn ret;\n")
1327 for fn_line in trait_fn_lines:
1328 # For now, just disable enabling the _call_log - we don't know how to inverse-map String
1329 is_log = fn_line.group(2) == "log" and struct_name == "LDKLogger"
1330 if fn_line.group(2) != "free" and fn_line.group(2) != "clone" and fn_line.group(2) != "eq" and not is_log:
1331 dummy_line = fn_line.group(1) + struct_name.replace("LDK", "") + "_" + fn_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
1332 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")
1333 for idx, var_line in enumerate(field_var_lines):
1334 if var_line.group(1) not in trait_structs:
1335 out_c.write(var_line.group(1) + " " + struct_name + "_set_get_" + var_line.group(2) + "(" + struct_name + "* this_arg) {\n")
1336 out_c.write("\tif (this_arg->set_" + var_line.group(2) + " != NULL)\n")
1337 out_c.write("\t\tthis_arg->set_" + var_line.group(2) + "(this_arg);\n")
1338 out_c.write("\treturn this_arg->" + var_line.group(2) + ";\n")
1340 dummy_line = var_line.group(1) + " " + struct_name.replace("LDK", "") + "_get_" + var_line.group(2) + " " + struct_name + "* this_arg" + fn_line.group(4) + "\n"
1341 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")
1343 out_c.write("""#include \"org_ldk_impl_bindings.h\"
1344 #include <rust_types.h>
1345 #include <lightning.h>
1347 #include <stdatomic.h>
1350 if sys.argv[4] == "false":
1351 out_c.write("#define MALLOC(a, _) malloc(a)\n")
1352 out_c.write("#define FREE(p) if ((p) > 1024) { free(p); }\n")
1353 out_c.write("#define DO_ASSERT(a) (void)(a)\n")
1354 out_c.write("#define CHECK(a)\n")
1356 out_c.write("""#include <assert.h>
1357 // Always run a, then assert it is true:
1358 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
1359 // Assert a is true or do nothing
1360 #define CHECK(a) DO_ASSERT(a)
1362 // Running a leak check across all the allocations and frees of the JDK is a mess,
1363 // so instead we implement our own naive leak checker here, relying on the -wrap
1364 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
1365 // and free'd in Rust or C across the generated bindings shared library.
1366 #include <threads.h>
1367 #include <execinfo.h>
1369 static mtx_t allocation_mtx;
1371 void __attribute__((constructor)) init_mtx() {
1372 DO_ASSERT(mtx_init(&allocation_mtx, mtx_plain) == thrd_success);
1376 typedef struct allocation {
1377 struct allocation* next;
1379 const char* struct_name;
1383 static allocation* allocation_ll = NULL;
1385 void* __real_malloc(size_t len);
1386 void* __real_calloc(size_t nmemb, size_t len);
1387 static void new_allocation(void* res, const char* struct_name) {
1388 allocation* new_alloc = __real_malloc(sizeof(allocation));
1389 new_alloc->ptr = res;
1390 new_alloc->struct_name = struct_name;
1391 new_alloc->bt_len = backtrace(new_alloc->bt, BT_MAX);
1392 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
1393 new_alloc->next = allocation_ll;
1394 allocation_ll = new_alloc;
1395 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
1397 static void* MALLOC(size_t len, const char* struct_name) {
1398 void* res = __real_malloc(len);
1399 new_allocation(res, struct_name);
1402 void __real_free(void* ptr);
1403 static void alloc_freed(void* ptr) {
1404 allocation* p = NULL;
1405 DO_ASSERT(mtx_lock(&allocation_mtx) == thrd_success);
1406 allocation* it = allocation_ll;
1407 while (it->ptr != ptr) {
1408 p = it; it = it->next;
1410 fprintf(stderr, "Tried to free unknown pointer %p at:\\n", ptr);
1412 int bt_len = backtrace(bt, BT_MAX);
1413 backtrace_symbols_fd(bt, bt_len, STDERR_FILENO);
1414 fprintf(stderr, "\\n\\n");
1415 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
1416 return; // addrsan should catch malloc-unknown and print more info than we have
1419 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
1420 DO_ASSERT(mtx_unlock(&allocation_mtx) == thrd_success);
1421 DO_ASSERT(it->ptr == ptr);
1424 static void FREE(void* ptr) {
1425 if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
1430 void* __wrap_malloc(size_t len) {
1431 void* res = __real_malloc(len);
1432 new_allocation(res, "malloc call");
1435 void* __wrap_calloc(size_t nmemb, size_t len) {
1436 void* res = __real_calloc(nmemb, len);
1437 new_allocation(res, "calloc call");
1440 void __wrap_free(void* ptr) {
1445 void* __real_realloc(void* ptr, size_t newlen);
1446 void* __wrap_realloc(void* ptr, size_t len) {
1448 void* res = __real_realloc(ptr, len);
1449 new_allocation(res, "realloc call");
1452 void __wrap_reallocarray(void* ptr, size_t new_sz) {
1453 // Rust doesn't seem to use reallocarray currently
1457 void __attribute__((destructor)) check_leaks() {
1458 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
1459 fprintf(stderr, "%s %p remains:\\n", a->struct_name, a->ptr);
1460 backtrace_symbols_fd(a->bt, a->bt_len, STDERR_FILENO);
1461 fprintf(stderr, "\\n\\n");
1463 DO_ASSERT(allocation_ll == NULL);
1466 out_java.write("""package org.ldk.impl;
1467 import org.ldk.enums.*;
1469 public class bindings {
1470 public static class VecOrSliceDef {
1471 public long dataptr;
1472 public long datalen;
1474 public VecOrSliceDef(long dataptr, long datalen, long stride) {
1475 this.dataptr = dataptr; this.datalen = datalen; this.stride = stride;
1479 System.loadLibrary(\"lightningjni\");
1480 init(java.lang.Enum.class, VecOrSliceDef.class);
1482 static native void init(java.lang.Class c, java.lang.Class slicedef);
1484 public static native boolean deref_bool(long ptr);
1485 public static native long deref_long(long ptr);
1486 public static native void free_heap_ptr(long ptr);
1487 public static native byte[] read_bytes(long ptr, long len);
1488 public static native byte[] get_u8_slice_bytes(long slice_ptr);
1489 public static native long bytes_to_u8_vec(byte[] bytes);
1490 public static native long new_txpointer_copy_data(byte[] txdata);
1491 public static native void txpointer_free(long ptr);
1492 public static native long vec_slice_len(long vec);
1493 public static native long new_empty_slice_vec();
1497 static jmethodID ordinal_meth = NULL;
1498 static jmethodID slicedef_meth = NULL;
1499 static jclass slicedef_cls = NULL;
1500 JNIEXPORT void Java_org_ldk_impl_bindings_init(JNIEnv * env, jclass _b, jclass enum_class, jclass slicedef_class) {
1501 ordinal_meth = (*env)->GetMethodID(env, enum_class, "ordinal", "()I");
1502 CHECK(ordinal_meth != NULL);
1503 slicedef_meth = (*env)->GetMethodID(env, slicedef_class, "<init>", "(JJJ)V");
1504 CHECK(slicedef_meth != NULL);
1505 slicedef_cls = (*env)->NewGlobalRef(env, slicedef_class);
1506 CHECK(slicedef_cls != NULL);
1509 JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_deref_1bool (JNIEnv * env, jclass _a, jlong ptr) {
1510 return *((bool*)ptr);
1512 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_deref_1long (JNIEnv * env, jclass _a, jlong ptr) {
1513 return *((long*)ptr);
1515 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_free_1heap_1ptr (JNIEnv * env, jclass _a, jlong ptr) {
1518 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_read_1bytes (JNIEnv * _env, jclass _b, jlong ptr, jlong len) {
1519 jbyteArray ret_arr = (*_env)->NewByteArray(_env, len);
1520 (*_env)->SetByteArrayRegion(_env, ret_arr, 0, len, (unsigned char*)ptr);
1523 JNIEXPORT jbyteArray JNICALL Java_org_ldk_impl_bindings_get_1u8_1slice_1bytes (JNIEnv * _env, jclass _b, jlong slice_ptr) {
1524 LDKu8slice *slice = (LDKu8slice*)slice_ptr;
1525 jbyteArray ret_arr = (*_env)->NewByteArray(_env, slice->datalen);
1526 (*_env)->SetByteArrayRegion(_env, ret_arr, 0, slice->datalen, slice->data);
1529 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_bytes_1to_1u8_1vec (JNIEnv * _env, jclass _b, jbyteArray bytes) {
1530 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "LDKCVec_u8");
1531 vec->datalen = (*_env)->GetArrayLength(_env, bytes);
1532 vec->data = (uint8_t*)MALLOC(vec->datalen, "LDKCVec_u8Z Bytes");
1533 (*_env)->GetByteArrayRegion (_env, bytes, 0, vec->datalen, vec->data);
1536 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1txpointer_1copy_1data (JNIEnv * env, jclass _b, jbyteArray bytes) {
1537 LDKTransaction *txdata = (LDKTransaction*)MALLOC(sizeof(LDKTransaction), "LDKTransaction");
1538 txdata->datalen = (*env)->GetArrayLength(env, bytes);
1539 txdata->data = (uint8_t*)MALLOC(txdata->datalen, "Tx Data Bytes");
1540 txdata->data_is_owned = false;
1541 (*env)->GetByteArrayRegion (env, bytes, 0, txdata->datalen, txdata->data);
1542 return (long)txdata;
1544 JNIEXPORT void JNICALL Java_org_ldk_impl_bindings_txpointer_1free (JNIEnv * env, jclass _b, jlong ptr) {
1545 LDKTransaction *tx = (LDKTransaction*)ptr;
1546 tx->data_is_owned = true;
1547 Transaction_free(*tx);
1550 JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_vec_1slice_1len (JNIEnv * env, jclass _a, jlong ptr) {
1551 // Check offsets of a few Vec types are all consistent as we're meant to be generic across types
1552 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_SignatureZ, datalen), "Vec<*> needs to be mapped identically");
1553 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_MessageSendEventZ, datalen), "Vec<*> needs to be mapped identically");
1554 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_EventZ, datalen), "Vec<*> needs to be mapped identically");
1555 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKCVec_C2Tuple_usizeTransactionZZ, datalen), "Vec<*> needs to be mapped identically");
1556 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)ptr;
1557 return (long)vec->datalen;
1559 JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_new_1empty_1slice_1vec (JNIEnv * _env, jclass _b) {
1560 // Check sizes of a few Vec types are all consistent as we're meant to be generic across types
1561 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_SignatureZ), "Vec<*> needs to be mapped identically");
1562 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_MessageSendEventZ), "Vec<*> needs to be mapped identically");
1563 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_EventZ), "Vec<*> needs to be mapped identically");
1564 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKCVec_C2Tuple_usizeTransactionZZ), "Vec<*> needs to be mapped identically");
1565 LDKCVec_u8Z *vec = (LDKCVec_u8Z*)MALLOC(sizeof(LDKCVec_u8Z), "Empty LDKCVec");
1571 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
1572 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
1573 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
1574 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
1578 with open(sys.argv[3] + "/structs/CommonBase.java", "a") as out_java_struct:
1579 out_java_struct.write("""package org.ldk.structs;
1580 import java.util.LinkedList;
1583 LinkedList<Object> ptrs_to = new LinkedList();
1584 protected CommonBase(long ptr) { this.ptr = ptr; }
1585 public long _test_only_get_ptr() { return this.ptr; }
1589 in_block_comment = False
1590 cur_block_obj = None
1592 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1594 line_indicates_result_regex = re.compile("^ (LDKCResultPtr_[A-Za-z_0-9]*) contents;$")
1595 line_indicates_vec_regex = re.compile("^ ([A-Za-z_0-9]*) \*data;$")
1596 line_indicates_opaque_regex = re.compile("^ bool is_owned;$")
1597 line_indicates_trait_regex = re.compile("^ ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
1598 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
1599 assert(line_indicates_trait_regex.match(" LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
1600 assert(line_indicates_trait_regex.match(" void *(*clone)(const void *this_arg);"))
1601 line_field_var_regex = re.compile("^ ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
1602 assert(line_field_var_regex.match(" LDKMessageSendEventsProvider MessageSendEventsProvider;"))
1603 assert(line_field_var_regex.match(" LDKChannelPublicKeys pubkeys;"))
1604 struct_name_regex = re.compile("^typedef (struct|enum|union) (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
1605 assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
1606 assert(struct_name_regex.match("typedef enum LDKNetwork {"))
1607 struct_alias_regex = re.compile("^typedef (LDK[A-Za-z_0-9]*) (LDK[A-Za-z_0-9]*);$")
1608 assert(struct_alias_regex.match("typedef LDKCResultTempl_bool__PeerHandleError LDKCResult_boolPeerHandleErrorZ;"))
1610 result_templ_structs = set()
1611 union_enum_items = {}
1612 result_ptr_struct_items = {}
1614 if in_block_comment:
1615 if line.endswith("*/\n"):
1616 in_block_comment = False
1617 elif cur_block_obj is not None:
1618 cur_block_obj = cur_block_obj + line
1619 if line.startswith("} "):
1623 obj_lines = cur_block_obj.split("\n")
1625 result_contents = None
1626 is_unitary_enum = False
1627 is_union_enum = False
1631 field_var_lines = []
1633 for idx, struct_line in enumerate(obj_lines):
1634 if struct_line.strip().startswith("/*"):
1635 in_block_comment = True
1636 if in_block_comment:
1637 if struct_line.endswith("*/"):
1638 in_block_comment = False
1640 struct_name_match = struct_name_regex.match(struct_line)
1641 if struct_name_match is not None:
1642 struct_name = struct_name_match.group(3)
1643 if struct_name_match.group(1) == "enum":
1644 if not struct_name.endswith("_Tag"):
1645 is_unitary_enum = True
1647 is_union_enum = True
1648 elif struct_name_match.group(1) == "union":
1650 if line_indicates_opaque_regex.match(struct_line):
1652 result_match = line_indicates_result_regex.match(struct_line)
1653 if result_match is not None:
1654 result_contents = result_match.group(1)
1655 vec_ty_match = line_indicates_vec_regex.match(struct_line)
1656 if vec_ty_match is not None and struct_name.startswith("LDKCVecTempl_"):
1657 vec_ty = vec_ty_match.group(1)
1658 elif struct_name.startswith("LDKC2TupleTempl_") or struct_name.startswith("LDKC3TupleTempl_"):
1660 trait_fn_match = line_indicates_trait_regex.match(struct_line)
1661 if trait_fn_match is not None:
1662 trait_fn_lines.append(trait_fn_match)
1663 field_var_match = line_field_var_regex.match(struct_line)
1664 if field_var_match is not None:
1665 field_var_lines.append(field_var_match)
1666 field_lines.append(struct_line)
1668 assert(struct_name is not None)
1669 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))
1670 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))
1671 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))
1672 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))
1673 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))
1674 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))
1675 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))
1678 opaque_structs.add(struct_name)
1679 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "w") as out_java_struct:
1680 out_java_struct.write(hu_struct_file_prefix)
1681 out_java_struct.write("public class " + struct_name.replace("LDK","") + " extends CommonBase")
1682 if struct_name.startswith("LDKLocked"):
1683 out_java_struct.write(" implements AutoCloseable")
1684 out_java_struct.write(" {\n")
1685 out_java_struct.write("\t" + struct_name.replace("LDK", "") + "(Object _dummy, long ptr) { super(ptr); }\n")
1686 if struct_name.startswith("LDKLocked"):
1687 out_java_struct.write("\t@Override public void close() {\n")
1689 out_java_struct.write("\t@Override @SuppressWarnings(\"deprecation\")\n")
1690 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1691 out_java_struct.write("\t\tsuper.finalize();\n")
1692 out_java_struct.write("\t\tif (ptr != 0) { bindings." + struct_name.replace("LDK","") + "_free(ptr); }\n")
1693 out_java_struct.write("\t}\n\n")
1694 elif result_contents is not None:
1695 result_templ_structs.add(struct_name)
1696 assert result_contents in result_ptr_struct_items
1697 elif struct_name.startswith("LDKCResultPtr_"):
1698 for line in field_lines:
1699 if line.endswith("*result;"):
1700 res_ty = line[:-8].strip()
1701 elif line.endswith("*err;"):
1702 err_ty = line[:-5].strip()
1703 result_ptr_struct_items[struct_name] = (res_ty, err_ty)
1705 out_java.write("\tpublic static native long " + struct_name + "_new(")
1706 out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new(JNIEnv *_env, jclass _b")
1708 for idx, line in enumerate(field_lines):
1709 if idx != 0 and idx < len(field_lines) - 2:
1710 ty_info = java_c_types(line.strip(';'), None)
1712 out_java.write(", ")
1713 e = chr(ord('a') + idx - 1)
1714 out_java.write(ty_info.java_ty + " " + e)
1715 out_c.write(", " + ty_info.c_ty + " " + e)
1716 ty_list.append(ty_info)
1717 tuple_types[struct_name] = (ty_list, struct_name)
1718 out_java.write(");\n")
1719 out_c.write(") {\n")
1720 out_c.write("\t" + struct_name + "* ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1721 for idx, line in enumerate(field_lines):
1722 if idx != 0 and idx < len(field_lines) - 2:
1723 ty_info = map_type(line.strip(';'), False, None, False, False)
1724 e = chr(ord('a') + idx - 1)
1725 if ty_info.arg_conv is not None:
1726 out_c.write("\t" + ty_info.arg_conv.replace("\n", "\n\t"))
1727 out_c.write("\n\tret->" + e + " = " + ty_info.arg_conv_name + ";\n")
1729 out_c.write("\tret->" + e + " = " + e + ";\n")
1730 if ty_info.arg_conv_cleanup is not None:
1731 out_c.write("\t//TODO: Really need to call " + ty_info.arg_conv_cleanup + " here\n")
1732 out_c.write("\treturn (long)ret;\n")
1734 elif vec_ty is not None:
1735 if vec_ty in opaque_structs:
1736 out_java.write("\tpublic static native long[] " + struct_name + "_arr_info(long vec_ptr);\n")
1737 out_c.write("JNIEXPORT jlongArray JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1739 out_java.write("\tpublic static native VecOrSliceDef " + struct_name + "_arr_info(long vec_ptr);\n")
1740 out_c.write("JNIEXPORT jobject JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1arr_1info(JNIEnv *env, jclass _b, jlong ptr) {\n")
1741 out_c.write("\t" + struct_name + " *vec = (" + struct_name + "*)ptr;\n")
1742 if vec_ty in opaque_structs:
1743 out_c.write("\tjlongArray ret = (*env)->NewLongArray(env, vec->datalen);\n")
1744 out_c.write("\tjlong *ret_elems = (*env)->GetPrimitiveArrayCritical(env, ret, NULL);\n")
1745 out_c.write("\tfor (size_t i = 0; i < vec->datalen; i++) {\n")
1746 out_c.write("\t\tCHECK((((long)vec->data[i].inner) & 1) == 0);\n")
1747 out_c.write("\t\tret_elems[i] = (long)vec->data[i].inner | (vec->data[i].is_owned ? 1 : 0);\n")
1748 out_c.write("\t}\n")
1749 out_c.write("\t(*env)->ReleasePrimitiveArrayCritical(env, ret, ret_elems, 0);\n")
1750 out_c.write("\treturn ret;\n")
1752 out_c.write("\treturn (*env)->NewObject(env, slicedef_cls, slicedef_meth, (long)vec->data, (long)vec->datalen, sizeof(" + vec_ty + "));\n")
1755 ty_info = map_type(vec_ty + " arr_elem", False, None, False, False)
1756 if len(ty_info.java_fn_ty_arg) == 1: # ie we're a primitive of some form
1757 out_java.write("\tpublic static native long " + struct_name + "_new(" + ty_info.java_ty + "[] elems);\n")
1758 out_c.write("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")
1759 out_c.write("\t" + struct_name + " *ret = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n")
1760 out_c.write("\tret->datalen = (*env)->GetArrayLength(env, elems);\n")
1761 out_c.write("\tif (ret->datalen == 0) {\n")
1762 out_c.write("\t\tret->data = NULL;\n")
1763 out_c.write("\t} else {\n")
1764 out_c.write("\t\tret->data = MALLOC(sizeof(" + vec_ty + ") * ret->datalen, \"" + struct_name + " Data\");\n")
1765 out_c.write("\t\t" + ty_info.c_ty + " *java_elems = (*env)->GetPrimitiveArrayCritical(env, elems, NULL);\n")
1766 out_c.write("\t\tfor (size_t i = 0; i < ret->datalen; i++) {\n")
1767 if ty_info.arg_conv is not None:
1768 out_c.write("\t\t\t" + ty_info.c_ty + " arr_elem = java_elems[i];\n")
1769 out_c.write("\t\t\t" + ty_info.arg_conv.replace("\n", "\n\t\t\t") + "\n")
1770 out_c.write("\t\t\tret->data[i] = " + ty_info.arg_conv_name + ";\n")
1771 assert ty_info.arg_conv_cleanup is None
1773 out_c.write("\t\t\tret->data[i] = java_elems[i];\n")
1774 out_c.write("\t\t}\n")
1775 out_c.write("\t\t(*env)->ReleasePrimitiveArrayCritical(env, elems, java_elems, 0);\n")
1776 out_c.write("\t}\n")
1777 out_c.write("\treturn (long)ret;\n")
1780 assert(struct_name.endswith("_Tag"))
1781 struct_name = struct_name[:-4]
1782 union_enum_items[struct_name] = {"field_lines": field_lines}
1783 elif struct_name.endswith("_Body") and struct_name.split("_")[0] in union_enum_items:
1784 enum_var_name = struct_name.split("_")
1785 union_enum_items[enum_var_name[0]][enum_var_name[1]] = field_lines
1786 elif struct_name in union_enum_items:
1787 map_complex_enum(struct_name, union_enum_items[struct_name])
1788 elif is_unitary_enum:
1789 map_unitary_enum(struct_name, field_lines)
1790 elif len(trait_fn_lines) > 0:
1791 trait_structs.add(struct_name)
1792 map_trait(struct_name, field_var_lines, trait_fn_lines)
1793 elif struct_name == "LDKTxOut":
1794 with open(sys.argv[3] + "/structs/TxOut.java", "w") as out_java_struct:
1795 out_java_struct.write(hu_struct_file_prefix)
1796 out_java_struct.write("public class TxOut extends CommonBase{\n")
1797 out_java_struct.write("\tTxOut(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
1798 out_java_struct.write("\tlong to_c_ptr() { return 0; }\n")
1800 out_java_struct.write("}")
1801 elif struct_name == "LDKTransaction":
1802 with open(sys.argv[3] + "/structs/Transaction.java", "w") as out_java_struct:
1803 out_java_struct.write(hu_struct_file_prefix)
1804 out_java_struct.write("public class Transaction extends CommonBase{\n")
1805 out_java_struct.write("\tTransaction(java.lang.Object _dummy, long ptr) { super(ptr); }\n")
1806 out_java_struct.write("\tpublic Transaction(byte[] data) { super(bindings.new_txpointer_copy_data(data)); }\n")
1807 out_java_struct.write("\t@Override public void finalize() throws Throwable { super.finalize(); bindings.txpointer_free(ptr); }\n")
1808 # TODO: Transaction body
1809 out_java_struct.write("}")
1811 pass # Everything remaining is a byte[] or some form
1812 cur_block_obj = None
1814 fn_ptr = fn_ptr_regex.match(line)
1815 fn_ret_arr = fn_ret_arr_regex.match(line)
1816 reg_fn = reg_fn_regex.match(line)
1817 const_val = const_val_regex.match(line)
1819 if line.startswith("#include <"):
1821 elif line.startswith("/*"):
1822 #out_java.write("\t" + line)
1823 if not line.endswith("*/\n"):
1824 in_block_comment = True
1825 elif line.startswith("typedef enum "):
1826 cur_block_obj = line
1827 elif line.startswith("typedef struct "):
1828 cur_block_obj = line
1829 elif line.startswith("typedef union "):
1830 cur_block_obj = line
1831 elif line.startswith("typedef "):
1832 alias_match = struct_alias_regex.match(line)
1833 if alias_match.group(1) in tuple_types:
1834 tuple_types[alias_match.group(2)] = (tuple_types[alias_match.group(1)][0], alias_match.group(2))
1835 tuple_types[alias_match.group(1)] = (tuple_types[alias_match.group(1)][0], alias_match.group(2))
1836 for idx, ty_info in enumerate(tuple_types[alias_match.group(1)][0]):
1837 e = chr(ord('a') + idx)
1838 out_java.write("\tpublic static native " + ty_info.java_ty + " " + alias_match.group(2) + "_get_" + e + "(long ptr);\n")
1839 # XXX: Write C method!
1840 elif alias_match.group(1) in result_templ_structs:
1841 result_types.add(alias_match.group(2))
1842 human_ty = alias_match.group(2).replace("LDKCResult", "Result")
1843 with open(sys.argv[3] + "/structs/" + human_ty + ".java", "w") as out_java_struct:
1844 out_java_struct.write(hu_struct_file_prefix)
1845 out_java_struct.write("public class " + human_ty + " extends CommonBase {\n")
1846 out_java_struct.write("\tprivate " + human_ty + "(Object _dummy, long ptr) { super(ptr); }\n")
1847 out_java_struct.write("\tprotected void finalize() throws Throwable {\n")
1848 out_java_struct.write("\t\tif (ptr != 0) { bindings." + alias_match.group(2).replace("LDK","") + "_free(ptr); } super.finalize();\n")
1849 out_java_struct.write("\t}\n\n")
1850 out_java_struct.write("\tstatic " + human_ty + " constr_from_ptr(long ptr) {\n")
1851 out_java_struct.write("\t\tif (bindings." + alias_match.group(2) + "_result_ok(ptr)) {\n")
1852 out_java_struct.write("\t\t\treturn new " + human_ty + "_OK(null, ptr);\n")
1853 out_java_struct.write("\t\t} else {\n")
1854 out_java_struct.write("\t\t\treturn new " + human_ty + "_Err(null, ptr);\n")
1855 out_java_struct.write("\t\t}\n")
1856 out_java_struct.write("\t}\n")
1858 contents_ty = alias_match.group(1).replace("LDKCResultTempl", "LDKCResultPtr")
1859 res_ty, err_ty = result_ptr_struct_items[contents_ty]
1860 res_map = map_type(res_ty + " res", True, None, False, True)
1861 err_map = map_type(err_ty + " err", True, None, False, True)
1863 out_java.write("\tpublic static native boolean " + alias_match.group(2) + "_result_ok(long arg);\n")
1864 out_c.write("JNIEXPORT jboolean JNICALL Java_org_ldk_impl_bindings_" + alias_match.group(2).replace("_", "_1") + "_1result_1ok (JNIEnv * env, jclass _a, jlong arg) {\n")
1865 out_c.write("\treturn ((" + alias_match.group(2) + "*)arg)->result_ok;\n")
1868 out_java.write("\tpublic static native " + res_map.java_ty + " " + alias_match.group(2) + "_get_ok(long arg);\n")
1869 out_c.write("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")
1870 out_c.write("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
1871 out_c.write("\tCHECK(val->result_ok);\n\t")
1872 out_java_struct.write("\tpublic static final class " + human_ty + "_OK extends " + human_ty + " {\n")
1873 if res_map.ret_conv is not None:
1874 out_c.write(res_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.result)")
1875 out_c.write(res_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + res_map.ret_conv_name)
1877 out_c.write("return *val->contents.result")
1878 out_c.write(";\n}\n")
1880 out_java_struct.write("\t\tpublic final " + res_map.java_hu_ty + " res;\n")
1881 out_java_struct.write("\t\tprivate " + human_ty + "_OK(Object _dummy, long ptr) {\n")
1882 out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1883 if res_map.to_hu_conv is not None:
1884 out_java_struct.write("\t\t\t" + res_map.java_ty + " res = bindings." + alias_match.group(2) + "_get_ok(ptr);\n")
1885 out_java_struct.write("\t\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1886 out_java_struct.write("\n\t\t\tthis.res = " + res_map.to_hu_conv_name + ";\n")
1888 out_java_struct.write("\t\t\tthis.res = bindings." + alias_match.group(2) + "_get_ok(ptr);\n")
1889 out_java_struct.write("\t\t}\n")
1890 if alias_match.group(2).startswith("LDKCResult_None"):
1891 out_java_struct.write("\t\tpublic " + human_ty + "_OK() {\n\t\t\tthis(null, bindings.C" + human_ty + "_ok());\n")
1893 out_java_struct.write("\t\tpublic " + human_ty + "_OK(" + res_map.java_hu_ty + " res) {\n")
1894 if res_map.from_hu_conv is not None:
1895 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(" + res_map.from_hu_conv[0] + "));\n")
1896 if res_map.from_hu_conv[1] != "":
1897 out_java_struct.write("\t\t\t" + res_map.from_hu_conv[1] + ";\n")
1899 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_ok(res));\n")
1900 out_java_struct.write("\t\t}\n\t}\n\n")
1902 out_java.write("\tpublic static native " + err_map.java_ty + " " + alias_match.group(2) + "_get_err(long arg);\n")
1903 out_c.write("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")
1904 out_c.write("\t" + alias_match.group(2) + " *val = (" + alias_match.group(2) + "*)arg;\n")
1905 out_c.write("\tCHECK(!val->result_ok);\n\t")
1906 out_java_struct.write("\tpublic static final class " + human_ty + "_Err extends " + human_ty + " {\n")
1907 if err_map.ret_conv is not None:
1908 out_c.write(err_map.ret_conv[0].replace("\n", "\n\t") + "(*val->contents.err)")
1909 out_c.write(err_map.ret_conv[1].replace("\n", "\n\t") + "\n\treturn " + err_map.ret_conv_name)
1911 out_c.write("return *val->contents.err")
1912 out_c.write(";\n}\n")
1914 out_java_struct.write("\t\tpublic final " + err_map.java_hu_ty + " err;\n")
1915 out_java_struct.write("\t\tprivate " + human_ty + "_Err(Object _dummy, long ptr) {\n")
1916 out_java_struct.write("\t\t\tsuper(_dummy, ptr);\n")
1917 if err_map.to_hu_conv is not None:
1918 out_java_struct.write("\t\t\t" + err_map.java_ty + " err = bindings." + alias_match.group(2) + "_get_err(ptr);\n")
1919 out_java_struct.write("\t\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t\t"))
1920 out_java_struct.write("\n\t\t\tthis.err = " + err_map.to_hu_conv_name + ";\n")
1922 out_java_struct.write("\t\t\tthis.err = bindings." + alias_match.group(2) + "_get_err(ptr);\n")
1923 out_java_struct.write("\t\t}\n")
1925 if alias_match.group(2).endswith("NoneZ"):
1926 out_java_struct.write("\t\tpublic " + human_ty + "_Err() {\n\t\t\tthis(null, bindings.C" + human_ty + "_err());\n")
1928 out_java_struct.write("\t\tpublic " + human_ty + "_Err(" + err_map.java_hu_ty + " err) {\n")
1929 if err_map.from_hu_conv is not None:
1930 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(" + err_map.from_hu_conv[0] + "));\n")
1931 if err_map.from_hu_conv[1] != "":
1932 out_java_struct.write("\t\t\t" + err_map.from_hu_conv[1] + ";\n")
1934 out_java_struct.write("\t\t\tthis(null, bindings.C" + human_ty + "_err(err));\n")
1935 out_java_struct.write("\t\t}\n\t}\n}\n")
1936 elif fn_ptr is not None:
1937 map_fn(line, fn_ptr, None, None)
1938 elif fn_ret_arr is not None:
1939 map_fn(line, fn_ret_arr, fn_ret_arr.group(4), None)
1940 elif reg_fn is not None:
1941 map_fn(line, reg_fn, None, None)
1942 elif const_val_regex is not None:
1943 # TODO Map const variables
1946 assert(line == "\n")
1948 out_java.write("}\n")
1949 for struct_name in opaque_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 for struct_name in trait_structs:
1953 with open(sys.argv[3] + "/structs/" + struct_name.replace("LDK","") + ".java", "a") as out_java_struct:
1954 out_java_struct.write("}\n")