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