5 print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /path/to/bindings/output.c")
8 with open(sys.argv[1]) as in_h, open(sys.argv[2], "w") as out_java, open(sys.argv[3], "w") as out_c:
11 var_is_arr_regex = re.compile("\(\*([A-za-z_]*)\)\[([0-9]*)\]")
12 var_ty_regex = re.compile("([A-za-z_0-9]*)(.*)")
13 def map_type(fn_arg, print_void, ret_arr_len, is_free):
14 fn_arg = fn_arg.strip()
15 if fn_arg.startswith("MUST_USE_RES "):
17 if fn_arg.startswith("const "):
22 if fn_arg.startswith("void"):
24 out_java.write("void")
27 return (None, None, None)
28 fn_arg = fn_arg.strip("void ")
29 elif fn_arg.startswith("bool"):
30 out_java.write("boolean")
32 fn_arg = fn_arg.strip("bool ")
33 elif fn_arg.startswith("uint8_t"):
34 out_java.write("byte")
36 fn_arg = fn_arg.strip("uint8_t ")
37 elif fn_arg.startswith("uint32_t"):
40 fn_arg = fn_arg.strip("uint32_t ")
41 elif fn_arg.startswith("uint64_t"):
42 out_java.write("long")
44 fn_arg = fn_arg.strip("uint64_t ")
46 ma = var_ty_regex.match(fn_arg)
47 out_java.write("long")
49 is_ptr_to_obj = ma.group(1)
54 var_is_arr = var_is_arr_regex.match(fn_arg)
55 no_ptr = fn_arg.replace('*', '')
56 if var_is_arr is not None or ret_arr_len is not None:
59 if var_is_arr is not None:
60 arr_name = var_is_arr.group(1)
61 arr_len = var_is_arr.group(2)
62 out_java.write(arr_name)
67 assert(c_ty == "jbyte")
68 return ("unsigned char " + arr_name + "_arr[" + arr_len + "];\n" +
69 "(*_env)->GetByteArrayRegion (_env, """ + arr_name + ", 0, " + arr_len + ", " + arr_name + "_arr);\n" +
70 "unsigned char (*""" + arr_name + "_ref)[" + arr_len + "] = &" + arr_name + "_arr;",
71 (c_ty + "Array " + arr_name + "_arr = (*_env)->NewByteArray(_env, " + arr_len + ");\n" +
72 "(*_env)->SetByteArrayRegion(_env, " + arr_name + "_arr, 0, " + arr_len + ", *",
73 ");\nreturn ret_arr;"),
75 elif no_ptr.strip() != "":
76 # If we have a parameter name, print it (noting that it may indicate its a pointer)
77 out_java.write(" " + no_ptr.strip())
78 out_c.write(" " + no_ptr.strip())
79 if is_ptr_to_obj is not None:
81 base_conv = is_ptr_to_obj + " " + no_ptr.strip() + "_conv = *(" + is_ptr_to_obj + "*)" + no_ptr.strip() + ";\nfree((void*)" + no_ptr.strip() + ");";
82 if is_ptr_to_obj in opaque_structs:
83 return (base_conv + "\n" + no_ptr.strip() + "_conv._underlying_ref = false;",
84 "XXX2", no_ptr.strip() + "_conv")
85 return (base_conv, "XXX2", no_ptr.strip() + "_conv")
88 return (is_ptr_to_obj + "* " + no_ptr.strip() + "_conv = (" + is_ptr_to_obj + "*)" + no_ptr.strip() + ";",
89 "XXX2", no_ptr.strip() + "_conv")
90 elif no_ptr != fn_arg:
91 return ("YYY1", "XXX3", no_ptr.strip())
93 return (None, "XXX4", no_ptr.strip())
95 # We don't have a parameter name, and want one, just call it arg
96 out_java.write(" arg")
98 if is_ptr_to_obj is not None:
99 assert(not is_free or is_ptr_to_obj not in opaque_structs);
100 return (is_ptr_to_obj + " arg_conv = *(" + is_ptr_to_obj + "*)arg;\nfree((void*)arg);", "XXX2", "arg_conv")
103 return (None, "XXX6", "arg")
105 # We don't have a parameter name, and don't want one (cause we're returning)
106 if is_ptr_to_obj is not None:
108 if is_ptr_to_obj in opaque_structs:
109 # If we're returning a newly-allocated struct, we don't want Rust to ever
110 # free, instead relying on the Java GC to lose the ref. We undo this in
111 # any _free function.
112 # To avoid any issues, we first assert that the incoming object is non-ref.
113 return (None, (is_ptr_to_obj + "* ret = malloc(sizeof(" + is_ptr_to_obj + "));\n*ret = ", ";\nassert(!ret->_underlying_ref);\nret->_underlying_ref = true;\nreturn (long)ret;"), None)
115 return (None, (is_ptr_to_obj + "* ret = malloc(sizeof(" + is_ptr_to_obj + "));\n*ret = ", ";\nreturn (long)ret;"), None)
117 return (None, ("return (long) ", ";"), None)
119 return (None, None, None)
121 def map_fn(re_match, ret_arr_len):
122 out_java.write("\t/// " + line)
123 out_java.write("\tpublic static native ")
124 out_c.write("JNIEXPORT ")
126 _, ret_conv, _ = map_type(re_match.group(1), True, ret_arr_len, False)
127 if ret_conv is not None:
128 ret_conv_pfx, ret_conv_sfx = ret_conv
130 out_java.write(" " + re_match.group(2) + "(")
131 out_c.write(" JNICALL Java_org_ldk_impl_bindings_" + re_match.group(2).replace('_', '_1') + "(JNIEnv * _env, jclass _b")
134 for idx, arg in enumerate(re_match.group(3).split(',')):
139 arg_names.append(map_type(arg, False, None, re_match.group(2).endswith("_free")))
141 out_java.write(");\n")
144 for arg_conv, _, _ in arg_names:
145 if arg_conv is not None:
146 out_c.write("\t" + arg_conv.replace('\n', "\n\t") + "\n");
148 if ret_conv is not None:
149 out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
151 out_c.write("\treturn ");
153 out_c.write(re_match.group(2) + "(")
154 for idx, (_, _, arg) in enumerate(arg_names):
160 if ret_conv is not None:
161 out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
164 out_c.write("\n}\n\n")
166 out_java.write("""package org.ldk.impl;
168 public class bindings {
170 System.loadLibrary(\"lightningjni\");
174 out_c.write("#include \"org_ldk_impl_bindings.h\"\n")
175 out_c.write("#include <rust_types.h>\n")
176 out_c.write("#include <lightning.h>\n")
177 out_c.write("#include <assert.h>\n\n")
178 out_c.write("#include <string.h>\n\n")
180 in_block_comment = False
181 in_block_enum = False
182 cur_block_struct = None
183 in_block_union = False
185 fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
186 fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
187 reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
188 const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
190 line_indicates_opaque_regex = re.compile("^ bool _underlying_ref;$")
191 line_indicates_trait_regex = re.compile("^ ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg.*\);$")
192 assert(line_indicates_trait_regex.match(" uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
193 assert(line_indicates_trait_regex.match(" LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
194 assert(line_indicates_trait_regex.match(" void *(*clone)(const void *this_arg);"))
195 struct_name_regex = re.compile("^typedef struct (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
196 assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
200 #out_java.write("\t" + line)
201 if line.endswith("*/\n"):
202 in_block_comment = False
203 elif cur_block_struct is not None:
204 cur_block_struct = cur_block_struct + line
205 if line.startswith("} "):
208 struct_lines = cur_block_struct.split("\n")
212 for idx, struct_line in enumerate(struct_lines):
213 if struct_line.strip().startswith("/*"):
214 in_block_comment = True
216 if struct_line.endswith("*/"):
217 in_block_comment = False
219 struct_name_match = struct_name_regex.match(struct_line)
220 if struct_name_match is not None:
221 struct_name = struct_name_match.group(2)
222 if line_indicates_opaque_regex.match(struct_line):
224 trait_fn_match = line_indicates_trait_regex.match(struct_line)
225 if trait_fn_match is not None:
226 trait_fn_lines.append(trait_fn_match)
227 field_lines.append(struct_line)
229 assert(struct_name is not None)
230 assert(len(trait_fn_lines) == 0 or not is_opaque)
232 opaque_structs.add(struct_name)
233 if len(trait_fn_lines) > 0:
234 out_java.write("\tpublic interface " + struct_name + " {\n")
235 for fn_line in trait_fn_lines:
236 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
237 out_java.write("\t\t void " + fn_line.group(2) + "(/* TODO + rtype */);\n")
238 out_java.write("\t}\n")
239 out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl);\n")
241 out_c.write("typedef struct " + struct_name + "_JCalls {\n")
242 out_c.write("\tJNIEnv *env;\n")
243 out_c.write("\tjobject o;\n")
244 for fn_line in trait_fn_lines:
245 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
246 out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
247 out_c.write("} " + struct_name + "_JCalls;\n")
249 for fn_line in trait_fn_lines:
250 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
251 out_c.write("void " + fn_line.group(2) + "_jcall(void* this_arg/* TODO + rtype */) {\n")
252 out_c.write("\t" + struct_name + "_JCalls *arg = (" + struct_name + "_JCalls*) this_arg;\n")
253 out_c.write("\t(*arg->env)->CallObjectMethod(arg->env, arg->o, arg->" + fn_line.group(2) + "_meth);\n");
255 elif fn_line.group(2) == "free":
256 out_c.write("void " + struct_name + "_JCalls_free(void* this_arg) {\n")
257 out_c.write("\t" + struct_name + "_JCalls *arg = (" + struct_name + "_JCalls*) this_arg;\n")
258 out_c.write("\t(*arg->env)->DeleteGlobalRef(arg->env, arg->o);\n")
259 out_c.write("\tfree(arg);\n")
261 elif fn_line.group(2) == "clone":
262 out_c.write("void* " + struct_name + "_JCalls_clone(void* this_arg) {\n")
263 out_c.write("\t" + struct_name + "_JCalls *ret = malloc(sizeof(" + struct_name + "_JCalls));\n")
264 out_c.write("\tmemcpy(ret, this_arg, sizeof(" + struct_name + "_JCalls));\n")
265 out_c.write("\treturn ret;\n")
268 out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o) {\n")
269 out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
270 out_c.write("\tassert(c != NULL);\n")
271 out_c.write("\t" + struct_name + "_JCalls *calls = malloc(sizeof(" + struct_name + "_JCalls));\n")
272 out_c.write("\tcalls->env = env;\n")
273 out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
274 for fn_line in trait_fn_lines:
275 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
276 out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + "TODO" + "\");\n")
277 out_c.write("\tassert(calls->" + fn_line.group(2) + "_meth != NULL);\n")
278 out_c.write("\n\t" + struct_name + " *ret = malloc(sizeof(" + struct_name + "));\n")
279 out_c.write("\tret->this_arg = (void*) calls;\n")
280 for fn_line in trait_fn_lines:
281 if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
282 out_c.write("\tret->" + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall;\n")
283 elif fn_line.group(2) == "free":
284 out_c.write("\tret->free = " + struct_name + "_JCalls_free;\n")
286 out_c.write("\tret->clone = " + struct_name + "_JCalls_clone;\n")
287 out_c.write("\treturn (long)ret;\n")
290 #out_java.write("/* " + "\n".join(field_lines) + "*/\n")
291 cur_block_struct = None
293 if line.startswith("} "):
294 in_block_union = False
296 if line.startswith("} "):
297 in_block_enum = False
299 fn_ptr = fn_ptr_regex.match(line)
300 fn_ret_arr = fn_ret_arr_regex.match(line)
301 reg_fn = reg_fn_regex.match(line)
302 const_val = const_val_regex.match(line)
304 if line.startswith("#include <"):
306 elif line.startswith("/*"):
307 #out_java.write("\t" + line)
308 if not line.endswith("*/\n"):
309 in_block_comment = True
310 elif line.startswith("typedef enum "):
312 elif line.startswith("typedef struct "):
313 cur_block_struct = line
314 elif line.startswith("typedef union "):
315 in_block_union = True
316 elif line.startswith("typedef "):
318 elif fn_ptr is not None:
320 elif fn_ret_arr is not None:
321 map_fn(fn_ret_arr, fn_ret_arr.group(4))
322 elif reg_fn is not None:
324 elif const_val_regex is not None:
325 # TODO Map const variables
330 out_java.write("}\n")