3c44daea0e8d996bf308069ed86bbf75629f0f24
[ldk-java] / typescript_strings.py
1 from bindingstypes import ConvInfo
2
3
4 def first_to_lower(string: str) -> str:
5     first = string[0]
6     return first.lower() + string[1:]
7
8
9 class Consts:
10     def __init__(self, DEBUG):
11         self.common_base = """
12             export default class CommonBase {
13                 ptr: number;
14                 ptrs_to: object[] = []; // new LinkedList(); TODO: build linked list implementation
15                 protected constructor(ptr: number) { this.ptr = ptr; }
16                 public _test_only_get_ptr(): number { return this.ptr; }
17                 protected finalize() {
18                     // TODO: finalize myself
19                 }
20             }
21         """
22
23         self.c_file_pfx = """#include <rust_types.h>
24 #include <stdatomic.h>
25 #include <lightning.h>
26
27 // These should be provided...somehow...
28 void *memset(void *s, int c, size_t n);
29 void *memcpy(void *dest, const void *src, size_t n);
30 int memcmp(const void *s1, const void *s2, size_t n);
31
32 void __attribute__((noreturn)) abort(void);
33 void assert(scalar expression);
34 """
35
36         if not DEBUG:
37             self.c_file_pfx = self.c_file_pfx + """
38 void *malloc(size_t size);
39 void free(void *ptr);
40
41 #define MALLOC(a, _) malloc(a)
42 #define FREE(p) if ((long)(p) > 1024) { free(p); }
43 #define DO_ASSERT(a) (void)(a)
44 #define CHECK(a)
45 """
46         else:
47             self.c_file_pfx = self.c_file_pfx + """
48 // Always run a, then assert it is true:
49 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
50 // Assert a is true or do nothing
51 #define CHECK(a) DO_ASSERT(a)
52
53 // Running a leak check across all the allocations and frees of the JDK is a mess,
54 // so instead we implement our own naive leak checker here, relying on the -wrap
55 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
56 // and free'd in Rust or C across the generated bindings shared library.
57
58 #define BT_MAX 128
59 typedef struct allocation {
60         struct allocation* next;
61         void* ptr;
62         const char* struct_name;
63 } allocation;
64 static allocation* allocation_ll = NULL;
65
66 void* __real_malloc(size_t len);
67 void* __real_calloc(size_t nmemb, size_t len);
68 static void new_allocation(void* res, const char* struct_name) {
69         allocation* new_alloc = __real_malloc(sizeof(allocation));
70         new_alloc->ptr = res;
71         new_alloc->struct_name = struct_name;
72         new_alloc->next = allocation_ll;
73         allocation_ll = new_alloc;
74 }
75 static void* MALLOC(size_t len, const char* struct_name) {
76         void* res = __real_malloc(len);
77         new_allocation(res, struct_name);
78         return res;
79 }
80 void __real_free(void* ptr);
81 static void alloc_freed(void* ptr) {
82         allocation* p = NULL;
83         allocation* it = allocation_ll;
84         while (it->ptr != ptr) {
85                 p = it; it = it->next;
86                 if (it == NULL) {
87                         //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
88                         return; // addrsan should catch malloc-unknown and print more info than we have
89                 }
90         }
91         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
92         DO_ASSERT(it->ptr == ptr);
93         __real_free(it);
94 }
95 static void FREE(void* ptr) {
96         if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
97         alloc_freed(ptr);
98         __real_free(ptr);
99 }
100
101 void* __wrap_malloc(size_t len) {
102         void* res = __real_malloc(len);
103         new_allocation(res, "malloc call");
104         return res;
105 }
106 void* __wrap_calloc(size_t nmemb, size_t len) {
107         void* res = __real_calloc(nmemb, len);
108         new_allocation(res, "calloc call");
109         return res;
110 }
111 void __wrap_free(void* ptr) {
112         if (ptr == NULL) return;
113         alloc_freed(ptr);
114         __real_free(ptr);
115 }
116
117 void* __real_realloc(void* ptr, size_t newlen);
118 void* __wrap_realloc(void* ptr, size_t len) {
119         if (ptr != NULL) alloc_freed(ptr);
120         void* res = __real_realloc(ptr, len);
121         new_allocation(res, "realloc call");
122         return res;
123 }
124 void __wrap_reallocarray(void* ptr, size_t new_sz) {
125         // Rust doesn't seem to use reallocarray currently
126         DO_ASSERT(false);
127 }
128
129 void __attribute__((destructor)) check_leaks() {
130         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
131                 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
132         }
133         DO_ASSERT(allocation_ll == NULL);
134 }
135 """
136         self.c_file_pfx = self.c_file_pfx + """
137 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
138 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
139 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
140 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
141
142 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
143
144 typedef struct int64_tArray {uint32_t len;int64_t *ptr;} int64_tArray;
145 typedef struct uint32_tArray {uint32_t len;int32_t *ptr;} uint32_tArray;
146 typedef struct int8_tArray {uint32_t len;int8_t *ptr;} int8_tArray;
147
148 typedef bool jboolean;
149
150 """
151
152         self.hu_struct_file_prefix = f"""
153 import CommonBase from './CommonBase';
154 import * as bindings from '../bindings' // TODO: figure out location
155
156 """
157         self.c_fn_ty_pfx = ""
158         self.c_fn_name_pfx = ""
159         self.c_fn_args_pfx = "void* ctx_TODO"
160         self.file_ext = ".ts"
161         self.ptr_c_ty = "uint32_t"
162         self.ptr_native_ty = "uint32_t"
163         self.result_c_ty = "uint32_t"
164         self.ptr_arr = "uint32_tArray"
165         self.get_native_arr_len_call = ("", ".len")
166         self.get_native_arr_ptr_call = ("", ".ptr")
167
168     def release_native_arr_ptr_call(self, arr_var, arr_ptr_var):
169         return None
170     def create_native_arr_call(self, arr_len, ty_info):
171         if ty_info.c_ty == "int8_tArray":
172             return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + ", \"Native " + ty_info.c_ty + " Bytes\") }"
173         elif ty_info.c_ty == "int64_tArray":
174             return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int64_t), \"Native " + ty_info.c_ty + " Bytes\") }"
175         elif ty_info.c_ty == "uint32_tArray":
176             return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int32_t), \"Native " + ty_info.c_ty + " Bytes\") }"
177         else:
178             print("Need to create arr!", ty_info.c_ty)
179             return ty_info.c_ty
180     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
181         if ty_info.c_ty == "int8_tArray":
182             return ("memcpy(" + arr_name + ".ptr, ", ", " + arr_len + ")")
183         else:
184             assert False
185     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
186         if ty_info.c_ty == "int8_tArray":
187             if copy:
188                 return "memcpy(" + dest_name + ", " + arr_name + ".ptr, " + arr_len + ")"
189             else:
190                 return arr_name + ".ptr"
191         else:
192             return "(" + ty_info.subty.c_ty + "*) " + arr_name + ".ptr"
193     def get_native_arr_elem(self, arr_name, idxc, ty_info):
194         assert False # Only called if above is None
195     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
196         if ty_info.c_ty == "int8_tArray":
197             return None
198         else:
199             return None
200
201     def init_str(self, c_array_class_caches):
202         return ""
203
204     def native_c_unitary_enum_map(self, struct_name, variants):
205         out_c = "static inline " + struct_name + " " + struct_name + "_from_js(int32_t ord) {\n"
206         out_c = out_c + "\tswitch (ord) {\n"
207         ord_v = 0
208
209         out_typescript_enum_fields = ""
210
211         for var in variants:
212             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
213             ord_v = ord_v + 1
214             out_typescript_enum_fields += f"{var},\n\t\t\t\t"
215         out_c = out_c + "\t}\n"
216         out_c = out_c + "\tabort();\n"
217         out_c = out_c + "}\n"
218
219         out_c = out_c + "static inline int32_t " + struct_name + "_to_js(" + struct_name + " val) {\n"
220         out_c = out_c + "\tswitch (val) {\n"
221         ord_v = 0
222         for var in variants:
223             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
224             ord_v = ord_v + 1
225         out_c = out_c + "\t\tdefault: abort();\n"
226         out_c = out_c + "\t}\n"
227         out_c = out_c + "}\n"
228
229         out_typescript_enum = f"""
230             export enum {struct_name} {{
231                 {out_typescript_enum_fields}
232             }}
233         """
234
235         return (out_c, out_typescript_enum, "")
236
237     def c_unitary_enum_to_native_call(self, ty_info):
238         return (ty_info.rust_obj + "_to_js(", ")")
239     def native_unitary_enum_to_c_call(self, ty_info):
240         return (ty_info.rust_obj + "_from_js(", ")")
241
242     def c_complex_enum_pass_ty(self, struct_name):
243         return "uint32_t"
244
245     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
246         ret = "0 /* " + struct_name + " - " + variant + " */"
247         for param in c_params:
248             ret = ret + "; (void) " + param
249         return ret
250
251     def native_c_map_trait(self, struct_name, field_var_conversions, field_function_lines):
252         out_java = "out_java:native_c_map_trait"
253         out_java_trait = "out_java_trait:native_c_map_trait"
254         out_c = "out_c:native_c_map_trait"
255
256
257         out_java_trait = ""
258         out_java = ""
259
260         constructor_arguments = ""
261         super_instantiator = ""
262         pointer_to_adder = ""
263         for var in field_var_conversions:
264             if isinstance(var, ConvInfo):
265                 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
266                 if var.from_hu_conv is not None:
267                     super_instantiator += ", " + var.from_hu_conv[0]
268                     if var.from_hu_conv[1] != "":
269                         pointer_to_adder += var.from_hu_conv[1] + ";\n"
270                 else:
271                     super_instantiator += ", " + first_to_lower(var.arg_name)
272             else:
273                 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
274                 super_instantiator += ", " + first_to_lower(var[1])
275                 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
276
277         out_java_trait = f"""
278             {self.hu_struct_file_prefix}
279             
280             export class {struct_name.replace("LDK","")} extends CommonBase {{
281             
282                 bindings_instance?: bindings.{struct_name};
283                 
284                 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
285                     if (Number.isFinite(ptr)) {{
286                                         super(ptr);
287                                         this.bindings_instance = null;
288                                     }} else {{
289                                         // TODO: private constructor instantiation
290                                         super(bindings.{struct_name}_new(arg{super_instantiator}));
291                                         this.ptrs_to.push(arg);
292                                         {pointer_to_adder}
293                                     }}
294                 }}
295                 
296                 protected finalize() {{
297                     if (this.ptr != 0) {{ 
298                         bindings.{struct_name.replace("LDK","")}_free(this.ptr); 
299                     }} 
300                     super.finalize();
301                 }}
302                 
303             }}
304         """
305
306
307
308         java_trait_constr = "\tprivate static class " + struct_name + "Holder { " + struct_name.replace("LDK", "") + " held; }\n"
309         java_trait_constr = java_trait_constr + "\tpublic static " + struct_name.replace("LDK", "") + " new_impl(" + struct_name.replace("LDK", "") + "Interface arg"
310         for var in field_var_conversions:
311             if isinstance(var, ConvInfo):
312                 java_trait_constr = java_trait_constr + ", " + var.java_hu_ty + " " + var.arg_name
313             else:
314                 # Ideally we'd be able to take any instance of the interface, but our C code can only represent
315                 # Java-implemented version, so we require users pass a Java implementation here :/
316                 java_trait_constr = java_trait_constr + ", " + var[0].replace("LDK", "") + "." + var[0].replace("LDK", "") + "Interface " + var[1] + "_impl"
317         java_trait_constr = java_trait_constr + ") {\n\t\tfinal " + struct_name + "Holder impl_holder = new " + struct_name + "Holder();\n"
318         java_trait_constr = java_trait_constr + "\t\timpl_holder.held = new " + struct_name.replace("LDK", "") + "(new bindings." + struct_name + "() {\n"
319         out_java_trait = out_java_trait + "\tpublic static interface " + struct_name.replace("LDK", "") + "Interface {\n"
320         out_java = out_java + "\tpublic interface " + struct_name + " {\n"
321         java_meths = []
322         for fn_line in field_function_lines:
323             java_meth_descr = "("
324             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
325                 out_java = out_java + "\t\t " + fn_line.ret_ty_info.java_ty + " " + fn_line.fn_name + "("
326                 java_trait_constr = java_trait_constr + "\t\t\t@Override public " + fn_line.ret_ty_info.java_ty + " " + fn_line.fn_name + "("
327                 out_java_trait = out_java_trait + "\t\t" + fn_line.ret_ty_info.java_hu_ty + " " + fn_line.fn_name + "("
328
329                 for idx, arg_conv_info in enumerate(fn_line.args_ty):
330                     if idx >= 1:
331                         out_java = out_java + ", "
332                         java_trait_constr = java_trait_constr + ", "
333                         out_java_trait = out_java_trait + ", "
334                     out_java = out_java + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
335                     out_java_trait = out_java_trait + arg_conv_info.java_hu_ty + " " + arg_conv_info.arg_name
336                     java_trait_constr = java_trait_constr + arg_conv_info.java_ty + " " + arg_conv_info.arg_name
337                     java_meth_descr = java_meth_descr + arg_conv_info.java_fn_ty_arg
338                 java_meth_descr = java_meth_descr + ")" + fn_line.ret_ty_info.java_fn_ty_arg
339                 java_meths.append((fn_line.fn_name, java_meth_descr))
340
341                 out_java = out_java + ");\n"
342                 out_java_trait = out_java_trait + ");\n"
343                 java_trait_constr = java_trait_constr + ") {\n"
344
345                 for arg_info in fn_line.args_ty:
346                     if arg_info.to_hu_conv is not None:
347                         java_trait_constr = java_trait_constr + "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
348
349                 if fn_line.ret_ty_info.java_ty != "void":
350                     java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
351                 else:
352                     java_trait_constr = java_trait_constr + "\t\t\t\targ." + fn_line.fn_name + "("
353
354                 for idx, arg_info in enumerate(fn_line.args_ty):
355                     if idx != 0:
356                         java_trait_constr = java_trait_constr + ", "
357                     if arg_info.to_hu_conv_name is not None:
358                         java_trait_constr = java_trait_constr + arg_info.to_hu_conv_name
359                     else:
360                         java_trait_constr = java_trait_constr + arg_info.arg_name
361
362                 java_trait_constr = java_trait_constr + ");\n"
363                 if fn_line.ret_ty_info.java_ty != "void":
364                     if fn_line.ret_ty_info.from_hu_conv is not None:
365                         java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.java_ty + " result = " + fn_line.ret_ty_info.from_hu_conv[0] + ";\n"
366                         if fn_line.ret_ty_info.from_hu_conv[1] != "":
367                             java_trait_constr = java_trait_constr + "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held") + ";\n"
368                         #if fn_line.ret_ty_info.rust_obj in result_types:
369                         # XXX: We need to handle this in conversion logic so that its cross-language!
370                         # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
371                         #    java_trait_constr = java_trait_constr + "\t\t\t\tret.ptr = 0;\n"
372                         java_trait_constr = java_trait_constr + "\t\t\t\treturn result;\n"
373                     else:
374                         java_trait_constr = java_trait_constr + "\t\t\t\treturn ret;\n"
375                 java_trait_constr = java_trait_constr + "\t\t\t}\n"
376         java_trait_constr = java_trait_constr + "\t\t}"
377         for var in field_var_conversions:
378             if isinstance(var, ConvInfo):
379                 java_trait_constr = java_trait_constr + ", " + var.arg_name
380             else:
381                 java_trait_constr = java_trait_constr + ", " + var[1] + ".new_impl(" + var[1] + "_impl).bindings_instance"
382         out_java_trait = out_java_trait + "\t}\n"
383         out_java_trait = out_java_trait + java_trait_constr + ");\n\t\treturn impl_holder.held;\n\t}\n"
384
385         out_java = out_java + "\t}\n"
386
387         out_java = out_java + "\tpublic static native long " + struct_name + "_new(" + struct_name + " impl"
388         for var in field_var_conversions:
389             if isinstance(var, ConvInfo):
390                 out_java = out_java + ", " + var.java_ty + " " + var.arg_name
391             else:
392                 out_java = out_java + ", " + var[0] + " " + var[1]
393         out_java = out_java + ");\n"
394         out_java = out_java + "\tpublic static native " + struct_name + " " + struct_name + "_get_obj_from_jcalls(long val);\n"
395
396         # Now that we've written out our java code (and created java_meths), generate C
397         out_c = "typedef struct " + struct_name + "_JCalls {\n"
398         out_c = out_c + "\tatomic_size_t refcnt;\n"
399         out_c = out_c + "\tJavaVM *vm;\n"
400         out_c = out_c + "\tjweak o;\n"
401         for var in field_var_conversions:
402             if isinstance(var, ConvInfo):
403                 # We're a regular ol' field
404                 pass
405             else:
406                 # We're a supertrait
407                 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
408         for fn in field_function_lines:
409             if fn.fn_name != "free" and fn.fn_name != "clone":
410                 out_c = out_c + "\tjmethodID " + fn.fn_name + "_meth;\n"
411         out_c = out_c + "} " + struct_name + "_JCalls;\n"
412
413         for fn_line in field_function_lines:
414             if fn_line.fn_name == "free":
415                 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
416                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
417                 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
418                 out_c = out_c + "\t\tJNIEnv *env;\n"
419                 out_c = out_c + "\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
420                 out_c = out_c + "\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n"
421                 out_c = out_c + "\t\tFREE(j_calls);\n"
422                 out_c = out_c + "\t}\n}\n"
423
424         for idx, fn_line in enumerate(field_function_lines):
425             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
426                 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
427                 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_jcall("
428                 if fn_line.self_is_const:
429                     out_c = out_c + "const void* this_arg"
430                 else:
431                     out_c = out_c + "void* this_arg"
432
433                 for idx, arg in enumerate(fn_line.args_ty):
434                     out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
435
436                 out_c = out_c + ") {\n"
437                 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
438                 out_c = out_c + "\tJNIEnv *env;\n"
439                 out_c = out_c + "\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
440
441                 for arg_info in fn_line.args_ty:
442                     if arg_info.ret_conv is not None:
443                         out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
444                         out_c = out_c + arg_info.arg_name
445                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
446
447                 out_c = out_c + "\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tCHECK(obj != NULL);\n"
448                 if fn_line.ret_ty_info.c_ty.endswith("Array"):
449                     out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " arg = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
450                 elif not fn_line.ret_ty_info.passed_as_ptr:
451                     out_c = out_c + "\treturn (*env)->Call" + fn_line.ret_ty_info.java_ty.title() + "Method(env, obj, j_calls->" + fn_line.fn_name + "_meth"
452                 else:
453                     out_c = out_c + "\t" + fn_line.ret_ty_info.rust_obj + "* ret = (" + fn_line.ret_ty_info.rust_obj + "*)(*env)->CallLongMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
454
455                 for idx, arg_info in enumerate(fn_line.args_ty):
456                     if arg_info.ret_conv is not None:
457                         out_c = out_c + ", " + arg_info.ret_conv_name
458                     else:
459                         out_c = out_c + ", " + arg_info.arg_name
460                 out_c = out_c + ");\n"
461                 if fn_line.ret_ty_info.arg_conv is not None:
462                     out_c = out_c + "\t" + fn_line.ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + fn_line.ret_ty_info.arg_conv_name + ";\n"
463
464                 out_c = out_c + "}\n"
465
466         # Write out a clone function whether we need one or not, as we use them in moving to rust
467         out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
468         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
469         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
470         for var in field_var_conversions:
471             if not isinstance(var, ConvInfo):
472                 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
473         out_c = out_c + "\treturn (void*) this_arg;\n"
474         out_c = out_c + "}\n"
475
476         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (" + self.c_fn_args_pfx + ", jobject o"
477         for var in field_var_conversions:
478             if isinstance(var, ConvInfo):
479                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
480             else:
481                 out_c = out_c + ", jobject " + var[1]
482         out_c = out_c + ") {\n"
483
484         out_c = out_c + "\tjclass c = (*env)->GetObjectClass(env, o);\n"
485         out_c = out_c + "\tCHECK(c != NULL);\n"
486         out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
487         out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
488         out_c = out_c + "\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n"
489         out_c = out_c + "\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n"
490
491         for (fn_name, java_meth_descr) in java_meths:
492             if fn_name != "free" and fn_name != "clone":
493                 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
494                 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
495
496         for var in field_var_conversions:
497             if isinstance(var, ConvInfo) and var.arg_conv is not None:
498                 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
499         out_c = out_c + "\n\t" + struct_name + " ret = {\n"
500         out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
501         for fn_line in field_function_lines:
502             if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
503                 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_jcall,\n"
504             elif fn_line.fn_name == "free":
505                 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
506             else:
507                 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
508         for var in field_var_conversions:
509             if isinstance(var, ConvInfo):
510                 if var.arg_conv_name is not None:
511                     out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
512                     out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
513                 else:
514                     out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
515                     out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
516             else:
517                 out_c = out_c + "\t\t." + var[1] + " = " + var[0] + "_init(env, clz, " + var[1] + "),\n"
518         out_c = out_c + "\t};\n"
519         for var in field_var_conversions:
520             if not isinstance(var, ConvInfo):
521                 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
522         out_c = out_c + "\treturn ret;\n"
523         out_c = out_c + "}\n"
524
525         out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1new (" + self.c_fn_args_pfx + ", jobject o"
526         for var in field_var_conversions:
527             if isinstance(var, ConvInfo):
528                 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
529             else:
530                 out_c = out_c + ", jobject " + var[1]
531         out_c = out_c + ") {\n"
532         out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
533         out_c = out_c + "\t*res_ptr = " + struct_name + "_init(env, clz, o"
534         for var in field_var_conversions:
535             if isinstance(var, ConvInfo):
536                 out_c = out_c + ", " + var.arg_name
537             else:
538                 out_c = out_c + ", " + var[1]
539         out_c = out_c + ");\n"
540         out_c = out_c + "\treturn (long)res_ptr;\n"
541         out_c = out_c + "}\n"
542
543         out_c = out_c + self.c_fn_ty_pfx + "jobject " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1get_1obj_1from_1jcalls (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " val) {\n"
544         out_c = out_c + "\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n"
545         out_c = out_c + "\tCHECK(ret != NULL);\n"
546         out_c = out_c + "\treturn ret;\n"
547         out_c = out_c + "}\n"
548
549
550         return (out_java, out_java_trait, out_c)
551
552     def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
553         java_hu_type = struct_name.replace("LDK", "")
554
555         out_java_enum = ""
556         out_java = ""
557         out_c = ""
558
559         out_java_enum += (self.hu_struct_file_prefix)
560         out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
561         out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
562         out_java_enum += ("\tprotected finalize() {\n")
563         out_java_enum += ("\t\tsuper.finalize();\n")
564         out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
565         out_java_enum += ("\t}\n")
566         out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
567         out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
568         java_hu_subclasses = ""
569
570         out_java +=  ("\tpublic static class " + struct_name + " {\n")
571         out_java +=  ("\t\tprivate " + struct_name + "() {}\n")
572         for var in variant_list:
573             out_java +=  ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
574             java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
575             out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
576             out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
577             init_meth_params = ""
578             init_meth_body = ""
579             hu_conv_body = ""
580             for idx, field_ty in enumerate(var.fields):
581                 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
582                 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
583                 if field_ty.to_hu_conv is not None:
584                     hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
585                     hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
586                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
587                 else:
588                     hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
589                 if idx > 0:
590                     init_meth_params = init_meth_params + ", "
591                 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
592                 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
593             out_java +=  ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
594             out_java +=  (init_meth_body)
595             out_java +=  ("}\n")
596             out_java += ("\t\t}\n")
597             out_java_enum += ("\t\t}\n")
598             java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
599             java_hu_subclasses = java_hu_subclasses + hu_conv_body
600             java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
601         out_java += ("\t\tstatic native void init();\n")
602         out_java += ("\t}\n")
603         out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
604         out_java += ("\tstatic { " + struct_name + ".init(); }\n")
605         out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
606
607         out_c += (self.c_fn_ty_pfx + self.c_complex_enum_pass_ty(struct_name) + " " + self.c_fn_name_pfx + struct_name.replace("_", "_1") + "_1ref_1from_1ptr (" + self.c_fn_args_pfx + ", " + self.ptr_c_ty + " ptr) {\n")
608         out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
609         out_c += ("\tswitch(obj->tag) {\n")
610         for var in variant_list:
611             out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
612             c_params = []
613             for idx, field_map in enumerate(var.fields):
614                 if field_map.ret_conv is not None:
615                     out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
616                     out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
617                     out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
618                     c_params.append(field_map.ret_conv_name)
619                 else:
620                     c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
621             out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
622             out_c += ("\t\t}\n")
623         out_c += ("\t\tdefault: abort();\n")
624         out_c += ("\t}\n}\n")
625         out_java_enum += ("}\n")
626         out_java_enum += (java_hu_subclasses)
627         return (out_java, out_java_enum, out_c)