1 from bindingstypes import ConvInfo
4 def first_to_lower(string: str) -> str:
6 return first.lower() + string[1:]
10 def __init__(self, DEBUG):
12 self.c_type_map = dict(
13 uint8_t = ['number', 'Uint8Array'],
14 uint16_t = ['number', 'Uint16Array'],
15 uint32_t = ['number', 'Uint32Array'],
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});',
24 self.bindings_header = """
26 const path = require('path').join(__dirname, 'bindings.wasm');
27 const bytes = require('fs').readFileSync(path);
29 // add all exports to dictionary and move down?
30 // use `module.exports`?
31 // imports['./bindings.js'] = require('./bindings.js');
33 const wasmModule = new WebAssembly.Module(bytes);
34 const wasmInstance = new WebAssembly.Instance(wasmModule, imports);
35 // module.exports = wasmInstance.exports;
36 const wasm = wasmInstance.exports;
38 export class VecOrSliceDef {
39 public dataptr: number;
40 public datalen: number;
41 public stride: number;
42 public constructor(dataptr: number, datalen: number, stride: number) {
43 this.dataptr = dataptr;
44 this.datalen = datalen;
52 System.loadLibrary(\"lightningjni\");
53 init(java.lang.Enum.class, VecOrSliceDef.class);
57 static native void init(java.lang.Class c, java.lang.Class slicedef);
58 static native void init_class_cache();
60 public static native boolean deref_bool(long ptr);
61 public static native long deref_long(long ptr);
62 public static native void free_heap_ptr(long ptr);
63 public static native byte[] read_bytes(long ptr, long len);
64 public static native byte[] get_u8_slice_bytes(long slice_ptr);
65 public static native long bytes_to_u8_vec(byte[] bytes);
66 public static native long new_txpointer_copy_data(byte[] txdata);
67 public static native void txpointer_free(long ptr);
68 public static native byte[] txpointer_get_buffer(long ptr);
69 public static native long vec_slice_len(long vec);
70 public static native long new_empty_slice_vec();
75 self.common_base = """
76 export default class CommonBase {
78 ptrs_to: object[] = []; // new LinkedList(); TODO: build linked list implementation
79 protected constructor(ptr: number) { this.ptr = ptr; }
80 public _test_only_get_ptr(): number { return this.ptr; }
81 protected finalize() {
82 // TODO: finalize myself
87 self.c_file_pfx = """#include <rust_types.h>
88 #include <stdatomic.h>
89 #include <lightning.h>
91 // These should be provided...somehow...
92 void *memset(void *s, int c, size_t n);
93 void *memcpy(void *dest, const void *src, size_t n);
94 int memcmp(const void *s1, const void *s2, size_t n);
96 void __attribute__((noreturn)) abort(void);
97 void assert(scalar expression);
101 self.c_file_pfx = self.c_file_pfx + """
102 void *malloc(size_t size);
103 void free(void *ptr);
105 #define MALLOC(a, _) malloc(a)
106 #define FREE(p) if ((long)(p) > 1024) { free(p); }
107 #define DO_ASSERT(a) (void)(a)
111 self.c_file_pfx = self.c_file_pfx + """
112 // Always run a, then assert it is true:
113 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
114 // Assert a is true or do nothing
115 #define CHECK(a) DO_ASSERT(a)
117 // Running a leak check across all the allocations and frees of the JDK is a mess,
118 // so instead we implement our own naive leak checker here, relying on the -wrap
119 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
120 // and free'd in Rust or C across the generated bindings shared library.
123 typedef struct allocation {
124 struct allocation* next;
126 const char* struct_name;
128 static allocation* allocation_ll = NULL;
130 void* __real_malloc(size_t len);
131 void* __real_calloc(size_t nmemb, size_t len);
132 static void new_allocation(void* res, const char* struct_name) {
133 allocation* new_alloc = __real_malloc(sizeof(allocation));
134 new_alloc->ptr = res;
135 new_alloc->struct_name = struct_name;
136 new_alloc->next = allocation_ll;
137 allocation_ll = new_alloc;
139 static void* MALLOC(size_t len, const char* struct_name) {
140 void* res = __real_malloc(len);
141 new_allocation(res, struct_name);
144 void __real_free(void* ptr);
145 static void alloc_freed(void* ptr) {
146 allocation* p = NULL;
147 allocation* it = allocation_ll;
148 while (it->ptr != ptr) {
149 p = it; it = it->next;
151 //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
152 return; // addrsan should catch malloc-unknown and print more info than we have
155 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
156 DO_ASSERT(it->ptr == ptr);
159 static void FREE(void* ptr) {
160 if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
165 void* __wrap_malloc(size_t len) {
166 void* res = __real_malloc(len);
167 new_allocation(res, "malloc call");
170 void* __wrap_calloc(size_t nmemb, size_t len) {
171 void* res = __real_calloc(nmemb, len);
172 new_allocation(res, "calloc call");
175 void __wrap_free(void* ptr) {
176 if (ptr == NULL) return;
181 void* __real_realloc(void* ptr, size_t newlen);
182 void* __wrap_realloc(void* ptr, size_t len) {
183 if (ptr != NULL) alloc_freed(ptr);
184 void* res = __real_realloc(ptr, len);
185 new_allocation(res, "realloc call");
188 void __wrap_reallocarray(void* ptr, size_t new_sz) {
189 // Rust doesn't seem to use reallocarray currently
193 void __attribute__((destructor)) check_leaks() {
194 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
195 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
197 DO_ASSERT(allocation_ll == NULL);
200 self.c_file_pfx = self.c_file_pfx + """
201 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
202 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
203 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
204 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
206 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
208 typedef struct int64_tArray {uint32_t len;int64_t *ptr;} int64_tArray;
209 typedef struct uint32_tArray {uint32_t len;int32_t *ptr;} uint32_tArray;
210 typedef struct int8_tArray {uint32_t len;int8_t *ptr;} int8_tArray;
212 typedef bool jboolean;
216 self.hu_struct_file_prefix = f"""
217 import CommonBase from './CommonBase';
218 import * as bindings from '../bindings' // TODO: figure out location
221 self.c_fn_ty_pfx = ""
222 self.c_fn_name_pfx = ""
223 self.c_fn_args_pfx = "void* ctx_TODO"
224 self.file_ext = ".ts"
225 self.ptr_c_ty = "uint32_t"
226 self.ptr_native_ty = "uint32_t"
227 self.result_c_ty = "uint32_t"
228 self.ptr_arr = "uint32_tArray"
229 self.get_native_arr_len_call = ("", ".len")
230 self.get_native_arr_ptr_call = ("", ".ptr")
232 def release_native_arr_ptr_call(self, arr_var, arr_ptr_var):
234 def create_native_arr_call(self, arr_len, ty_info):
235 if ty_info.c_ty == "int8_tArray":
236 return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + ", \"Native " + ty_info.c_ty + " Bytes\") }"
237 elif ty_info.c_ty == "int64_tArray":
238 return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int64_t), \"Native " + ty_info.c_ty + " Bytes\") }"
239 elif ty_info.c_ty == "uint32_tArray":
240 return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int32_t), \"Native " + ty_info.c_ty + " Bytes\") }"
242 print("Need to create arr!", ty_info.c_ty)
244 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
245 if ty_info.c_ty == "int8_tArray":
246 return ("memcpy(" + arr_name + ".ptr, ", ", " + arr_len + ")")
249 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
250 if ty_info.c_ty == "int8_tArray":
252 return "memcpy(" + dest_name + ", " + arr_name + ".ptr, " + arr_len + ")"
254 return arr_name + ".ptr"
256 return "(" + ty_info.subty.c_ty + "*) " + arr_name + ".ptr"
257 def get_native_arr_elem(self, arr_name, idxc, ty_info):
258 assert False # Only called if above is None
259 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
260 if ty_info.c_ty == "int8_tArray":
265 def init_str(self, c_array_class_caches):
268 def native_c_unitary_enum_map(self, struct_name, variants):
269 out_c = "static inline " + struct_name + " " + struct_name + "_from_js(int32_t ord) {\n"
270 out_c = out_c + "\tswitch (ord) {\n"
273 out_typescript_enum_fields = ""
276 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
278 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
279 out_c = out_c + "\t}\n"
280 out_c = out_c + "\tabort();\n"
281 out_c = out_c + "}\n"
283 out_c = out_c + "static inline int32_t " + struct_name + "_to_js(" + struct_name + " val) {\n"
284 out_c = out_c + "\tswitch (val) {\n"
287 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
289 out_c = out_c + "\t\tdefault: abort();\n"
290 out_c = out_c + "\t}\n"
291 out_c = out_c + "}\n"
293 out_typescript_enum = f"""
294 export enum {struct_name} {{
295 {out_typescript_enum_fields}
299 return (out_c, out_typescript_enum, "")
301 def c_unitary_enum_to_native_call(self, ty_info):
302 return (ty_info.rust_obj + "_to_js(", ")")
303 def native_unitary_enum_to_c_call(self, ty_info):
304 return (ty_info.rust_obj + "_from_js(", ")")
306 def c_complex_enum_pass_ty(self, struct_name):
309 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
310 ret = "0 /* " + struct_name + " - " + variant + " */"
311 for param in c_params:
312 ret = ret + "; (void) " + param
315 def native_c_map_trait(self, struct_name, field_var_conversions, field_function_lines):
316 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
318 constructor_arguments = ""
319 super_instantiator = ""
320 pointer_to_adder = ""
321 impl_constructor_arguments = ""
322 for var in field_var_conversions:
323 if isinstance(var, ConvInfo):
324 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
325 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
326 if var.from_hu_conv is not None:
327 super_instantiator += ", " + var.from_hu_conv[0]
328 if var.from_hu_conv[1] != "":
329 pointer_to_adder += var.from_hu_conv[1] + ";\n"
331 super_instantiator += ", " + first_to_lower(var.arg_name)
333 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
334 super_instantiator += ", " + first_to_lower(var[1])
335 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
336 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
338 # BUILD INTERFACE METHODS
339 out_java_interface = ""
340 out_interface_implementation_overrides = ""
342 for fn_line in field_function_lines:
343 java_method_descriptor = ""
344 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
345 out_java_interface += fn_line.fn_name + "("
346 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
348 for idx, arg_conv_info in enumerate(fn_line.args_ty):
350 out_java_interface += ", "
351 out_interface_implementation_overrides += ", "
352 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
353 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
354 java_method_descriptor += arg_conv_info.java_fn_ty_arg
355 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
356 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
357 java_methods.append((fn_line.fn_name, java_method_descriptor))
359 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
361 interface_method_override_inset = "\t\t\t\t\t\t"
362 interface_implementation_inset = "\t\t\t\t\t\t\t"
363 for arg_info in fn_line.args_ty:
364 if arg_info.to_hu_conv is not None:
365 out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
367 if fn_line.ret_ty_info.java_ty != "void":
368 out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
370 out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
372 for idx, arg_info in enumerate(fn_line.args_ty):
374 out_interface_implementation_overrides += ", "
375 if arg_info.to_hu_conv_name is not None:
376 out_interface_implementation_overrides += arg_info.to_hu_conv_name
378 out_interface_implementation_overrides += arg_info.arg_name
380 out_interface_implementation_overrides += ");\n"
381 if fn_line.ret_ty_info.java_ty != "void":
382 if fn_line.ret_ty_info.from_hu_conv is not None:
383 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"
384 if fn_line.ret_ty_info.from_hu_conv[1] != "":
385 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"
386 #if fn_line.ret_ty_info.rust_obj in result_types:
387 # XXX: We need to handle this in conversion logic so that its cross-language!
388 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
389 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
390 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
392 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
393 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
395 trait_constructor_arguments = ""
396 for var in field_var_conversions:
397 if isinstance(var, ConvInfo):
398 trait_constructor_arguments += ", " + var.arg_name
400 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl).bindings_instance"
404 out_typescript_human = f"""
405 {self.hu_struct_file_prefix}
407 export class {struct_name.replace("LDK","")} extends CommonBase {{
409 bindings_instance?: bindings.{struct_name};
411 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
412 if (Number.isFinite(ptr)) {{
414 this.bindings_instance = null;
416 // TODO: private constructor instantiation
417 super(bindings.{struct_name}_new(arg{super_instantiator}));
418 this.ptrs_to.push(arg);
423 protected finalize() {{
424 if (this.ptr != 0) {{
425 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
430 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
431 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
432 let structImplementation = <bindings.{struct_name}>{{
434 // todo: in-line interface filling
436 {out_interface_implementation_overrides}
438 impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
443 export interface {struct_name.replace("LDK", "")}Interface {{
447 class {struct_name}Holder {{
448 held: {struct_name.replace("LDK", "")};
455 out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
457 for fn_line in field_function_lines:
458 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
459 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
461 for idx, arg_conv_info in enumerate(fn_line.args_ty):
463 out_typescript_bindings = out_typescript_bindings + ", "
464 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
466 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
468 out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
470 out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
471 for var in field_var_conversions:
472 if isinstance(var, ConvInfo):
473 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
475 out_typescript_bindings += f", {var[1]}: {var[0]}"
477 out_typescript_bindings += f"""): number {{
478 throw new Error('unimplemented'); // TODO: bind to WASM
481 export function {struct_name}_get_obj_from_jcalls(val: number): {struct_name} {{
482 throw new Error('unimplemented'); // TODO: bind to WASM
486 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
488 # Now that we've written out our java code (and created java_meths), generate C
489 out_c = "typedef struct " + struct_name + "_JCalls {\n"
490 out_c = out_c + "\tatomic_size_t refcnt;\n"
491 out_c = out_c + "\tJavaVM *vm;\n"
492 out_c = out_c + "\tjweak o;\n"
493 for var in field_var_conversions:
494 if isinstance(var, ConvInfo):
495 # We're a regular ol' field
499 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
500 for fn in field_function_lines:
501 if fn.fn_name != "free" and fn.fn_name != "clone":
502 out_c = out_c + "\tjmethodID " + fn.fn_name + "_meth;\n"
503 out_c = out_c + "} " + struct_name + "_JCalls;\n"
505 for fn_line in field_function_lines:
506 if fn_line.fn_name == "free":
507 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
508 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
509 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
510 out_c = out_c + "\t\tJNIEnv *env;\n"
511 out_c = out_c + "\t\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
512 out_c = out_c + "\t\t(*env)->DeleteWeakGlobalRef(env, j_calls->o);\n"
513 out_c = out_c + "\t\tFREE(j_calls);\n"
514 out_c = out_c + "\t}\n}\n"
516 for idx, fn_line in enumerate(field_function_lines):
517 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
518 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
519 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_jcall("
520 if fn_line.self_is_const:
521 out_c = out_c + "const void* this_arg"
523 out_c = out_c + "void* this_arg"
525 for idx, arg in enumerate(fn_line.args_ty):
526 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
528 out_c = out_c + ") {\n"
529 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
530 out_c = out_c + "\tJNIEnv *env;\n"
531 out_c = out_c + "\tDO_ASSERT((*j_calls->vm)->GetEnv(j_calls->vm, (void**)&env, JNI_VERSION_1_8) == JNI_OK);\n"
533 for arg_info in fn_line.args_ty:
534 if arg_info.ret_conv is not None:
535 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
536 out_c = out_c + arg_info.arg_name
537 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
539 out_c = out_c + "\tjobject obj = (*env)->NewLocalRef(env, j_calls->o);\n\tCHECK(obj != NULL);\n"
540 if fn_line.ret_ty_info.c_ty.endswith("Array"):
541 out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " arg = (*env)->CallObjectMethod(env, obj, j_calls->" + fn_line.fn_name + "_meth"
542 elif not fn_line.ret_ty_info.passed_as_ptr:
543 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"
545 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"
547 for idx, arg_info in enumerate(fn_line.args_ty):
548 if arg_info.ret_conv is not None:
549 out_c = out_c + ", " + arg_info.ret_conv_name
551 out_c = out_c + ", " + arg_info.arg_name
552 out_c = out_c + ");\n"
553 if fn_line.ret_ty_info.arg_conv is not None:
554 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"
556 out_c = out_c + "}\n"
558 # Write out a clone function whether we need one or not, as we use them in moving to rust
559 out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
560 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
561 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
562 for var in field_var_conversions:
563 if not isinstance(var, ConvInfo):
564 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
565 out_c = out_c + "\treturn (void*) this_arg;\n"
566 out_c = out_c + "}\n"
568 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (" + self.c_fn_args_pfx + ", jobject o"
569 for var in field_var_conversions:
570 if isinstance(var, ConvInfo):
571 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
573 out_c = out_c + ", jobject " + var[1]
574 out_c = out_c + ") {\n"
576 out_c = out_c + "\tjclass c = (*env)->GetObjectClass(env, o);\n"
577 out_c = out_c + "\tCHECK(c != NULL);\n"
578 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
579 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
580 out_c = out_c + "\tDO_ASSERT((*env)->GetJavaVM(env, &calls->vm) == 0);\n"
581 out_c = out_c + "\tcalls->o = (*env)->NewWeakGlobalRef(env, o);\n"
583 for (fn_name, java_meth_descr) in java_meths:
584 if fn_name != "free" and fn_name != "clone":
585 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
586 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
588 for var in field_var_conversions:
589 if isinstance(var, ConvInfo) and var.arg_conv is not None:
590 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
591 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
592 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
593 for fn_line in field_function_lines:
594 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
595 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_jcall,\n"
596 elif fn_line.fn_name == "free":
597 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
599 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
600 for var in field_var_conversions:
601 if isinstance(var, ConvInfo):
602 if var.arg_conv_name is not None:
603 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
604 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
606 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
607 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
609 out_c = out_c + "\t\t." + var[1] + " = " + var[0] + "_init(env, clz, " + var[1] + "),\n"
610 out_c = out_c + "\t};\n"
611 for var in field_var_conversions:
612 if not isinstance(var, ConvInfo):
613 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
614 out_c = out_c + "\treturn ret;\n"
615 out_c = out_c + "}\n"
617 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"
618 for var in field_var_conversions:
619 if isinstance(var, ConvInfo):
620 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
622 out_c = out_c + ", jobject " + var[1]
623 out_c = out_c + ") {\n"
624 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
625 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(env, clz, o"
626 for var in field_var_conversions:
627 if isinstance(var, ConvInfo):
628 out_c = out_c + ", " + var.arg_name
630 out_c = out_c + ", " + var[1]
631 out_c = out_c + ");\n"
632 out_c = out_c + "\treturn (long)res_ptr;\n"
633 out_c = out_c + "}\n"
635 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"
636 out_c = out_c + "\tjobject ret = (*env)->NewLocalRef(env, ((" + struct_name + "_JCalls*)val)->o);\n"
637 out_c = out_c + "\tCHECK(ret != NULL);\n"
638 out_c = out_c + "\treturn ret;\n"
639 out_c = out_c + "}\n"
642 return (out_typescript_bindings, out_typescript_human, out_c)
644 def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
645 java_hu_type = struct_name.replace("LDK", "")
651 out_java_enum += (self.hu_struct_file_prefix)
652 out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
653 out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
654 out_java_enum += ("\tprotected finalize() {\n")
655 out_java_enum += ("\t\tsuper.finalize();\n")
656 out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
657 out_java_enum += ("\t}\n")
658 out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
659 out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
660 java_hu_subclasses = ""
662 out_java += ("\tpublic static class " + struct_name + " {\n")
663 out_java += ("\t\tprivate " + struct_name + "() {}\n")
664 for var in variant_list:
665 out_java += ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
666 java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
667 out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
668 out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
669 init_meth_params = ""
672 for idx, field_ty in enumerate(var.fields):
673 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
674 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
675 if field_ty.to_hu_conv is not None:
676 hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
677 hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
678 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
680 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
682 init_meth_params = init_meth_params + ", "
683 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
684 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
685 out_java += ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
686 out_java += (init_meth_body)
688 out_java += ("\t\t}\n")
689 out_java_enum += ("\t\t}\n")
690 java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
691 java_hu_subclasses = java_hu_subclasses + hu_conv_body
692 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
693 out_java += ("\t\tstatic native void init();\n")
694 out_java += ("\t}\n")
695 out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
696 out_java += ("\tstatic { " + struct_name + ".init(); }\n")
697 out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
699 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")
700 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
701 out_c += ("\tswitch(obj->tag) {\n")
702 for var in variant_list:
703 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
705 for idx, field_map in enumerate(var.fields):
706 if field_map.ret_conv is not None:
707 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
708 out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
709 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
710 c_params.append(field_map.ret_conv_name)
712 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
713 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
715 out_c += ("\t\tdefault: abort();\n")
716 out_c += ("\t}\n}\n")
717 out_java_enum += ("}\n")
718 out_java_enum += (java_hu_subclasses)
719 return (out_java, out_java_enum, out_c)