ref-count trait objects to avoid double-free, probably will need to do this everywhere
[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     in_block_comment = False
294     in_block_enum = False
295     cur_block_struct = None
296     in_block_union = False
297
298     fn_ptr_regex = re.compile("^extern const ([A-Za-z_0-9\* ]*) \(\*(.*)\)\((.*)\);$")
299     fn_ret_arr_regex = re.compile("(.*) \(\*(.*)\((.*)\)\)\[([0-9]*)\];$")
300     reg_fn_regex = re.compile("([A-Za-z_0-9\* ]* \*?)([a-zA-Z_0-9]*)\((.*)\);$")
301     const_val_regex = re.compile("^extern const ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
302
303     line_indicates_opaque_regex = re.compile("^   bool _underlying_ref;$")
304     line_indicates_trait_regex = re.compile("^   ([A-Za-z_0-9]* \*?)\(\*([A-Za-z_0-9]*)\)\((const )?void \*this_arg(.*)\);$")
305     assert(line_indicates_trait_regex.match("   uintptr_t (*send_data)(void *this_arg, LDKu8slice data, bool resume_read);"))
306     assert(line_indicates_trait_regex.match("   LDKCVec_MessageSendEventZ (*get_and_clear_pending_msg_events)(const void *this_arg);"))
307     assert(line_indicates_trait_regex.match("   void *(*clone)(const void *this_arg);"))
308     line_field_var_regex = re.compile("^   ([A-Za-z_0-9]*) ([A-Za-z_0-9]*);$")
309     assert(line_field_var_regex.match("   LDKMessageSendEventsProvider MessageSendEventsProvider;"))
310     struct_name_regex = re.compile("^typedef struct (MUST_USE_STRUCT )?(LDK[A-Za-z_0-9]*) {$")
311     assert(struct_name_regex.match("typedef struct LDKCVecTempl_u8 {"))
312
313     for line in in_h:
314         if in_block_comment:
315             #out_java.write("\t" + line)
316             if line.endswith("*/\n"):
317                 in_block_comment = False
318         elif cur_block_struct is not None:
319             cur_block_struct  = cur_block_struct + line
320             if line.startswith("} "):
321                 field_lines = []
322                 struct_name = None
323                 struct_lines = cur_block_struct.split("\n")
324                 is_opaque = False
325                 trait_fn_lines = []
326                 field_var_lines = []
327
328                 for idx, struct_line in enumerate(struct_lines):
329                     if struct_line.strip().startswith("/*"):
330                         in_block_comment = True
331                     if in_block_comment:
332                         if struct_line.endswith("*/"):
333                             in_block_comment = False
334                     else:
335                         struct_name_match = struct_name_regex.match(struct_line)
336                         if struct_name_match is not None:
337                             struct_name = struct_name_match.group(2)
338                         if line_indicates_opaque_regex.match(struct_line):
339                             is_opaque = True
340                         trait_fn_match = line_indicates_trait_regex.match(struct_line)
341                         if trait_fn_match is not None:
342                             trait_fn_lines.append(trait_fn_match)
343                         field_var_match = line_field_var_regex.match(struct_line)
344                         if field_var_match is not None:
345                             field_var_lines.append(field_var_match)
346                         field_lines.append(struct_line)
347
348                 assert(struct_name is not None)
349                 assert(len(trait_fn_lines) == 0 or not is_opaque)
350                 if is_opaque:
351                     opaque_structs.add(struct_name)
352                 if len(trait_fn_lines) > 0:
353                     trait_structs.add(struct_name)
354                     out_c.write("typedef struct " + struct_name + "_JCalls {\n")
355                     out_c.write("\tatomic_size_t refcnt;\n")
356                     out_c.write("\tJNIEnv *env;\n")
357                     out_c.write("\tjobject o;\n")
358                     for var_line in field_var_lines:
359                         if var_line.group(1) in trait_structs:
360                             out_c.write("\t" + var_line.group(1) + "_JCalls* " + var_line.group(2) + ";\n")
361                     for fn_line in trait_fn_lines:
362                         if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
363                             out_c.write("\tjmethodID " + fn_line.group(2) + "_meth;\n")
364                     out_c.write("} " + struct_name + "_JCalls;\n")
365
366                     out_java.write("\tpublic interface " + struct_name + " {\n")
367                     java_meths = []
368                     for fn_line in trait_fn_lines:
369                         java_meth_descr = "("
370                         if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
371                             ret_ty_info = java_c_types(fn_line.group(1), None)
372
373                             out_java.write("\t\t " + ret_ty_info.java_ty + " " + fn_line.group(2) + "(")
374                             is_const = fn_line.group(3) is not None
375                             out_c.write(fn_line.group(1) + fn_line.group(2) + "_jcall(")
376                             if is_const:
377                                 out_c.write("const void* this_arg")
378                             else:
379                                 out_c.write("void* this_arg")
380
381                             arg_names = []
382                             for idx, arg in enumerate(fn_line.group(4).split(',')):
383                                 if arg == "":
384                                     continue
385                                 if idx >= 2:
386                                     out_java.write(", ")
387                                 out_c.write(", ")
388                                 arg_conv_info = map_type(arg, True, None, False)
389                                 out_c.write(arg.strip())
390                                 out_java.write(arg_conv_info.java_ty + " " + arg_conv_info.arg_name)
391                                 arg_names.append(arg_conv_info)
392                                 java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
393                             java_meth_descr = java_meth_descr + ")" + ret_ty_info.java_fn_ty_arg
394                             java_meths.append(java_meth_descr)
395
396                             out_java.write(");\n")
397                             out_c.write(") {\n")
398                             out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
399
400                             for arg_info in arg_names:
401                                 if arg_info.ret_conv is not None:
402                                     out_c.write("\t" + arg_info.ret_conv[0].replace('\n', '\n\t').replace("_env", "j_calls->env"));
403                                     out_c.write(arg_info.arg_name)
404                                     out_c.write(arg_info.ret_conv[1].replace('\n', '\n\t').replace("_env", "j_calls->env") + "\n")
405
406                             if not ret_ty_info.passed_as_ptr:
407                                 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")
408                             else:
409                                 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");
410
411                             for arg_info in arg_names:
412                                 if arg_info.ret_conv is not None:
413                                     out_c.write(", " + arg_info.ret_conv_name)
414                                 else:
415                                     out_c.write(", " + arg_info.arg_name)
416                             out_c.write(");\n");
417
418                             if ret_ty_info.passed_as_ptr:
419                                 out_c.write("\t" + fn_line.group(1).strip() + " res = *ret;\n")
420                                 out_c.write("\tfree(ret);\n")
421                                 out_c.write("\treturn res;\n")
422                             out_c.write("}\n")
423                         elif fn_line.group(2) == "free":
424                             out_c.write("void " + struct_name + "_JCalls_free(void* this_arg) {\n")
425                             out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
426                             out_c.write("\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n")
427                             out_c.write("\t\t(*j_calls->env)->DeleteGlobalRef(j_calls->env, j_calls->o);\n")
428                             out_c.write("\t\tfree(j_calls);\n")
429                             out_c.write("\t}\n}\n")
430
431                     # Write out a clone function whether we need one or not, as we use them in moving to rust
432                     out_c.write("void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n")
433                     out_c.write("\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n")
434                     out_c.write("\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n")
435                     for var_line in field_var_lines:
436                         if var_line.group(1) in trait_structs:
437                             out_c.write("\tatomic_fetch_add_explicit(&j_calls->" + var_line.group(2) + "->refcnt, 1, memory_order_release);\n")
438                     out_c.write("\treturn (void*) this_arg;\n")
439                     out_c.write("}\n")
440
441                     out_java.write("\t}\n")
442
443                     out_java.write("\tpublic static native long " + struct_name + "_new(" + struct_name + " impl")
444                     out_c.write("JNIEXPORT long JNICALL Java_org_ldk_impl_bindings_" + struct_name.replace("_", "_1") + "_1new (JNIEnv * env, jclass _a, jobject o")
445                     for var_line in field_var_lines:
446                         if var_line.group(1) in trait_structs:
447                             out_java.write(", " + var_line.group(1) + " " + var_line.group(2))
448                             out_c.write(", jobject " + var_line.group(2))
449                     out_java.write(");\n")
450                     out_c.write(") {\n")
451
452                     out_c.write("\tjclass c = (*env)->GetObjectClass(env, o);\n")
453                     out_c.write("\tassert(c != NULL);\n")
454                     out_c.write("\t" + struct_name + "_JCalls *calls = malloc(sizeof(" + struct_name + "_JCalls));\n")
455                     out_c.write("\tatomic_init(&calls->refcnt, 1);\n")
456                     out_c.write("\tcalls->env = env;\n")
457                     out_c.write("\tcalls->o = (*env)->NewGlobalRef(env, o);\n")
458                     for (fn_line, java_meth_descr) in zip(trait_fn_lines, java_meths):
459                         if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
460                             out_c.write("\tcalls->" + fn_line.group(2) + "_meth = (*env)->GetMethodID(env, c, \"" + fn_line.group(2) + "\", \"" + java_meth_descr + "\");\n")
461                             out_c.write("\tassert(calls->" + fn_line.group(2) + "_meth != NULL);\n")
462                     out_c.write("\n\t" + struct_name + " *ret = malloc(sizeof(" + struct_name + "));\n")
463                     out_c.write("\tret->this_arg = (void*) calls;\n")
464                     for fn_line in trait_fn_lines:
465                         if fn_line.group(2) != "free" and fn_line.group(2) != "clone":
466                             out_c.write("\tret->" + fn_line.group(2) + " = " + fn_line.group(2) + "_jcall;\n")
467                         elif fn_line.group(2) == "free":
468                             out_c.write("\tret->free = " + struct_name + "_JCalls_free;\n")
469                         else:
470                             out_c.write("\tret->clone = " + struct_name + "_JCalls_clone;\n")
471                     for var_line in field_var_lines:
472                         if var_line.group(1) in trait_structs:
473                             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")
474                             out_c.write("\tcalls->" + var_line.group(2) + " = ret->" + var_line.group(2) + ".this_arg;\n")
475                     out_c.write("\treturn (long)ret;\n")
476                     out_c.write("}\n\n")
477
478                     #out_java.write("/* " + "\n".join(field_lines) + "*/\n")
479                 cur_block_struct = None
480         elif in_block_union:
481             if line.startswith("} "):
482                 in_block_union = False
483         elif in_block_enum:
484             if line.startswith("} "):
485                 in_block_enum = False
486         else:
487             fn_ptr = fn_ptr_regex.match(line)
488             fn_ret_arr = fn_ret_arr_regex.match(line)
489             reg_fn = reg_fn_regex.match(line)
490             const_val = const_val_regex.match(line)
491
492             if line.startswith("#include <"):
493                 pass
494             elif line.startswith("/*"):
495                 #out_java.write("\t" + line)
496                 if not line.endswith("*/\n"):
497                     in_block_comment = True
498             elif line.startswith("typedef enum "):
499                 in_block_enum = True
500             elif line.startswith("typedef struct "):
501                 cur_block_struct = line
502             elif line.startswith("typedef union "):
503                 in_block_union = True
504             elif line.startswith("typedef "):
505                 pass
506             elif fn_ptr is not None:
507                 map_fn(fn_ptr, None)
508             elif fn_ret_arr is not None:
509                 map_fn(fn_ret_arr, fn_ret_arr.group(4))
510             elif reg_fn is not None:
511                 map_fn(reg_fn, None)
512             elif const_val_regex is not None:
513                 # TODO Map const variables
514                 pass
515             else:
516                 assert(line == "\n")
517
518     out_java.write("}\n")