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()
48 var_is_arr_regex = re.compile("\(\*([A-za-z_]*)\)\[([0-9]*)\]")
49 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
50 def java_c_types(fn_arg, ret_arr_len):
51 fn_arg = fn_arg.strip()
52 if fn_arg.startswith("MUST_USE_RES "):
55 if fn_arg.startswith("const "):
62 if fn_arg.startswith("void"):
66 fn_arg = fn_arg[4:].strip()
67 elif fn_arg.startswith("bool"):
71 fn_arg = fn_arg[4:].strip()
72 elif fn_arg.startswith("uint8_t"):
76 fn_arg = fn_arg[7:].strip()
77 elif fn_arg.startswith("uint16_t"):
81 fn_arg = fn_arg[8:].strip()
82 elif fn_arg.startswith("uint32_t"):
86 fn_arg = fn_arg[8:].strip()
87 elif fn_arg.startswith("uint64_t"):
91 fn_arg = fn_arg[8:].strip()
92 elif is_const and fn_arg.startswith("char *"):
95 fn_ty_arg = "Ljava/lang/String;"
96 fn_arg = fn_arg[6:].strip()
98 ma = var_ty_regex.match(fn_arg)
102 fn_arg = ma.group(2).strip()
103 rust_obj = ma.group(1).strip()
106 if fn_arg.startswith(" *") or fn_arg.startswith("*"):
107 fn_arg = fn_arg.replace("*", "").strip()
112 var_is_arr = var_is_arr_regex.match(fn_arg)
113 if var_is_arr is not None or ret_arr_len is not None:
114 assert(not take_by_ptr)
116 java_ty = java_ty + "[]"
117 c_ty = c_ty + "Array"
118 if var_is_arr is not None:
119 return TypeInfo(rust_obj=None, java_ty=java_ty, java_fn_ty_arg="[" + fn_ty_arg, c_ty=c_ty,
120 passed_as_ptr=False, is_ptr=False, var_name=var_is_arr.group(1), arr_len=var_is_arr.group(2))
121 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,
122 is_ptr=is_ptr, var_name=fn_arg, arr_len=None)
124 def map_type(fn_arg, print_void, ret_arr_len, is_free):
125 ty_info = java_c_types(fn_arg, ret_arr_len)
127 if ty_info.c_ty == "void":
129 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
130 arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
132 if ty_info.c_ty.endswith("Array"):
133 arr_len = ty_info.arr_len
134 if arr_len is not None:
135 arr_name = ty_info.var_name
138 arr_len = ret_arr_len
139 assert(ty_info.c_ty == "jbyteArray")
140 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
141 arg_conv = "unsigned char " + arr_name + "_arr[" + arr_len + "];\n" +
142 "(*_env)->GetByteArrayRegion (_env, """ + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" +
143 "unsigned char (*""" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;",
144 arg_conv_name = arr_name + "_ref",
145 ret_conv = ("jbyteArray " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
146 "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", *",
148 ret_conv_name = arr_name + "_arr")
149 elif ty_info.var_name != "":
150 # If we have a parameter name, print it (noting that it may indicate its a pointer)
151 if ty_info.rust_obj is not None:
152 assert(ty_info.passed_as_ptr)
153 if not ty_info.is_ptr:
154 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 + ");";
155 if ty_info.rust_obj in opaque_structs:
156 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
157 arg_conv = base_conv + "\n" + ty_info.var_name + "_conv._underlying_ref = false;",
158 arg_conv_name = ty_info.var_name + "_conv",
159 ret_conv = None, ret_conv_name = None)
160 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
161 arg_conv = base_conv, arg_conv_name = ty_info.var_name + "_conv",
162 ret_conv = None, ret_conv_name = None)
165 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
166 arg_conv = ty_info.rust_obj + "* " + ty_info.var_name + "_conv = (" + ty_info.rust_obj + "*)" + ty_info.var_name + ";",
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 = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
172 elif ty_info.java_ty == "String":
173 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
174 arg_conv = None, arg_conv_name = None,
175 ret_conv = ("jstring " + ty_info.var_name + "_conv = (*_env)->NewStringUTF(_env, ", ");"), ret_conv_name = ty_info.var_name + "_conv")
177 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
178 arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
180 # We don't have a parameter name, and want one, just call it arg
181 if ty_info.rust_obj is not None:
182 assert(not is_free or ty_info.rust_obj not in opaque_structs);
183 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
184 arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nfree((void*)arg);",
185 arg_conv_name = "arg_conv",
186 ret_conv = None, ret_conv_name = None)
189 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
190 arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
192 # We don't have a parameter name, and don't want one (cause we're returning)
193 if ty_info.rust_obj is not None:
194 if not ty_info.is_ptr:
195 if ty_info.rust_obj in opaque_structs:
196 # If we're returning a newly-allocated struct, we don't want Rust to ever
197 # free, instead relying on the Java GC to lose the ref. We undo this in
198 # any _free function.
199 # To avoid any issues, we first assert that the incoming object is non-ref.
200 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
201 ret_conv = (ty_info.rust_obj + "* ret = malloc(sizeof(" + ty_info.rust_obj + "));\n*ret = ", ";\nassert(!ret->_underlying_ref);\nret->_underlying_ref = true;"),
202 ret_conv_name = "(long)ret",
203 arg_conv = None, arg_conv_name = None)
205 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
206 ret_conv = (ty_info.rust_obj + "* ret = malloc(sizeof(" + ty_info.rust_obj + "));\n*ret = ", ";"),
207 ret_conv_name = "(long)ret",
208 arg_conv = None, arg_conv_name = None)
210 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
211 ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
212 arg_conv = None, arg_conv_name = None)
214 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
215 arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
217 def map_fn(re_match, ret_arr_len):
218 out_java.write("\t/// " + line)
219 out_java.write("\tpublic static native ")
220 out_c.write("JNIEXPORT ")
222 ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
224 if ret_info.ret_conv is not None:
225 ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
227 out_java.write(" " + re_match.group(2) + "(")
228 out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
231 for idx, arg in enumerate(re_match.group(3).split(',')):
236 arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
237 if arg_conv_info.c_ty != "void":
238 arg_conv_info.print_ty()
239 arg_conv_info.print_name()
240 arg_names.append(arg_conv_info)
242 out_java.write(");\n")
245 for info in arg_names:
246 if info.arg_conv is not None:
247 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
249 if ret_info.ret_conv is not None:
250 out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
252 out_c.write("\treturn ");
254 out_c.write(re_match.group(2) + "(")
255 for idx, info in enumerate(arg_names):
256 if info.arg_conv_name is not None:
259 out_c.write(info.arg_conv_name)
261 if ret_info.ret_conv is not None:
262 out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
263 out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
266 out_c.write("\n}\n\n")
268 out_java.write("""package org.ldk.impl;
270 public class bindings {
272 System.loadLibrary(\"lightningjni\");
276 out_c.write("#include \"org_ldk_impl_bindings.h\"\n")
277 out_c.write("#include <rust_types.h>\n")
278 out_c.write("#include <lightning.h>\n")
279 out_c.write("#include <assert.h>\n\n")
280 out_c.write("#include <string.h>\n\n")
282 in_block_comment = False
283 in_block_enum = False
284 cur_block_struct = None
285 in_block_union = False
287 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
288 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
289 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
290 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
292 line_indicates_opaque_regex = re.compile("^ bool _underlying_ref;$")
293 line_indicates_trait_regex = re.compile("^ ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
294 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
295 assert(line_indicates_trait_regex.match(" LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
296 assert(line_indicates_trait_regex.match(" void *(*clone)(const void *this_arg);"))
297 struct_name_regex = re.compile("^typedef struct (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
298 assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
302 #out_java.write("\t" + line)
303 if line.endswith("*/\n"):
304 in_block_comment = False
305 elif cur_block_struct is not None:
306 cur_block_struct = cur_block_struct + line
307 if line.startswith("} "):
310 struct_lines = cur_block_struct.split("\n")
314 for idx, struct_line in enumerate(struct_lines):
315 if struct_line.strip().startswith("/*"):
316 in_block_comment = True
318 if struct_line.endswith("*/"):
319 in_block_comment = False
321 struct_name_match = struct_name_regex.match(struct_line)
322 if struct_name_match is not None:
323 struct_name = struct_name_match.group(2)
324 if line_indicates_opaque_regex.match(struct_line):
326 trait_fn_match = line_indicates_trait_regex.match(struct_line)
327 if trait_fn_match is not None:
328 trait_fn_lines.append(trait_fn_match)
329 field_lines.append(struct_line)
331 assert(struct_name is not None)
332 assert(len(trait_fn_lines) == 0 or not is_opaque)
334 opaque_structs.add(struct_name)
335 if len(trait_fn_lines) > 0:
336 out_c.write("typedef struct " + struct_name + "_JCalls {\n")
337 out_c.write("\tJNIEnv *env;\n")
338 out_c.write("\tjobject o;\n")
339 for fn_line in trait_fn_lines:
340 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
341 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
342 out_c.write("} " + struct_name + "_JCalls;\n")
344 out_java.write("\tpublic interface " + struct_name + " {\n")
346 for fn_line in trait_fn_lines:
347 java_meth_descr = "("
348 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
349 ret_ty_info = java_c_types(fn_line.group(1), None)
351 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
352 is_const = fn_line.group(3) is not None
353 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
355 out_c.write("const void* this_arg")
357 out_c.write("void* this_arg")
360 for idx, arg in enumerate(fn_line.group(4).split(',')):
366 arg_conv_info = map_type(arg, True, None, False)
367 out_c.write(arg.strip())
368 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
369 arg_names.append(arg_conv_info)
370 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
371 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
372 java_meths.append(java_meth_descr)
374 out_java.write(");\n")
376 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
378 for arg_info in arg_names:
379 if arg_info.ret_conv is not None:
380 out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "j_calls->env"));
381 out_c.write(arg_info.arg_name)
382 out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "j_calls->env") + "\n")
384 if not ret_ty_info.passed_as_ptr:
385 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")
387 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");
389 for arg_info in arg_names:
390 if arg_info.ret_conv is not None:
391 out_c.write(", " + arg_info.ret_conv_name)
393 out_c.write(", " + arg_info.arg_name)
396 if ret_ty_info.passed_as_ptr:
397 out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
398 out_c.write("\tfree(ret);\n")
399 out_c.write("\treturn res;\n")
401 elif fn_line.group(2) == "free":
402 out_c.write("void " + struct_name + "_JCalls_free(void* this_arg) {\n")
403 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
404 out_c.write("\t(*j_calls->env)->DeleteGlobalRef(j_calls->env, j_calls->o);\n")
405 out_c.write("\tfree(j_calls);\n")
407 elif fn_line.group(2) == "clone":
408 out_c.write("void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
409 out_c.write("\t" + struct_name + "_JCalls *ret = malloc(sizeof(" + struct_name + "_JCalls));\n")
410 out_c.write("\tmemcpy(ret, this_arg, sizeof(" + struct_name + "_JCalls));\n")
411 out_c.write("\treturn ret;\n")
413 out_java.write("\t}\n")
414 out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl);\n")
416 out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o) {\n")
417 out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
418 out_c.write("\tassert(c != NULL);\n")
419 out_c.write("\t" + struct_name + "_JCalls *calls = malloc(sizeof(" + struct_name + "_JCalls));\n")
420 out_c.write("\tcalls->env = env;\n")
421 out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
422 for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
423 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
424 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
425 out_c.write("\tassert(calls->" + fn_line.group(2) + "_meth != NULL);\n")
426 out_c.write("\n\t" + struct_name + " *ret = malloc(sizeof(" + struct_name + "));\n")
427 out_c.write("\tret->this_arg = (void*) calls;\n")
428 for fn_line in trait_fn_lines:
429 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
430 out_c.write("\tret->" + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall;\n")
431 elif fn_line.group(2) == "free":
432 out_c.write("\tret->free = " + struct_name + "_JCalls_free;\n")
434 out_c.write("\tret->clone = " + struct_name + "_JCalls_clone;\n")
435 out_c.write("\treturn (long)ret;\n")
438 #out_java.write("/* " + "\n".join(field_lines) + "*/\n")
439 cur_block_struct = None
441 if line.startswith("} "):
442 in_block_union = False
444 if line.startswith("} "):
445 in_block_enum = False
447 fn_ptr = fn_ptr_regex.match(line)
448 fn_ret_arr = fn_ret_arr_regex.match(line)
449 reg_fn = reg_fn_regex.match(line)
450 const_val = const_val_regex.match(line)
452 if line.startswith("#include <"):
454 elif line.startswith("/*"):
455 #out_java.write("\t" + line)
456 if not line.endswith("*/\n"):
457 in_block_comment = True
458 elif line.startswith("typedef enum "):
460 elif line.startswith("typedef struct "):
461 cur_block_struct = line
462 elif line.startswith("typedef union "):
463 in_block_union = True
464 elif line.startswith("typedef "):
466 elif fn_ptr is not None:
468 elif fn_ret_arr is not None:
469 map_fn(fn_ret_arr, fn_ret_arr.group(4))
470 elif reg_fn is not None:
472 elif const_val_regex is not None:
473 # TODO Map const variables
478 out_java.write("}\n")