1 from bindingstypes import ConvInfo
4 def first_to_lower(string: str) -> str:
6 return first.lower() + string[1:]
14 def __init__(self, DEBUG: bool, target: Target, **kwargs):
16 self.c_type_map = dict(
17 uint8_t = ['number', 'Uint8Array'],
18 uint16_t = ['number', 'Uint16Array'],
19 uint32_t = ['number', 'Uint32Array'],
20 uint64_t = ['number'],
23 self.to_hu_conv_templates = dict(
24 ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
25 default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
28 self.bindings_header = self.wasm_import_header(target) + """
29 export class VecOrSliceDef {
30 public dataptr: number;
31 public datalen: number;
32 public stride: number;
33 public constructor(dataptr: number, datalen: number, stride: number) {
34 this.dataptr = dataptr;
35 this.datalen = datalen;
43 System.loadLibrary(\"lightningjni\");
44 init(java.lang.Enum.class, VecOrSliceDef.class);
48 static native void init(java.lang.Class c, java.lang.Class slicedef);
49 static native void init_class_cache();
51 public static native boolean deref_bool(long ptr);
52 public static native long deref_long(long ptr);
53 public static native void free_heap_ptr(long ptr);
54 public static native byte[] read_bytes(long ptr, long len);
55 public static native byte[] get_u8_slice_bytes(long slice_ptr);
56 public static native long bytes_to_u8_vec(byte[] bytes);
57 public static native long new_txpointer_copy_data(byte[] txdata);
58 public static native void txpointer_free(long ptr);
59 public static native byte[] txpointer_get_buffer(long ptr);
60 public static native long vec_slice_len(long vec);
61 public static native long new_empty_slice_vec();
66 self.common_base = """
67 export default class CommonBase {
69 ptrs_to: object[] = []; // new LinkedList(); TODO: build linked list implementation
70 protected constructor(ptr: number) { this.ptr = ptr; }
71 public _test_only_get_ptr(): number { return this.ptr; }
72 protected finalize() {
73 // TODO: finalize myself
78 self.c_file_pfx = """#include <rust_types.h>
79 #include <stdatomic.h>
80 #include <lightning.h>
82 // These should be provided...somehow...
83 void *memset(void *s, int c, size_t n);
84 void *memcpy(void *dest, const void *src, size_t n);
85 int memcmp(const void *s1, const void *s2, size_t n);
87 void __attribute__((noreturn)) abort(void);
88 void assert(scalar expression);
92 self.c_file_pfx = self.c_file_pfx + """
93 void *malloc(size_t size);
96 #define MALLOC(a, _) malloc(a)
97 #define FREE(p) if ((long)(p) > 1024) { free(p); }
98 #define DO_ASSERT(a) (void)(a)
102 self.c_file_pfx = self.c_file_pfx + """
103 // Always run a, then assert it is true:
104 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
105 // Assert a is true or do nothing
106 #define CHECK(a) DO_ASSERT(a)
108 // Running a leak check across all the allocations and frees of the JDK is a mess,
109 // so instead we implement our own naive leak checker here, relying on the -wrap
110 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
111 // and free'd in Rust or C across the generated bindings shared library.
114 typedef struct allocation {
115 struct allocation* next;
117 const char* struct_name;
119 static allocation* allocation_ll = NULL;
121 void* __real_malloc(size_t len);
122 void* __real_calloc(size_t nmemb, size_t len);
123 static void new_allocation(void* res, const char* struct_name) {
124 allocation* new_alloc = __real_malloc(sizeof(allocation));
125 new_alloc->ptr = res;
126 new_alloc->struct_name = struct_name;
127 new_alloc->next = allocation_ll;
128 allocation_ll = new_alloc;
130 static void* MALLOC(size_t len, const char* struct_name) {
131 void* res = __real_malloc(len);
132 new_allocation(res, struct_name);
135 void __real_free(void* ptr);
136 static void alloc_freed(void* ptr) {
137 allocation* p = NULL;
138 allocation* it = allocation_ll;
139 while (it->ptr != ptr) {
140 p = it; it = it->next;
142 //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
143 return; // addrsan should catch malloc-unknown and print more info than we have
146 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
147 DO_ASSERT(it->ptr == ptr);
150 static void FREE(void* ptr) {
151 if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
156 void* __wrap_malloc(size_t len) {
157 void* res = __real_malloc(len);
158 new_allocation(res, "malloc call");
161 void* __wrap_calloc(size_t nmemb, size_t len) {
162 void* res = __real_calloc(nmemb, len);
163 new_allocation(res, "calloc call");
166 void __wrap_free(void* ptr) {
167 if (ptr == NULL) return;
172 void* __real_realloc(void* ptr, size_t newlen);
173 void* __wrap_realloc(void* ptr, size_t len) {
174 if (ptr != NULL) alloc_freed(ptr);
175 void* res = __real_realloc(ptr, len);
176 new_allocation(res, "realloc call");
179 void __wrap_reallocarray(void* ptr, size_t new_sz) {
180 // Rust doesn't seem to use reallocarray currently
184 void __attribute__((destructor)) check_leaks() {
185 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
186 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
188 DO_ASSERT(allocation_ll == NULL);
191 self.c_file_pfx = self.c_file_pfx + """
192 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
193 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
194 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
195 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
197 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
199 typedef struct int64_tArray {uint32_t len;int64_t *ptr;} int64_tArray;
200 typedef struct uint32_tArray {uint32_t len;int32_t *ptr;} uint32_tArray;
201 typedef struct int8_tArray {uint32_t len;int8_t *ptr;} int8_tArray;
202 typedef struct jstring {} jstring;
204 jstring conv_owned_string(const char* _src) { jstring a; return a; }
206 typedef bool jboolean;
210 self.hu_struct_file_prefix = f"""
211 import CommonBase from './CommonBase';
212 import * as bindings from '../bindings' // TODO: figure out location
215 self.c_fn_ty_pfx = ""
216 self.c_fn_name_pfx = ""
217 self.c_fn_args_pfx = "void* ctx_TODO"
218 self.file_ext = ".ts"
219 self.ptr_c_ty = "uint32_t"
220 self.ptr_native_ty = "number" # "uint32_t"
221 self.result_c_ty = "uint32_t"
222 self.owned_str_to_c_call = ("conv_owned_string(", ")")
223 self.ptr_arr = "uint32_tArray"
224 self.get_native_arr_len_call = ("", ".len")
225 self.get_native_arr_ptr_call = ("", ".ptr")
227 def release_native_arr_ptr_call(self, arr_var, arr_ptr_var):
229 def create_native_arr_call(self, arr_len, ty_info):
230 if ty_info.c_ty == "int8_tArray":
231 return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + ", \"Native " + ty_info.c_ty + " Bytes\") }"
232 elif ty_info.c_ty == "int64_tArray":
233 return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int64_t), \"Native " + ty_info.c_ty + " Bytes\") }"
234 elif ty_info.c_ty == "uint32_tArray":
235 return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int32_t), \"Native " + ty_info.c_ty + " Bytes\") }"
237 print("Need to create arr!", ty_info.c_ty)
239 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
240 if ty_info.c_ty == "int8_tArray":
241 return ("memcpy(" + arr_name + ".ptr, ", ", " + arr_len + ")")
244 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
245 if ty_info.c_ty == "int8_tArray":
247 return "memcpy(" + dest_name + ", " + arr_name + ".ptr, " + arr_len + ")"
249 return arr_name + ".ptr"
251 return "(" + ty_info.subty.c_ty + "*) " + arr_name + ".ptr"
252 def get_native_arr_elem(self, arr_name, idxc, ty_info):
253 assert False # Only called if above is None
254 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
255 if ty_info.c_ty == "int8_tArray":
261 def wasm_import_header(self, target):
262 if target == Target.NODEJS:
264 const path = require('path').join(__dirname, 'bindings.wasm');
265 const bytes = require('fs').readFileSync(path);
267 // add all exports to dictionary and move down?
268 // use `module.exports`?
269 // imports['./bindings.js'] = require('./bindings.js');
271 const wasmModule = new WebAssembly.Module(bytes);
272 const wasmInstance = new WebAssembly.Instance(wasmModule, imports);
273 // module.exports = wasmInstance.exports;
274 const wasm = wasmInstance.exports;
278 def init_str(self, c_array_class_caches):
281 def native_c_unitary_enum_map(self, struct_name, variants):
282 out_c = "static inline " + struct_name + " " + struct_name + "_from_js(int32_t ord) {\n"
283 out_c = out_c + "\tswitch (ord) {\n"
286 out_typescript_enum_fields = ""
289 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
291 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
292 out_c = out_c + "\t}\n"
293 out_c = out_c + "\tabort();\n"
294 out_c = out_c + "}\n"
296 out_c = out_c + "static inline int32_t " + struct_name + "_to_js(" + struct_name + " val) {\n"
297 out_c = out_c + "\tswitch (val) {\n"
300 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
302 out_c = out_c + "\t\tdefault: abort();\n"
303 out_c = out_c + "\t}\n"
304 out_c = out_c + "}\n"
306 out_typescript_enum = f"""
307 export enum {struct_name} {{
308 {out_typescript_enum_fields}
312 return (out_c, out_typescript_enum, "")
314 def c_unitary_enum_to_native_call(self, ty_info):
315 return (ty_info.rust_obj + "_to_js(", ")")
316 def native_unitary_enum_to_c_call(self, ty_info):
317 return (ty_info.rust_obj + "_from_js(", ")")
319 def c_complex_enum_pass_ty(self, struct_name):
322 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
323 ret = "0 /* " + struct_name + " - " + variant + " */"
324 for param in c_params:
325 ret = ret + "; (void) " + param
328 def native_c_map_trait(self, struct_name, field_var_conversions, field_function_lines):
329 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
331 constructor_arguments = ""
332 super_instantiator = ""
333 pointer_to_adder = ""
334 impl_constructor_arguments = ""
335 for var in field_var_conversions:
336 if isinstance(var, ConvInfo):
337 constructor_arguments += f", {first_to_lower(var.arg_name)}?: {var.java_hu_ty}"
338 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
339 if var.from_hu_conv is not None:
340 super_instantiator += ", " + var.from_hu_conv[0]
341 if var.from_hu_conv[1] != "":
342 pointer_to_adder += var.from_hu_conv[1] + ";\n"
344 super_instantiator += ", " + first_to_lower(var.arg_name)
346 constructor_arguments += f", {first_to_lower(var[1])}?: bindings.{var[0]}"
347 super_instantiator += ", " + first_to_lower(var[1])
348 pointer_to_adder += "this.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
349 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}.{var[0].replace('LDK', '')}Interface"
351 # BUILD INTERFACE METHODS
352 out_java_interface = ""
353 out_interface_implementation_overrides = ""
355 for fn_line in field_function_lines:
356 java_method_descriptor = ""
357 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
358 out_java_interface += fn_line.fn_name + "("
359 out_interface_implementation_overrides += f"{fn_line.fn_name} ("
361 for idx, arg_conv_info in enumerate(fn_line.args_ty):
363 out_java_interface += ", "
364 out_interface_implementation_overrides += ", "
365 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
366 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
367 java_method_descriptor += arg_conv_info.java_fn_ty_arg
368 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n\t\t\t\t"
369 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
370 java_methods.append((fn_line.fn_name, java_method_descriptor))
372 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
374 interface_method_override_inset = "\t\t\t\t\t\t"
375 interface_implementation_inset = "\t\t\t\t\t\t\t"
376 for arg_info in fn_line.args_ty:
377 if arg_info.to_hu_conv is not None:
378 out_interface_implementation_overrides += interface_implementation_inset + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
380 if fn_line.ret_ty_info.java_ty != "void":
381 out_interface_implementation_overrides += interface_implementation_inset + fn_line.ret_ty_info.java_hu_ty + " ret = arg." + fn_line.fn_name + "("
383 out_interface_implementation_overrides += f"{interface_implementation_inset}arg." + fn_line.fn_name + "("
385 for idx, arg_info in enumerate(fn_line.args_ty):
387 out_interface_implementation_overrides += ", "
388 if arg_info.to_hu_conv_name is not None:
389 out_interface_implementation_overrides += arg_info.to_hu_conv_name
391 out_interface_implementation_overrides += arg_info.arg_name
393 out_interface_implementation_overrides += ");\n"
394 if fn_line.ret_ty_info.java_ty != "void":
395 if fn_line.ret_ty_info.from_hu_conv is not None:
396 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"
397 if fn_line.ret_ty_info.from_hu_conv[1] != "":
398 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"
399 #if fn_line.ret_ty_info.rust_obj in result_types:
400 # XXX: We need to handle this in conversion logic so that its cross-language!
401 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
402 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
403 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn result;\n"
405 out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\treturn ret;\n"
406 out_interface_implementation_overrides += f"{interface_method_override_inset}}},\n\n{interface_method_override_inset}"
408 trait_constructor_arguments = ""
409 for var in field_var_conversions:
410 if isinstance(var, ConvInfo):
411 trait_constructor_arguments += ", " + var.arg_name
413 trait_constructor_arguments += ", " + var[1] + ".new_impl(" + var[1] + "_impl).bindings_instance"
415 out_typescript_human = f"""
416 {self.hu_struct_file_prefix}
418 export class {struct_name.replace("LDK","")} extends CommonBase {{
420 bindings_instance?: bindings.{struct_name};
422 constructor(ptr?: number, arg?: bindings.{struct_name}{constructor_arguments}) {{
423 if (Number.isFinite(ptr)) {{
425 this.bindings_instance = null;
427 // TODO: private constructor instantiation
428 super(bindings.{struct_name}_new(arg{super_instantiator}));
429 this.ptrs_to.push(arg);
434 protected finalize() {{
435 if (this.ptr != 0) {{
436 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
441 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
442 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
443 let structImplementation = <bindings.{struct_name}>{{
444 // todo: in-line interface filling
445 {out_interface_implementation_overrides}
447 impl_holder.held = new {struct_name.replace("LDK", "")} (null, structImplementation{trait_constructor_arguments});
451 export interface {struct_name.replace("LDK", "")}Interface {{
455 class {struct_name}Holder {{
456 held: {struct_name.replace("LDK", "")};
460 out_typescript_bindings += "\t\texport interface " + struct_name + " {\n"
462 for fn_line in field_function_lines:
463 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
464 out_typescript_bindings += f"\t\t\t{fn_line.fn_name} ("
466 for idx, arg_conv_info in enumerate(fn_line.args_ty):
468 out_typescript_bindings = out_typescript_bindings + ", "
469 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
471 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
473 out_typescript_bindings = out_typescript_bindings + "\t\t}\n\n"
475 out_typescript_bindings += f"\t\texport function {struct_name}_new(impl: {struct_name}"
476 for var in field_var_conversions:
477 if isinstance(var, ConvInfo):
478 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
480 out_typescript_bindings += f", {var[1]}: {var[0]}"
482 out_typescript_bindings += f"""): number {{
483 throw new Error('unimplemented'); // TODO: bind to WASM
487 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
489 # Now that we've written out our java code (and created java_meths), generate C
490 out_c = "typedef struct " + struct_name + "_JCalls {\n"
491 out_c = out_c + "\tatomic_size_t refcnt;\n"
492 out_c = out_c + "\t// TODO: Object pointer 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 + "\t// TODO: Some kind of method pointer " + 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\t// TODO: do any release required for j_calls->o (refcnt-- in java, but may be redundant)\n"
511 out_c = out_c + "\t\tFREE(j_calls);\n"
512 out_c = out_c + "\t}\n}\n"
514 for idx, fn_line in enumerate(field_function_lines):
515 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
516 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
517 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_jcall("
518 if fn_line.self_is_const:
519 out_c = out_c + "const void* this_arg"
521 out_c = out_c + "void* this_arg"
523 for idx, arg in enumerate(fn_line.args_ty):
524 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
526 out_c = out_c + ") {\n"
527 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
529 for arg_info in fn_line.args_ty:
530 if arg_info.ret_conv is not None:
531 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
532 out_c = out_c + arg_info.arg_name
533 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
535 out_c = out_c + "\t//TODO: jobject obj = get object we can call against on j_calls->o\n"
536 if fn_line.ret_ty_info.c_ty.endswith("Array"):
537 out_c = out_c + "\t" + fn_line.ret_ty_info.c_ty + " arg; // TODO: Call " + fn_line.fn_name + " on j_calls with instance obj, returning an object"
538 elif fn_line.ret_ty_info.java_ty == "void":
539 out_c = out_c + "\treturn; //TODO: Call " + fn_line.fn_name + " on j_calls with instance obj"
540 elif not fn_line.ret_ty_info.passed_as_ptr:
541 out_c = out_c + "\treturn 0; //TODO: Call " + fn_line.fn_name + " on j_calls with instance obj, returning " + fn_line.ret_ty_info.java_ty
543 out_c = out_c + "\t" + fn_line.ret_ty_info.rust_obj + "* ret; // TODO: Call " + fn_line.fn_name + " on j_calls with instance obj, returning a pointer"
545 for idx, arg_info in enumerate(fn_line.args_ty):
546 if arg_info.ret_conv is not None:
547 out_c = out_c + ", " + arg_info.ret_conv_name
549 out_c = out_c + ", " + arg_info.arg_name
550 out_c = out_c + ");\n"
551 if fn_line.ret_ty_info.arg_conv is not None:
552 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"
554 out_c = out_c + "}\n"
556 # Write out a clone function whether we need one or not, as we use them in moving to rust
557 out_c = out_c + "static void* " + struct_name + "_JCalls_clone(const void* this_arg) {\n"
558 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
559 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
560 for var in field_var_conversions:
561 if not isinstance(var, ConvInfo):
562 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
563 out_c = out_c + "\treturn (void*) this_arg;\n"
564 out_c = out_c + "}\n"
566 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (" + self.c_fn_args_pfx + ", /*TODO: JS Object Reference */void* o"
567 for var in field_var_conversions:
568 if isinstance(var, ConvInfo):
569 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
571 out_c = out_c + ", /*TODO: JS Object Reference */void* " + var[1]
572 out_c = out_c + ") {\n"
574 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
575 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
576 out_c = out_c + "\t//TODO: Assign calls->o from o\n"
578 for (fn_name, java_meth_descr) in java_meths:
579 if fn_name != "free" and fn_name != "clone":
580 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
581 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
583 for var in field_var_conversions:
584 if isinstance(var, ConvInfo) and var.arg_conv is not None:
585 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
586 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
587 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
588 for fn_line in field_function_lines:
589 if fn_line.fn_name != "free" and fn_line.fn_name != "clone":
590 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_jcall,\n"
591 elif fn_line.fn_name == "free":
592 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
594 out_c = out_c + "\t\t.clone = " + struct_name + "_JCalls_clone,\n"
595 for var in field_var_conversions:
596 if isinstance(var, ConvInfo):
597 if var.arg_conv_name is not None:
598 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
599 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
601 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
602 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
604 out_c = out_c + "\t\t." + var[1] + " = " + var[0] + "_init(NULL, " + var[1] + "),\n"
605 out_c = out_c + "\t};\n"
606 for var in field_var_conversions:
607 if not isinstance(var, ConvInfo):
608 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
609 out_c = out_c + "\treturn ret;\n"
610 out_c = out_c + "}\n"
612 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 + ", /*TODO: JS Object Reference */void* o"
613 for var in field_var_conversions:
614 if isinstance(var, ConvInfo):
615 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
617 out_c = out_c + ", /*TODO: JS Object Reference */ void* " + var[1]
618 out_c = out_c + ") {\n"
619 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
620 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(NULL, o"
621 for var in field_var_conversions:
622 if isinstance(var, ConvInfo):
623 out_c = out_c + ", " + var.arg_name
625 out_c = out_c + ", " + var[1]
626 out_c = out_c + ");\n"
627 out_c = out_c + "\treturn (long)res_ptr;\n"
628 out_c = out_c + "}\n"
630 return (out_typescript_bindings, out_typescript_human, out_c)
632 def trait_struct_inc_refcnt(self, ty_info):
635 def map_complex_enum(self, struct_name, variant_list, camel_to_snake):
636 java_hu_type = struct_name.replace("LDK", "")
642 out_java_enum += (self.hu_struct_file_prefix)
643 out_java_enum += ("export default class " + java_hu_type + " extends CommonBase {\n")
644 out_java_enum += ("\tprotected constructor(_dummy: object, ptr: number) { super(ptr); }\n")
645 out_java_enum += ("\tprotected finalize() {\n")
646 out_java_enum += ("\t\tsuper.finalize();\n")
647 out_java_enum += ("\t\tif (this.ptr != 0) { bindings." + java_hu_type + "_free(this.ptr); }\n")
648 out_java_enum += ("\t}\n")
649 out_java_enum += f"\tstatic constr_from_ptr(ptr: number): {java_hu_type} {{\n"
650 out_java_enum += (f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n")
651 java_hu_subclasses = ""
653 out_java += ("\tpublic static class " + struct_name + " {\n")
654 out_java += ("\t\tprivate " + struct_name + "() {}\n")
655 for var in variant_list:
656 out_java += ("\t\texport class " + var.var_name + " extends " + struct_name + " {\n")
657 java_hu_subclasses = java_hu_subclasses + "export class " + var.var_name + " extends " + java_hu_type + " {\n"
658 out_java_enum += ("\t\tif (raw_val instanceof bindings." + struct_name + "." + var.var_name + ") {\n")
659 out_java_enum += ("\t\t\treturn new " + var.var_name + "(this.ptr, raw_val);\n")
660 init_meth_params = ""
663 for idx, field_ty in enumerate(var.fields):
664 out_java += ("\t\t\tpublic " + field_ty.java_ty + " " + field_ty.arg_name + ";\n")
665 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
666 if field_ty.to_hu_conv is not None:
667 hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
668 hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
669 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
671 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
673 init_meth_params = init_meth_params + ", "
674 init_meth_params = init_meth_params + field_ty.java_ty + " " + field_ty.arg_name
675 init_meth_body = init_meth_body + "this." + field_ty.arg_name + " = " + field_ty.arg_name + "; "
676 out_java += ("\t\t\t" + var.var_name + "(" + init_meth_params + ") { ")
677 out_java += (init_meth_body)
679 out_java += ("\t\t}\n")
680 out_java_enum += ("\t\t}\n")
681 java_hu_subclasses = java_hu_subclasses + "\tprivate constructor(ptr: number, obj: bindings." + struct_name + "." + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
682 java_hu_subclasses = java_hu_subclasses + hu_conv_body
683 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
684 out_java += ("\t\tstatic native void init();\n")
685 out_java += ("\t}\n")
686 out_java_enum += ("\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n")
687 out_java += ("\tstatic { " + struct_name + ".init(); }\n")
688 out_java += ("\tpublic static native " + struct_name + " " + struct_name + "_ref_from_ptr(long ptr);\n");
690 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")
691 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)ptr;\n")
692 out_c += ("\tswitch(obj->tag) {\n")
693 for var in variant_list:
694 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
696 for idx, field_map in enumerate(var.fields):
697 if field_map.ret_conv is not None:
698 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
699 out_c += ("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
700 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
701 c_params.append(field_map.ret_conv_name)
703 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
704 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
706 out_c += ("\t\tdefault: abort();\n")
707 out_c += ("\t}\n}\n")
708 out_java_enum += ("}\n")
709 out_java_enum += (java_hu_subclasses)
710 return (out_java, out_java_enum, out_c)
712 def map_opaque_struct(self, struct_name):
715 if struct_name.startswith("LDKLocked"):
716 implementations += "implements AutoCloseable "
722 protected finalize() {
726 out_opaque_struct_human = f"""
727 {self.hu_struct_file_prefix}
729 export default class {struct_name.replace("LDK","")} extends CommonBase {implementations}{{
730 constructor(_dummy: object, ptr: number) {{
735 if (this.ptr != 0) {{
736 bindings.{struct_name.replace("LDK","")}_free(this.ptr);
740 return out_opaque_struct_human