5 print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /path/to/bindings/output.c")
9 def __init__(self, rust_obj, java_ty, java_fn_ty_arg, c_ty, passed_as_ptr, is_ptr, var_name, arr_len):
10 self.rust_obj = rust_obj
11 self.java_ty = java_ty
12 self.java_fn_ty_arg = java_fn_ty_arg
14 self.passed_as_ptr = passed_as_ptr
16 self.var_name = var_name
17 self.arr_len = arr_len
20 def __init__(self, ty_info, arg_name, arg_conv, arg_conv_name, ret_conv, ret_conv_name):
21 assert(ty_info.c_ty is not None)
22 assert(ty_info.java_ty is not None)
23 assert(arg_name is not None)
24 self.c_ty = ty_info.c_ty
25 self.java_ty = ty_info.java_ty
26 self.java_fn_ty_arg = ty_info.java_fn_ty_arg
27 self.arg_name = arg_name
28 self.arg_conv = arg_conv
29 self.arg_conv_name = arg_conv_name
30 self.ret_conv = ret_conv
31 self.ret_conv_name = ret_conv_name
34 out_c.write(self.c_ty)
35 out_java.write(self.java_ty)
38 if self.arg_name != "":
39 out_java.write(" " + self.arg_name)
40 out_c.write(" " + self.arg_name)
42 out_java.write(" arg")
45 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[3], "w") as out_c:
46 opaque_structs = set()
49 var_is_arr_regex = re.compile("\(\*([A-za-z_]*)\)\[([0-9]*)\]")
50 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
51 def java_c_types(fn_arg, ret_arr_len):
52 fn_arg = fn_arg.strip()
53 if fn_arg.startswith("MUST_USE_RES "):
56 if fn_arg.startswith("const "):
63 if fn_arg.startswith("void"):
67 fn_arg = fn_arg[4:].strip()
68 elif fn_arg.startswith("bool"):
72 fn_arg = fn_arg[4:].strip()
73 elif fn_arg.startswith("uint8_t"):
77 fn_arg = fn_arg[7:].strip()
78 elif fn_arg.startswith("uint16_t"):
82 fn_arg = fn_arg[8:].strip()
83 elif fn_arg.startswith("uint32_t"):
87 fn_arg = fn_arg[8:].strip()
88 elif fn_arg.startswith("uint64_t"):
92 fn_arg = fn_arg[8:].strip()
93 elif is_const and fn_arg.startswith("char *"):
96 fn_ty_arg = "Ljava/lang/String;"
97 fn_arg = fn_arg[6:].strip()
99 ma = var_ty_regex.match(fn_arg)
103 fn_arg = ma.group(2).strip()
104 rust_obj = ma.group(1).strip()
107 if fn_arg.startswith(" *") or fn_arg.startswith("*"):
108 fn_arg = fn_arg.replace("*", "").strip()
113 var_is_arr = var_is_arr_regex.match(fn_arg)
114 if var_is_arr is not None or ret_arr_len is not None:
115 assert(not take_by_ptr)
117 java_ty = java_ty + "[]"
118 c_ty = c_ty + "Array"
119 if var_is_arr is not None:
120 return TypeInfo(rust_obj=None, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
121 passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2))
122 return TypeInfo(rust_obj=rust_obj, java_ty=java_ty, java_fn_ty_arg=fn_ty_arg, c_ty=c_ty, passed_as_ptr=is_ptr or take_by_ptr,
123 is_ptr=is_ptr, var_name=fn_arg, arr_len=None)
125 def map_type(fn_arg, print_void, ret_arr_len, is_free):
126 ty_info = java_c_types(fn_arg, ret_arr_len)
128 if ty_info.c_ty == "void":
130 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
131 arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
133 if ty_info.c_ty.endswith("Array"):
134 arr_len = ty_info.arr_len
135 if arr_len is not None:
136 arr_name = ty_info.var_name
139 arr_len = ret_arr_len
140 assert(ty_info.c_ty == "jbyteArray")
141 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
142 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n" +
143 "(*_env)->GetByteArrayRegion (_env, """ + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" +
144 "unsigned char (*""" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;",
145 arg_conv_name = arr_name + "_ref",
146 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
147 "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", *",
149 ret_conv_name = arr_name + "_arr")
150 elif ty_info.var_name != "":
151 # If we have a parameter name, print it (noting that it may indicate its a pointer)
152 if ty_info.rust_obj is not None:
153 assert(ty_info.passed_as_ptr)
154 if not ty_info.is_ptr:
155 if ty_info.rust_obj in trait_structs:
156 base_conv = ty_info.rust_obj + " *" + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";"
158 base_conv = base_conv + "\n" + ty_info.rust_obj + "_JCalls_clone(" + ty_info.var_name + "_conv->this_arg);"
159 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
160 arg_conv = base_conv,
161 arg_conv_name = "*" + ty_info.var_name + "_conv",
162 ret_conv = None, ret_conv_name = None)
163 base_conv = ty_info.rust_obj + " " + ty_info.var_name + "_conv = *(" + ty_info.rust_obj + "*)" + ty_info.var_name + ";\nfree((void*)" + ty_info.var_name + ");";
164 if ty_info.rust_obj in opaque_structs:
165 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
166 arg_conv = base_conv + "\n" + ty_info.var_name + "_conv._underlying_ref = false;",
167 arg_conv_name = ty_info.var_name + "_conv",
168 ret_conv = None, ret_conv_name = None)
170 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
171 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
172 ret_conv = None, ret_conv_name = None)
175 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
176 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
177 arg_conv_name = ty_info.var_name + "_conv",
178 ret_conv = None, ret_conv_name = None)
180 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
181 arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
182 elif ty_info.java_ty == "String":
183 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
184 arg_conv = None, arg_conv_name = None,
185 ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
187 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
188 arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
190 # We don't have a parameter name, and want one, just call it arg
191 if ty_info.rust_obj is not None:
192 assert(not is_free or ty_info.rust_obj not in opaque_structs);
193 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
194 arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nfree((void*)arg);",
195 arg_conv_name = "arg_conv",
196 ret_conv = None, ret_conv_name = None)
199 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
200 arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
202 # We don't have a parameter name, and don't want one (cause we're returning)
203 if ty_info.rust_obj is not None:
204 if not ty_info.is_ptr:
205 if ty_info.rust_obj in opaque_structs:
206 # If we're returning a newly-allocated struct, we don't want Rust to ever
207 # free, instead relying on the Java GC to lose the ref. We undo this in
208 # any _free function.
209 # To avoid any issues, we first assert that the incoming object is non-ref.
210 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
211 ret_conv = (ty_info.rust_obj + "* ret = malloc(sizeof(" + ty_info.rust_obj + "));\n*ret = ", ";\nassert(!ret->_underlying_ref);\nret->_underlying_ref = true;"),
212 ret_conv_name = "(long)ret",
213 arg_conv = None, arg_conv_name = None)
215 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
216 ret_conv = (ty_info.rust_obj + "* ret = malloc(sizeof(" + ty_info.rust_obj + "));\n*ret = ", ";"),
217 ret_conv_name = "(long)ret",
218 arg_conv = None, arg_conv_name = None)
220 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
221 ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
222 arg_conv = None, arg_conv_name = None)
224 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
225 arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
227 def map_fn(re_match, ret_arr_len):
228 out_java.write("\t/// " + line)
229 out_java.write("\tpublic static native ")
230 out_c.write("JNIEXPORT ")
232 ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
234 if ret_info.ret_conv is not None:
235 ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
237 out_java.write(" " + re_match.group(2) + "(")
238 out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
241 for idx, arg in enumerate(re_match.group(3).split(',')):
246 arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
247 if arg_conv_info.c_ty != "void":
248 arg_conv_info.print_ty()
249 arg_conv_info.print_name()
250 arg_names.append(arg_conv_info)
252 out_java.write(");\n")
255 for info in arg_names:
256 if info.arg_conv is not None:
257 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
259 if ret_info.ret_conv is not None:
260 out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
262 out_c.write("\treturn ");
264 out_c.write(re_match.group(2) + "(")
265 for idx, info in enumerate(arg_names):
266 if info.arg_conv_name is not None:
269 out_c.write(info.arg_conv_name)
271 if ret_info.ret_conv is not None:
272 out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
273 out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
276 out_c.write("\n}\n\n")
278 out_java.write("""package org.ldk.impl;
280 public class bindings {
282 System.loadLibrary(\"lightningjni\");
286 out_c.write("#include \"org_ldk_impl_bindings.h\"\n")
287 out_c.write("#include <rust_types.h>\n")
288 out_c.write("#include <lightning.h>\n")
289 out_c.write("#include <assert.h>\n")
290 out_c.write("#include <string.h>\n")
291 out_c.write("#include <stdatomic.h>\n\n")
293 in_block_comment = False
294 in_block_enum = False
295 cur_block_struct = None
296 in_block_union = False
298 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
299 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
300 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
301 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
303 line_indicates_opaque_regex = re.compile("^ bool _underlying_ref;$")
304 line_indicates_trait_regex = re.compile("^ ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
305 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
306 assert(line_indicates_trait_regex.match(" LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
307 assert(line_indicates_trait_regex.match(" void *(*clone)(const void *this_arg);"))
308 line_field_var_regex = re.compile("^ ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
309 assert(line_field_var_regex.match(" LDKMessageSendEventsProvider MessageSendEventsProvider;"))
310 struct_name_regex = re.compile("^typedef struct (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
311 assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
315 #out_java.write("\t" + line)
316 if line.endswith("*/\n"):
317 in_block_comment = False
318 elif cur_block_struct is not None:
319 cur_block_struct = cur_block_struct + line
320 if line.startswith("} "):
323 struct_lines = cur_block_struct.split("\n")
328 for idx, struct_line in enumerate(struct_lines):
329 if struct_line.strip().startswith("/*"):
330 in_block_comment = True
332 if struct_line.endswith("*/"):
333 in_block_comment = False
335 struct_name_match = struct_name_regex.match(struct_line)
336 if struct_name_match is not None:
337 struct_name = struct_name_match.group(2)
338 if line_indicates_opaque_regex.match(struct_line):
340 trait_fn_match = line_indicates_trait_regex.match(struct_line)
341 if trait_fn_match is not None:
342 trait_fn_lines.append(trait_fn_match)
343 field_var_match = line_field_var_regex.match(struct_line)
344 if field_var_match is not None:
345 field_var_lines.append(field_var_match)
346 field_lines.append(struct_line)
348 assert(struct_name is not None)
349 assert(len(trait_fn_lines) == 0 or not is_opaque)
351 opaque_structs.add(struct_name)
352 if len(trait_fn_lines) > 0:
353 trait_structs.add(struct_name)
354 out_c.write("typedef struct " + struct_name + "_JCalls {\n")
355 out_c.write("\tatomic_size_t refcnt;\n")
356 out_c.write("\tJNIEnv *env;\n")
357 out_c.write("\tjobject o;\n")
358 for var_line in field_var_lines:
359 if var_line.group(1) in trait_structs:
360 out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
361 for fn_line in trait_fn_lines:
362 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
363 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
364 out_c.write("} " + struct_name + "_JCalls;\n")
366 out_java.write("\tpublic interface " + struct_name + " {\n")
368 for fn_line in trait_fn_lines:
369 java_meth_descr = "("
370 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
371 ret_ty_info = java_c_types(fn_line.group(1), None)
373 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
374 is_const = fn_line.group(3) is not None
375 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
377 out_c.write("const void* this_arg")
379 out_c.write("void* this_arg")
382 for idx, arg in enumerate(fn_line.group(4).split(',')):
388 arg_conv_info = map_type(arg, True, None, False)
389 out_c.write(arg.strip())
390 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
391 arg_names.append(arg_conv_info)
392 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
393 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
394 java_meths.append(java_meth_descr)
396 out_java.write(");\n")
398 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
400 for arg_info in arg_names:
401 if arg_info.ret_conv is not None:
402 out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "j_calls->env"));
403 out_c.write(arg_info.arg_name)
404 out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "j_calls->env") + "\n")
406 if not ret_ty_info.passed_as_ptr:
407 out_c.write("\treturn (*j_calls->env)->Call" + ret_ty_info.java_ty.title() + "Method(j_calls->env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth")
409 out_c.write("\t" + fn_line.group(1).strip() + "* ret = (" + fn_line.group(1).strip() + "*)(*j_calls->env)->CallLongMethod(j_calls->env, j_calls->o, j_calls->" + fn_line.group(2) + "_meth");
411 for arg_info in arg_names:
412 if arg_info.ret_conv is not None:
413 out_c.write(", " + arg_info.ret_conv_name)
415 out_c.write(", " + arg_info.arg_name)
418 if ret_ty_info.passed_as_ptr:
419 out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
420 out_c.write("\tfree(ret);\n")
421 out_c.write("\treturn res;\n")
423 elif fn_line.group(2) == "free":
424 out_c.write("void " + struct_name + "_JCalls_free(void* this_arg) {\n")
425 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
426 out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
427 out_c.write("\t\t(*j_calls->env)->DeleteGlobalRef(j_calls->env, j_calls->o);\n")
428 out_c.write("\t\tfree(j_calls);\n")
429 out_c.write("\t}\n}\n")
431 # Write out a clone function whether we need one or not, as we use them in moving to rust
432 out_c.write("void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
433 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
434 out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
435 for var_line in field_var_lines:
436 if var_line.group(1) in trait_structs:
437 out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
438 out_c.write("\treturn (void*) this_arg;\n")
441 out_java.write("\t}\n")
443 out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
444 out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
445 for var_line in field_var_lines:
446 if var_line.group(1) in trait_structs:
447 out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
448 out_c.write(", jobject " + var_line.group(2))
449 out_java.write(");\n")
452 out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
453 out_c.write("\tassert(c != NULL);\n")
454 out_c.write("\t" + struct_name + "_JCalls *calls = malloc(sizeof(" + struct_name + "_JCalls));\n")
455 out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
456 out_c.write("\tcalls->env = env;\n")
457 out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
458 for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
459 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
460 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
461 out_c.write("\tassert(calls->" + fn_line.group(2) + "_meth != NULL);\n")
462 out_c.write("\n\t" + struct_name + " *ret = malloc(sizeof(" + struct_name + "));\n")
463 out_c.write("\tret->this_arg = (void*) calls;\n")
464 for fn_line in trait_fn_lines:
465 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
466 out_c.write("\tret->" + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall;\n")
467 elif fn_line.group(2) == "free":
468 out_c.write("\tret->free = " + struct_name + "_JCalls_free;\n")
470 out_c.write("\tret->clone = " + struct_name + "_JCalls_clone;\n")
471 for var_line in field_var_lines:
472 if var_line.group(1) in trait_structs:
473 out_c.write("\tret->" + var_line.group(2) + " = *(" + var_line.group(1) + "*)Java_org_ldk_impl_bindings_" + var_line.group(1) + "_1new(env, _a, " + var_line.group(2) + ");\n")
474 out_c.write("\tcalls->" + var_line.group(2) + " = ret->" + var_line.group(2) + ".this_arg;\n")
475 out_c.write("\treturn (long)ret;\n")
478 #out_java.write("/* " + "\n".join(field_lines) + "*/\n")
479 cur_block_struct = None
481 if line.startswith("} "):
482 in_block_union = False
484 if line.startswith("} "):
485 in_block_enum = False
487 fn_ptr = fn_ptr_regex.match(line)
488 fn_ret_arr = fn_ret_arr_regex.match(line)
489 reg_fn = reg_fn_regex.match(line)
490 const_val = const_val_regex.match(line)
492 if line.startswith("#include <"):
494 elif line.startswith("/*"):
495 #out_java.write("\t" + line)
496 if not line.endswith("*/\n"):
497 in_block_comment = True
498 elif line.startswith("typedef enum "):
500 elif line.startswith("typedef struct "):
501 cur_block_struct = line
502 elif line.startswith("typedef union "):
503 in_block_union = True
504 elif line.startswith("typedef "):
506 elif fn_ptr is not None:
508 elif fn_ret_arr is not None:
509 map_fn(fn_ret_arr, fn_ret_arr.group(4))
510 elif reg_fn is not None:
512 elif const_val_regex is not None:
513 # TODO Map const variables
518 out_java.write("}\n")