Test current state of things, which actually doesn't crash!
[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 class TypeInfo:
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
13         self.c_ty = c_ty
14         self.passed_as_ptr = passed_as_ptr
15         self.is_ptr = is_ptr
16         self.var_name = var_name
17         self.arr_len = arr_len
18
19 class ConvInfo:
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
32
33     def print_ty(self):
34         out_c.write(self.c_ty)
35         out_java.write(self.java_ty)
36
37     def print_name(self):
38         if self.arg_name != "":
39             out_java.write(" " + self.arg_name)
40             out_c.write(" " + self.arg_name)
41         else:
42             out_java.write(" arg")
43             out_c.write(" arg")
44
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()
47     trait_structs = set()
48
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 "):
54             fn_arg = fn_arg[13:]
55         is_const = False
56         if fn_arg.startswith("const "):
57             fn_arg = fn_arg[6:]
58             is_const = True
59
60         is_ptr = False
61         take_by_ptr = False
62         rust_obj = None
63         if fn_arg.startswith("void"):
64             java_ty = "void"
65             c_ty = "void"
66             fn_ty_arg = "V"
67             fn_arg = fn_arg[4:].strip()
68         elif fn_arg.startswith("bool"):
69             java_ty = "boolean"
70             c_ty = "jboolean"
71             fn_ty_arg = "Z"
72             fn_arg = fn_arg[4:].strip()
73         elif fn_arg.startswith("uint8_t"):
74             java_ty = "byte"
75             c_ty = "jbyte"
76             fn_ty_arg = "B"
77             fn_arg = fn_arg[7:].strip()
78         elif fn_arg.startswith("uint16_t"):
79             java_ty = "short"
80             c_ty = "jshort"
81             fn_ty_arg = "S"
82             fn_arg = fn_arg[8:].strip()
83         elif fn_arg.startswith("uint32_t"):
84             java_ty = "int"
85             c_ty = "jint"
86             fn_ty_arg = "I"
87             fn_arg = fn_arg[8:].strip()
88         elif fn_arg.startswith("uint64_t"):
89             java_ty = "long"
90             c_ty = "jlong"
91             fn_ty_arg = "J"
92             fn_arg = fn_arg[8:].strip()
93         elif is_const and fn_arg.startswith("char *"):
94             java_ty = "String"
95             c_ty = "const char*"
96             fn_ty_arg = "Ljava/lang/String;"
97             fn_arg = fn_arg[6:].strip()
98         else:
99             ma = var_ty_regex.match(fn_arg)
100             java_ty = "long"
101             c_ty = "jlong"
102             fn_ty_arg = "J"
103             fn_arg = ma.group(2).strip()
104             rust_obj = ma.group(1).strip()
105             take_by_ptr = True
106
107         if fn_arg.startswith(" *") or fn_arg.startswith("*"):
108             fn_arg = fn_arg.replace("*", "").strip()
109             is_ptr = True
110             c_ty = "jlong"
111             java_ty = "long"
112
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)
116             assert(not is_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)
124
125     def map_type(fn_arg, print_void, ret_arr_len, is_free):
126         ty_info = java_c_types(fn_arg, ret_arr_len)
127
128         if ty_info.c_ty == "void":
129             if not print_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)
132
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
137             else:
138                 arr_name = "ret"
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 + ", *",
148                     ");"),
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 + ";"
157                         if not is_free:
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)
169
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)
173                 else:
174                     assert(not is_free)
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)
179             elif ty_info.is_ptr:
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")
186             else:
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)
189         elif not print_void:
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)
197             else:
198                 assert(not is_free)
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)
201         else:
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)
214                     else:
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)
219                 else:
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)
223             else:
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)
226
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 ")
231
232         ret_info = map_type(re_match.group(1), True, ret_arr_len, False)
233         ret_info.print_ty()
234         if ret_info.ret_conv is not None:
235             ret_conv_pfx, ret_conv_sfx = ret_info.ret_conv
236
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")
239
240         arg_names = []
241         for idx, arg in enumerate(re_match.group(3).split(',')):
242             if idx != 0:
243                 out_java.write(", ")
244             if arg != "void":
245                 out_c.write(", ")
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)
251
252         out_java.write(");\n")
253         out_c.write(") {\n")
254
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");
258
259         if ret_info.ret_conv is not None:
260             out_c.write("\t" + ret_conv_pfx.replace('\n', '\n\t'));
261         else:
262             out_c.write("\treturn ");
263
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:
267                 if idx != 0:
268                     out_c.write(", ")
269                 out_c.write(info.arg_conv_name)
270         out_c.write(")")
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 + ";")
274         else:
275             out_c.write(";")
276         out_c.write("\n}\n\n")
277
278     out_java.write("""package org.ldk.impl;
279
280 public class bindings {
281         static {
282                 System.loadLibrary(\"lightningjni\");
283         }
284
285 """)
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")
292
293     # XXX: Temporarily write out a manual SecretKey_new() for testing, we should auto-gen this kind of thing
294     out_java.write("\tpublic static native long LDKSecretKey_new();\n\n") # TODO: rm me
295     out_c.write("JNIEXPORT jlong JNICALL Java_org_ldk_impl_bindings_LDKSecretKey_1new(JNIEnv * _env, jclass _b) {\n") # TODO: rm me
296     out_c.write("\tLDKSecretKey* key = (LDKSecretKey*)malloc(sizeof(LDKSecretKey));\n") # TODO: rm me
297     out_c.write("\treturn (long)key;\n") # TODO: rm me
298     out_c.write("}\n") # TODO: rm me
299
300     in_block_comment = False
301     in_block_enum = False
302     cur_block_struct = None
303     in_block_union = False
304
305     fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
306     fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
307     reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
308     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
309
310     line_indicates_opaque_regex = re.compile("^   bool _underlying_ref;$")
311     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
312     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
313     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
314     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
315     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
316     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
317     struct_name_regex = re.compile("^typedef struct (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
318     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
319
320     for line in in_h:
321         if in_block_comment:
322             #out_java.write("\t" + line)
323             if line.endswith("*/\n"):
324                 in_block_comment = False
325         elif cur_block_struct is not None:
326             cur_block_struct  = cur_block_struct + line
327             if line.startswith("} "):
328                 field_lines = []
329                 struct_name = None
330                 struct_lines = cur_block_struct.split("\n")
331                 is_opaque = False
332                 trait_fn_lines = []
333                 field_var_lines = []
334
335                 for idx, struct_line in enumerate(struct_lines):
336                     if struct_line.strip().startswith("/*"):
337                         in_block_comment = True
338                     if in_block_comment:
339                         if struct_line.endswith("*/"):
340                             in_block_comment = False
341                     else:
342                         struct_name_match = struct_name_regex.match(struct_line)
343                         if struct_name_match is not None:
344                             struct_name = struct_name_match.group(2)
345                         if line_indicates_opaque_regex.match(struct_line):
346                             is_opaque = True
347                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
348                         if trait_fn_match is not None:
349                             trait_fn_lines.append(trait_fn_match)
350                         field_var_match = line_field_var_regex.match(struct_line)
351                         if field_var_match is not None:
352                             field_var_lines.append(field_var_match)
353                         field_lines.append(struct_line)
354
355                 assert(struct_name is not None)
356                 assert(len(trait_fn_lines) == 0 or not is_opaque)
357                 if is_opaque:
358                     opaque_structs.add(struct_name)
359                 if len(trait_fn_lines) > 0:
360                     trait_structs.add(struct_name)
361                     out_c.write("typedef struct " + struct_name + "_JCalls {\n")
362                     out_c.write("\tatomic_size_t refcnt;\n")
363                     out_c.write("\tJNIEnv *env;\n")
364                     out_c.write("\tjobject o;\n")
365                     for var_line in field_var_lines:
366                         if var_line.group(1) in trait_structs:
367                             out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
368                     for fn_line in trait_fn_lines:
369                         if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
370                             out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
371                     out_c.write("} " + struct_name + "_JCalls;\n")
372
373                     out_java.write("\tpublic interface " + struct_name + " {\n")
374                     java_meths = []
375                     for fn_line in trait_fn_lines:
376                         java_meth_descr = "("
377                         if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
378                             ret_ty_info = java_c_types(fn_line.group(1), None)
379
380                             out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
381                             is_const = fn_line.group(3) is not None
382                             out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
383                             if is_const:
384                                 out_c.write("const void* this_arg")
385                             else:
386                                 out_c.write("void* this_arg")
387
388                             arg_names = []
389                             for idx, arg in enumerate(fn_line.group(4).split(',')):
390                                 if arg == "":
391                                     continue
392                                 if idx >= 2:
393                                     out_java.write(", ")
394                                 out_c.write(", ")
395                                 arg_conv_info = map_type(arg, True, None, False)
396                                 out_c.write(arg.strip())
397                                 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
398                                 arg_names.append(arg_conv_info)
399                                 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
400                             java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
401                             java_meths.append(java_meth_descr)
402
403                             out_java.write(");\n")
404                             out_c.write(") {\n")
405                             out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
406
407                             for arg_info in arg_names:
408                                 if arg_info.ret_conv is not None:
409                                     out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "j_calls->env"));
410                                     out_c.write(arg_info.arg_name)
411                                     out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "j_calls->env") + "\n")
412
413                             if not ret_ty_info.passed_as_ptr:
414                                 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")
415                             else:
416                                 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");
417
418                             for arg_info in arg_names:
419                                 if arg_info.ret_conv is not None:
420                                     out_c.write(", " + arg_info.ret_conv_name)
421                                 else:
422                                     out_c.write(", " + arg_info.arg_name)
423                             out_c.write(");\n");
424
425                             if ret_ty_info.passed_as_ptr:
426                                 out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
427                                 out_c.write("\tfree(ret);\n")
428                                 out_c.write("\treturn res;\n")
429                             out_c.write("}\n")
430                         elif fn_line.group(2) == "free":
431                             out_c.write("void " + struct_name + "_JCalls_free(void* this_arg) {\n")
432                             out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
433                             out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
434                             out_c.write("\t\t(*j_calls->env)->DeleteGlobalRef(j_calls->env, j_calls->o);\n")
435                             out_c.write("\t\tfree(j_calls);\n")
436                             out_c.write("\t}\n}\n")
437
438                     # Write out a clone function whether we need one or not, as we use them in moving to rust
439                     out_c.write("void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
440                     out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
441                     out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
442                     for var_line in field_var_lines:
443                         if var_line.group(1) in trait_structs:
444                             out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
445                     out_c.write("\treturn (void*) this_arg;\n")
446                     out_c.write("}\n")
447
448                     out_java.write("\t}\n")
449
450                     out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
451                     out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
452                     for var_line in field_var_lines:
453                         if var_line.group(1) in trait_structs:
454                             out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
455                             out_c.write(", jobject " + var_line.group(2))
456                     out_java.write(");\n")
457                     out_c.write(") {\n")
458
459                     out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
460                     out_c.write("\tassert(c != NULL);\n")
461                     out_c.write("\t" + struct_name + "_JCalls *calls = malloc(sizeof(" + struct_name + "_JCalls));\n")
462                     out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
463                     out_c.write("\tcalls->env = env;\n")
464                     out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
465                     for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
466                         if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
467                             out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
468                             out_c.write("\tassert(calls->" + fn_line.group(2) + "_meth != NULL);\n")
469                     out_c.write("\n\t" + struct_name + " *ret = malloc(sizeof(" + struct_name + "));\n")
470                     out_c.write("\tret->this_arg = (void*) calls;\n")
471                     for fn_line in trait_fn_lines:
472                         if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
473                             out_c.write("\tret->" + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall;\n")
474                         elif fn_line.group(2) == "free":
475                             out_c.write("\tret->free = " + struct_name + "_JCalls_free;\n")
476                         else:
477                             out_c.write("\tret->clone = " + struct_name + "_JCalls_clone;\n")
478                     for var_line in field_var_lines:
479                         if var_line.group(1) in trait_structs:
480                             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")
481                             out_c.write("\tcalls->" + var_line.group(2) + " = ret->" + var_line.group(2) + ".this_arg;\n")
482                     out_c.write("\treturn (long)ret;\n")
483                     out_c.write("}\n\n")
484
485                     #out_java.write("/* " + "\n".join(field_lines) + "*/\n")
486                 cur_block_struct = None
487         elif in_block_union:
488             if line.startswith("} "):
489                 in_block_union = False
490         elif in_block_enum:
491             if line.startswith("} "):
492                 in_block_enum = False
493         else:
494             fn_ptr = fn_ptr_regex.match(line)
495             fn_ret_arr = fn_ret_arr_regex.match(line)
496             reg_fn = reg_fn_regex.match(line)
497             const_val = const_val_regex.match(line)
498
499             if line.startswith("#include <"):
500                 pass
501             elif line.startswith("/*"):
502                 #out_java.write("\t" + line)
503                 if not line.endswith("*/\n"):
504                     in_block_comment = True
505             elif line.startswith("typedef enum "):
506                 in_block_enum = True
507             elif line.startswith("typedef struct "):
508                 cur_block_struct = line
509             elif line.startswith("typedef union "):
510                 in_block_union = True
511             elif line.startswith("typedef "):
512                 pass
513             elif fn_ptr is not None:
514                 map_fn(fn_ptr, None)
515             elif fn_ret_arr is not None:
516                 map_fn(fn_ret_arr, fn_ret_arr.group(4))
517             elif reg_fn is not None:
518                 map_fn(reg_fn, None)
519             elif const_val_regex is not None:
520                 # TODO Map const variables
521                 pass
522             else:
523                 assert(line == "\n")
524
525     out_java.write("}\n")