Starting to look like something that might work...
[ldk-java] / genbindings.py
1 #!/usr/bin/env python3
2 import sys, re
3
4 if len(sys.argv) != 4:
5     print("USAGE: /path/to/lightning.h /path/to/bindings/output.java /path/to/bindings/output.c")
6     sys.exit(1)
7
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:
9     opaque_structs = set()
10
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 "):
16             fn_arg = fn_arg[13:]
17         if fn_arg.startswith("const "):
18             fn_arg = fn_arg[6:]
19
20         c_ty = None
21         is_ptr_to_obj = None
22         if fn_arg.startswith("void"):
23             if print_void:
24                 out_java.write("void")
25                 c_ty = "void"
26             else:
27                 return (None, None, None)
28             fn_arg = fn_arg.strip("void ")
29         elif fn_arg.startswith("bool"):
30             out_java.write("boolean")
31             c_ty = "jboolean"
32             fn_arg = fn_arg.strip("bool ")
33         elif fn_arg.startswith("uint8_t"):
34             out_java.write("byte")
35             c_ty = "jbyte"
36             fn_arg = fn_arg.strip("uint8_t ")
37         elif fn_arg.startswith("uint32_t"):
38             out_java.write("int")
39             c_ty = "jint"
40             fn_arg = fn_arg.strip("uint32_t ")
41         elif fn_arg.startswith("uint64_t"):
42             out_java.write("long")
43             c_ty = "jlong"
44             fn_arg = fn_arg.strip("uint64_t ")
45         else:
46             ma = var_ty_regex.match(fn_arg)
47             out_java.write("long")
48             out_c.write("jlong")
49             is_ptr_to_obj = ma.group(1)
50             fn_arg = ma.group(2)
51         if c_ty is not None:
52             out_c.write(c_ty)
53
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:
57             out_java.write("[] ")
58             out_c.write("Array ")
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)
63                 out_c.write(arr_name)
64             else:
65                 arr_name = "ret"
66                 arr_len = ret_arr_len
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;"),
74                 arr_name + "_ref")
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:
80                 if no_ptr == fn_arg:
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")
86                 else:
87                     assert(not is_free)
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())
92             else:
93                 return (None, "XXX4", no_ptr.strip())
94         elif not print_void:
95             # We don't have a parameter name, and want one, just call it arg
96             out_java.write(" arg")
97             out_c.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")
101             else:
102                 assert(not is_free)
103                 return (None, "XXX6", "arg")
104         else:
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:
107                 if no_ptr == fn_arg:
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)
114                     else:
115                         return (None, (is_ptr_to_obj + "* ret = malloc(sizeof(" + is_ptr_to_obj + "));\n*ret = ", ";\nreturn (long)ret;"), None)
116                 else:
117                     return (None, ("return (long) ", ";"), None)
118             else:
119                 return (None, None, None)
120
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 ")
125
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
129
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")
132
133         arg_names = []
134         for idx, arg in enumerate(re_match.group(3).split(',')):
135             if idx != 0:
136                 out_java.write(", ")
137             if arg != "void":
138                 out_c.write(", ")
139             arg_names.append(map_type(arg, False, None, re_match.group(2).endswith("_free")))
140
141         out_java.write(");\n")
142         out_c.write(") {\n")
143
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");
147
148         if ret_conv is not None:
149             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
150         else:
151             out_c.write("\treturn ");
152
153         out_c.write(re_match.group(2) + "(")
154         for idx, (_, _, arg) in enumerate(arg_names):
155             if arg is not None:
156                 if idx != 0:
157                     out_c.write(", ")
158                 out_c.write(arg)
159         out_c.write(")")
160         if ret_conv is not None:
161             out_c.write(ret_conv_sfx.replace('\n', '\n\t'))
162         else:
163             out_c.write(";")
164         out_c.write("\n}\n\n")
165
166     out_java.write("""package org.ldk.impl;
167
168 public class bindings {
169         static {
170                 System.loadLibrary(\"lightningjni\");
171         }
172
173 """)
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")
179
180     in_block_comment = False
181     in_block_enum = False
182     cur_block_struct = None
183     in_block_union = False
184
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]*);$")
189
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 {"))
197
198     for line in in_h:
199         if in_block_comment:
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("} "):
206                 field_lines = []
207                 struct_name = None
208                 struct_lines = cur_block_struct.split("\n")
209                 is_opaque = False
210                 trait_fn_lines = []
211
212                 for idx, struct_line in enumerate(struct_lines):
213                     if struct_line.strip().startswith("/*"):
214                         in_block_comment = True
215                     if in_block_comment:
216                         if struct_line.endswith("*/"):
217                             in_block_comment = False
218                     else:
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):
223                             is_opaque = True
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)
228
229                 assert(struct_name is not None)
230                 assert(len(trait_fn_lines) == 0 or not is_opaque)
231                 if 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")
240
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")
248
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");
254                             out_c.write("}\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")
260                             out_c.write("}\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")
266                             out_c.write("}\n")
267
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")
285                         else:
286                             out_c.write("\tret->clone = " + struct_name + "_JCalls_clone;\n")
287                     out_c.write("\treturn (long)ret;\n")
288                     out_c.write("}\n\n")
289
290                     #out_java.write("/* " + "\n".join(field_lines) + "*/\n")
291                 cur_block_struct = None
292         elif in_block_union:
293             if line.startswith("} "):
294                 in_block_union = False
295         elif in_block_enum:
296             if line.startswith("} "):
297                 in_block_enum = False
298         else:
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)
303
304             if line.startswith("#include <"):
305                 pass
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 "):
311                 in_block_enum = True
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 "):
317                 pass
318             elif fn_ptr is not None:
319                 map_fn(fn_ptr, 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:
323                 map_fn(reg_fn, None)
324             elif const_val_regex is not None:
325                 # TODO Map const variables
326                 pass
327             else:
328                 assert(line == "\n")
329
330     out_java.write("}\n")