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)
115 #assert(not passed_as_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, passed_as_ptr=is_ptr,
120 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)
173 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
174 arg_conv = None, arg_conv_name = ty_info.var_name, ret_conv = None, ret_conv_name = None)
176 # We don't have a parameter name, and want one, just call it arg
177 if ty_info.rust_obj is not None:
178 assert(not is_free or ty_info.rust_obj not in opaque_structs);
179 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
180 arg_conv = ty_info.rust_obj + " arg_conv = *(" + ty_info.rust_obj + "*)arg;\nfree((void*)arg);",
181 arg_conv_name = "arg_conv",
182 ret_conv = None, ret_conv_name = None)
185 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
186 arg_conv = None, arg_conv_name = "arg", ret_conv = None, ret_conv_name = None)
188 # We don't have a parameter name, and don't want one (cause we're returning)
189 if ty_info.rust_obj is not None:
190 if not ty_info.is_ptr:
191 if ty_info.rust_obj in opaque_structs:
192 # If we're returning a newly-allocated struct, we don't want Rust to ever
193 # free, instead relying on the Java GC to lose the ref. We undo this in
194 # any _free function.
195 # To avoid any issues, we first assert that the incoming object is non-ref.
196 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
197 ret_conv = (ty_info.rust_obj + "* ret = malloc(sizeof(" + ty_info.rust_obj + "));\n*ret = ", ";\nassert(!ret->_underlying_ref);\nret->_underlying_ref = true;"),
198 ret_conv_name = "(long)ret",
199 arg_conv = None, arg_conv_name = None)
201 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
202 ret_conv = (ty_info.rust_obj + "* ret = malloc(sizeof(" + ty_info.rust_obj + "));\n*ret = ", ";"),
203 ret_conv_name = "(long)ret",
204 arg_conv = None, arg_conv_name = None)
206 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
207 ret_conv = ("long ret = (long)", ";"), ret_conv_name = "ret",
208 arg_conv = None, arg_conv_name = None)
210 return ConvInfo(ty_info = ty_info, arg_name = ty_info.var_name,
211 arg_conv = None, arg_conv_name = None, ret_conv = None, ret_conv_name = None)
213 def map_fn(re_match, ret_arr_len):
214 out_java.write("\t/// " + line)
215 out_java.write("\tpublic static native ")
216 out_c.write("JNIEXPORT ")
218 ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
220 if ret_info.ret_conv is not None:
221 ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
223 out_java.write(" " + re_match.group(2) + "(")
224 out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
227 for idx, arg in enumerate(re_match.group(3).split(',')):
232 arg_conv_info = map_type(arg, False, None, re_match.group(2).endswith("_free"))
233 if arg_conv_info.c_ty != "void":
234 arg_conv_info.print_ty()
235 arg_conv_info.print_name()
236 arg_names.append(arg_conv_info)
238 out_java.write(");\n")
241 for info in arg_names:
242 if info.arg_conv is not None:
243 out_c.write("\t" + info.arg_conv.replace('\n', "\n\t") + "\n");
245 if ret_info.ret_conv is not None:
246 out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
248 out_c.write("\treturn ");
250 out_c.write(re_match.group(2) + "(")
251 for idx, info in enumerate(arg_names):
252 if info.arg_conv_name is not None:
255 out_c.write(info.arg_conv_name)
257 if ret_info.ret_conv is not None:
258 out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
259 out_c.write("\n\treturn " + ret_info.ret_conv_name + ";")
262 out_c.write("\n}\n\n")
264 out_java.write("""package org.ldk.impl;
266 public class bindings {
268 System.loadLibrary(\"lightningjni\");
272 out_c.write("#include \"org_ldk_impl_bindings.h\"\n")
273 out_c.write("#include <rust_types.h>\n")
274 out_c.write("#include <lightning.h>\n")
275 out_c.write("#include <assert.h>\n\n")
276 out_c.write("#include <string.h>\n\n")
278 in_block_comment = False
279 in_block_enum = False
280 cur_block_struct = None
281 in_block_union = False
283 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
284 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
285 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
286 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
288 line_indicates_opaque_regex = re.compile("^ bool _underlying_ref;$")
289 line_indicates_trait_regex = re.compile("^ ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
290 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
291 assert(line_indicates_trait_regex.match(" LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
292 assert(line_indicates_trait_regex.match(" void *(*clone)(const void *this_arg);"))
293 struct_name_regex = re.compile("^typedef struct (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
294 assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
298 #out_java.write("\t" + line)
299 if line.endswith("*/\n"):
300 in_block_comment = False
301 elif cur_block_struct is not None:
302 cur_block_struct = cur_block_struct + line
303 if line.startswith("} "):
306 struct_lines = cur_block_struct.split("\n")
310 for idx, struct_line in enumerate(struct_lines):
311 if struct_line.strip().startswith("/*"):
312 in_block_comment = True
314 if struct_line.endswith("*/"):
315 in_block_comment = False
317 struct_name_match = struct_name_regex.match(struct_line)
318 if struct_name_match is not None:
319 struct_name = struct_name_match.group(2)
320 if line_indicates_opaque_regex.match(struct_line):
322 trait_fn_match = line_indicates_trait_regex.match(struct_line)
323 if trait_fn_match is not None:
324 trait_fn_lines.append(trait_fn_match)
325 field_lines.append(struct_line)
327 assert(struct_name is not None)
328 assert(len(trait_fn_lines) == 0 or not is_opaque)
330 opaque_structs.add(struct_name)
331 if len(trait_fn_lines) > 0:
332 out_c.write("typedef struct " + struct_name + "_JCalls {\n")
333 out_c.write("\tJNIEnv *env;\n")
334 out_c.write("\tjobject o;\n")
335 for fn_line in trait_fn_lines:
336 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
337 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
338 out_c.write("} " + struct_name + "_JCalls;\n")
340 out_java.write("\tpublic interface " + struct_name + " {\n")
342 for fn_line in trait_fn_lines:
343 java_meth_descr = "("
344 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
345 ret_ty_info = java_c_types(fn_line.group(1), None)
347 out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
348 is_const = fn_line.group(3) is not None
349 out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
351 out_c.write("const void* this_arg")
353 out_c.write("void* this_arg")
356 for idx, arg in enumerate(fn_line.group(4).split(',')):
362 arg_conv_info = map_type(arg, True, None, False)
363 out_c.write(arg.strip())
364 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
365 arg_names.append(arg_conv_info)
366 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
367 java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
368 java_meths.append(java_meth_descr)
370 out_java.write(");\n")
372 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
374 for arg_info in arg_names:
375 if arg_info.ret_conv is not None:
376 out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "j_calls->env"));
377 out_c.write(arg_info.arg_name)
378 out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "j_calls->env") + "\n")
380 if not ret_ty_info.passed_as_ptr:
381 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")
383 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");
385 for arg_info in arg_names:
386 if arg_info.ret_conv is not None:
387 out_c.write(", " + arg_info.ret_conv_name)
389 out_c.write(", " + arg_info.arg_name)
392 if ret_ty_info.passed_as_ptr:
393 out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
394 out_c.write("\tfree(ret);\n")
395 out_c.write("\treturn res;\n")
397 elif fn_line.group(2) == "free":
398 out_c.write("void " + struct_name + "_JCalls_free(void* this_arg) {\n")
399 out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
400 out_c.write("\t(*j_calls->env)->DeleteGlobalRef(j_calls->env, j_calls->o);\n")
401 out_c.write("\tfree(j_calls);\n")
403 elif fn_line.group(2) == "clone":
404 out_c.write("void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
405 out_c.write("\t" + struct_name + "_JCalls *ret = malloc(sizeof(" + struct_name + "_JCalls));\n")
406 out_c.write("\tmemcpy(ret, this_arg, sizeof(" + struct_name + "_JCalls));\n")
407 out_c.write("\treturn ret;\n")
409 out_java.write("\t}\n")
410 out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl);\n")
412 out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o) {\n")
413 out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
414 out_c.write("\tassert(c != NULL);\n")
415 out_c.write("\t" + struct_name + "_JCalls *calls = malloc(sizeof(" + struct_name + "_JCalls));\n")
416 out_c.write("\tcalls->env = env;\n")
417 out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
418 for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
419 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
420 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
421 out_c.write("\tassert(calls->" + fn_line.group(2) + "_meth != NULL);\n")
422 out_c.write("\n\t" + struct_name + " *ret = malloc(sizeof(" + struct_name + "));\n")
423 out_c.write("\tret->this_arg = (void*) calls;\n")
424 for fn_line in trait_fn_lines:
425 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
426 out_c.write("\tret->" + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall;\n")
427 elif fn_line.group(2) == "free":
428 out_c.write("\tret->free = " + struct_name + "_JCalls_free;\n")
430 out_c.write("\tret->clone = " + struct_name + "_JCalls_clone;\n")
431 out_c.write("\treturn (long)ret;\n")
434 #out_java.write("/* " + "\n".join(field_lines) + "*/\n")
435 cur_block_struct = None
437 if line.startswith("} "):
438 in_block_union = False
440 if line.startswith("} "):
441 in_block_enum = False
443 fn_ptr = fn_ptr_regex.match(line)
444 fn_ret_arr = fn_ret_arr_regex.match(line)
445 reg_fn = reg_fn_regex.match(line)
446 const_val = const_val_regex.match(line)
448 if line.startswith("#include <"):
450 elif line.startswith("/*"):
451 #out_java.write("\t" + line)
452 if not line.endswith("*/\n"):
453 in_block_comment = True
454 elif line.startswith("typedef enum "):
456 elif line.startswith("typedef struct "):
457 cur_block_struct = line
458 elif line.startswith("typedef union "):
459 in_block_union = True
460 elif line.startswith("typedef "):
462 elif fn_ptr is not None:
464 elif fn_ret_arr is not None:
465 map_fn(fn_ret_arr, fn_ret_arr.group(4))
466 elif reg_fn is not None:
468 elif const_val_regex is not None:
469 # TODO Map const variables
474 out_java.write("}\n")