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, outdir: str, **kwargs):
16 self.struct_file_suffixes = {}
17 self.function_ptr_counter = 0
18 self.function_ptrs = {}
19 self.c_type_map = dict(
20 uint8_t = ['number', 'Uint8Array'],
21 uint16_t = ['number', 'Uint16Array'],
22 uint32_t = ['number', 'Uint32Array'],
23 uint64_t = ['BigInt'],
26 self.wasm_decoding_map = dict(
27 int8_tArray = 'decodeUint8Array'
30 self.wasm_encoding_map = dict(
31 int8_tArray = 'encodeUint8Array',
34 self.to_hu_conv_templates = dict(
35 ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
36 default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
39 self.bindings_header = self.wasm_import_header(target)
41 self.bindings_version_file = ""
43 self.bindings_footer = ""
45 self.common_base = """
46 function freer(f: () => void) { f() }
47 const finalizer = new FinalizationRegistry(freer);
48 function get_freeer(ptr: number, free_fn: (ptr: number) => void) {
54 export default class CommonBase {
55 protected ptr: number;
56 protected ptrs_to: object[] = [];
57 protected constructor(ptr: number, free_fn: (ptr: number) => void) {
59 if (Number.isFinite(ptr) && ptr != 0){
60 finalizer.register(this, get_freeer(ptr, free_fn));
63 // In Java, protected means "any subclass can access fields on any other subclass'"
64 // In TypeScript, protected means "any subclass can access parent fields on instances of itself"
65 // To work around this, we add accessors for other instances' protected fields here.
66 protected static add_ref_from(holder: CommonBase, referent: object) {
67 holder.ptrs_to.push(referent);
69 protected static get_ptr_of(o: CommonBase) {
72 protected static set_null_skip_free(o: CommonBase) {
74 finalizer.unregister(o);
79 self.txout_defn = """export class TxOut extends CommonBase {
80 /** The script_pubkey in this output */
81 public script_pubkey: Uint8Array;
82 /** The value, in satoshis, of this output */
86 public constructor(_dummy: object, ptr: number) {
87 super(ptr, bindings.TxOut_free);
88 this.script_pubkey = bindings.TxOut_get_script_pubkey(ptr);
89 this.value = bindings.TxOut_get_value(ptr);
91 public constructor_new(value: BigInt, script_pubkey: Uint8Array): TxOut {
92 return new TxOut(null, bindings.TxOut_new(script_pubkey, value));
95 self.obj_defined(["TxOut"], "structs")
97 self.c_file_pfx = """#include "js-wasm.h"
98 #include <stdatomic.h>
99 #include <lightning.h>
101 // These should be provided...somehow...
102 void *memset(void *s, int c, size_t n);
103 void *memcpy(void *dest, const void *src, size_t n);
104 int memcmp(const void *s1, const void *s2, size_t n);
106 extern void __attribute__((noreturn)) abort(void);
107 static inline void assert(bool expression) {
108 if (!expression) { abort(); }
111 uint32_t __attribute__((export_name("test_bigint_pass_deadbeef0badf00d"))) test_bigint_pass_deadbeef0badf00d(uint64_t val) {
112 return val == 0xdeadbeef0badf00dULL;
118 self.c_file_pfx = self.c_file_pfx + """
119 void *malloc(size_t size);
120 void free(void *ptr);
122 #define MALLOC(a, _) malloc(a)
123 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
124 #define DO_ASSERT(a) (void)(a)
126 #define CHECK_ACCESS(p)
127 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
130 self.c_file_pfx = self.c_file_pfx + """
131 // Always run a, then assert it is true:
132 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
133 // Assert a is true or do nothing
134 #define CHECK(a) DO_ASSERT(a)
136 // Running a leak check across all the allocations and frees of the JDK is a mess,
137 // so instead we implement our own naive leak checker here, relying on the -wrap
138 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
139 // and free'd in Rust or C across the generated bindings shared library.
142 typedef struct allocation {
143 struct allocation* next;
145 const char* struct_name;
147 static allocation* allocation_ll = NULL;
149 void* __real_malloc(size_t len);
150 void* __real_calloc(size_t nmemb, size_t len);
151 static void new_allocation(void* res, const char* struct_name) {
152 allocation* new_alloc = __real_malloc(sizeof(allocation));
153 new_alloc->ptr = res;
154 new_alloc->struct_name = struct_name;
155 new_alloc->next = allocation_ll;
156 allocation_ll = new_alloc;
158 static void* MALLOC(size_t len, const char* struct_name) {
159 void* res = __real_malloc(len);
160 new_allocation(res, struct_name);
163 void __real_free(void* ptr);
164 static void alloc_freed(void* ptr) {
165 allocation* p = NULL;
166 allocation* it = allocation_ll;
167 while (it->ptr != ptr) {
168 p = it; it = it->next;
170 //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
171 return; // addrsan should catch malloc-unknown and print more info than we have
174 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
175 DO_ASSERT(it->ptr == ptr);
178 static void FREE(void* ptr) {
179 if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
184 static void CHECK_ACCESS(const void* ptr) {
185 allocation* it = allocation_ll;
186 while (it->ptr != ptr) {
189 return; // addrsan should catch malloc-unknown and print more info than we have
193 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
194 if (v.is_owned && v.inner != NULL) { \\
195 const void *p = __unmangle_inner_ptr(v.inner); \\
201 void* __wrap_malloc(size_t len) {
202 void* res = __real_malloc(len);
203 new_allocation(res, "malloc call");
206 void* __wrap_calloc(size_t nmemb, size_t len) {
207 void* res = __real_calloc(nmemb, len);
208 new_allocation(res, "calloc call");
211 void __wrap_free(void* ptr) {
212 if (ptr == NULL) return;
217 void* __real_realloc(void* ptr, size_t newlen);
218 void* __wrap_realloc(void* ptr, size_t len) {
219 if (ptr != NULL) alloc_freed(ptr);
220 void* res = __real_realloc(ptr, len);
221 new_allocation(res, "realloc call");
224 void __wrap_reallocarray(void* ptr, size_t new_sz) {
225 // Rust doesn't seem to use reallocarray currently
229 void __attribute__((destructor)) check_leaks() {
230 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
231 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
233 DO_ASSERT(allocation_ll == NULL);
236 self.c_file_pfx = self.c_file_pfx + """
237 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
238 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
239 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
240 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
242 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
244 #define DECL_ARR_TYPE(ty, name) \\
245 struct name##array { \\
249 typedef struct name##array * name##Array; \\
250 static inline name##Array init_##name##Array(size_t arr_len) { \\
251 name##Array arr = (name##Array)MALLOC(arr_len * sizeof(ty) + sizeof(uint32_t), "##name array init"); \\
252 arr->arr_len = arr_len; \\
256 DECL_ARR_TYPE(int64_t, int64_t);
257 DECL_ARR_TYPE(int8_t, int8_t);
258 DECL_ARR_TYPE(uint32_t, uint32_t);
259 DECL_ARR_TYPE(void*, ptr);
260 DECL_ARR_TYPE(char, char);
261 typedef charArray jstring;
263 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
264 charArray arr = init_charArray(len);
265 memcpy(arr->elems, chars, len);
268 static inline LDKStr str_ref_to_owned_c(const jstring str) {
269 char* newchars = MALLOC(str->arr_len + 1, "String chars");
270 memcpy(newchars, str->elems, str->arr_len);
271 newchars[str->arr_len] = 0;
275 .chars_is_owned = true
280 typedef bool jboolean;
282 uint32_t __attribute__((export_name("TS_malloc"))) TS_malloc(uint32_t size) {
283 return (uint32_t)MALLOC(size, "JS-Called malloc");
285 void __attribute__((export_name("TS_free"))) TS_free(uint32_t ptr) {
290 self.c_version_file = ""
292 self.hu_struct_file_prefix = """
293 import CommonBase from './CommonBase.mjs';
294 import * as bindings from '../bindings.mjs'
295 import * as InternalUtils from '../InternalUtils.mjs'
298 self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
299 self.util_fn_sfx = "}"
300 self.c_fn_ty_pfx = ""
301 self.file_ext = ".mts"
302 self.ptr_c_ty = "uint32_t"
303 self.ptr_native_ty = "number"
304 self.result_c_ty = "uint32_t"
305 self.ptr_arr = "ptrArray"
306 self.is_arr_some_check = ("", " != 0")
307 self.get_native_arr_len_call = ("", "->arr_len")
309 with open(outdir + "/InternalUtils.mts", "w") as f:
310 f.write("export function check_arr_len(arr: Uint8Array, len: number): Uint8Array {\n")
311 f.write("\tif (arr.length != len) { throw new Error(\"Expected array of length \" + len + \"got \" + arr.length); }\n")
312 f.write("\treturn arr;\n")
315 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
317 def create_native_arr_call(self, arr_len, ty_info):
318 if ty_info.c_ty == "ptrArray":
319 assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
320 return "init_" + ty_info.c_ty + "(" + arr_len + ")"
321 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
322 if ty_info.c_ty == "int8_tArray":
323 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
326 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
327 if ty_info.c_ty == "int8_tArray":
329 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + ")"
330 if ty_info.c_ty == "ptrArray":
331 return "(void*) " + arr_name + "->elems"
334 return arr_name + "->elems"
335 def get_native_arr_elem(self, arr_name, idxc, ty_info):
336 assert False # Only called if above is None
337 def get_native_arr_ptr_call(self, ty_info):
338 if ty_info.subty is not None:
339 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 4)"
340 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 4)"
341 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
343 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
344 if ty_info.c_ty == "int8_tArray":
349 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
350 return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
352 def str_ref_to_native_call(self, var_name, str_len):
353 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
354 def str_ref_to_c_call(self, var_name):
355 return "str_ref_to_owned_c(" + var_name + ")"
357 def c_fn_name_define_pfx(self, fn_name, have_args):
358 return " __attribute__((export_name(\"TS_" + fn_name + "\"))) TS_" + fn_name + "("
360 def wasm_import_header(self, target):
362 const imports: any = {};
365 var js_objs: Array<WeakRef<object>> = [];
366 var js_invoke: Function;
368 imports.wasi_snapshot_preview1 = {
370 console.log("ABORT");
372 "random_get" : () => {
373 console.log("RAND GET");
375 "environ_sizes_get" : () => {
376 console.log("wasi_snapshot_preview1:environ_sizes_get");
378 "proc_exit" : () => {
379 console.log("wasi_snapshot_preview1:proc_exit");
381 "environ_get" : () => {
382 console.log("wasi_snapshot_preview1:environ_get");
386 var wasm: any = null;
387 let isWasmInitialized: boolean = false;
390 if target == Target.NODEJS:
391 res += """import * as fs from 'fs';
392 export async function initializeWasm(path: string) {
393 const source = fs.readFileSync(path);
394 imports.env["js_invoke_function"] = js_invoke;
395 const { instance: wasmInstance } = await WebAssembly.instantiate(source, imports);
396 wasm = wasmInstance.exports;
397 if (!wasm.test_bigint_pass_deadbeef0badf00d(BigInt("0xdeadbeef0badf00d"))) {
398 throw new Error(\"Currently need BigInt-as-u64 support, try ----experimental-wasm-bigint");
400 isWasmInitialized = true;
405 export async function initializeWasm(uri: string) {
406 const stream = fetch(uri);
407 imports.env["js_invoke_function"] = js_invoke;
408 const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);
409 wasm = wasmInstance.exports;
410 if (!wasm.test_bigint_pass_deadbeef0badf00d(BigInt("0xdeadbeef0badf00d"))) {
411 throw new Error(\"Currently need BigInt-as-u64 support, try ----experimental-wasm-bigint");
413 isWasmInitialized = true;
423 const nextMultipleOfFour = (value: number) => {
424 return Math.ceil(value / 4) * 4;
427 const encodeUint8Array = (inputArray: Uint8Array) => {
428 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
429 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
430 arrayLengthView[0] = inputArray.length;
431 const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
432 arrayMemoryView.set(inputArray);
433 return cArrayPointer;
436 const encodeUint32Array = (inputArray: Uint32Array) => {
437 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
438 const arrayMemoryView = new Uint32Array(wasm.memory.buffer, cArrayPointer, inputArray.length);
439 arrayMemoryView.set(inputArray, 1);
440 arrayMemoryView[0] = inputArray.length;
441 return cArrayPointer;
444 const getArrayLength = (arrayPointer: number) => {
445 const arraySizeViewer = new Uint32Array(
446 wasm.memory.buffer, // value
447 arrayPointer, // offset
450 return arraySizeViewer[0];
452 const decodeUint8Array = (arrayPointer: number, free = true) => {
453 const arraySize = getArrayLength(arrayPointer);
454 const actualArrayViewer = new Uint8Array(
455 wasm.memory.buffer, // value
456 arrayPointer + 4, // offset (ignoring length bytes)
457 arraySize // uint8 count
459 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
460 // will free the underlying memory when it becomes unreachable instead of copying here.
461 const actualArray = actualArrayViewer.slice(0, arraySize);
463 wasm.TS_free(arrayPointer);
467 const decodeUint32Array = (arrayPointer: number, free = true) => {
468 const arraySize = getArrayLength(arrayPointer);
469 const actualArrayViewer = new Uint32Array(
470 wasm.memory.buffer, // value
471 arrayPointer + 4, // offset (ignoring length bytes)
472 arraySize // uint32 count
474 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
475 // will free the underlying memory when it becomes unreachable instead of copying here.
476 const actualArray = actualArrayViewer.slice(0, arraySize);
478 wasm.TS_free(arrayPointer);
483 const encodeString = (string: string) => {
484 // make malloc count divisible by 4
485 const memoryNeed = nextMultipleOfFour(string.length + 1);
486 const stringPointer = wasm.TS_malloc(memoryNeed);
487 const stringMemoryView = new Uint8Array(
488 wasm.memory.buffer, // value
489 stringPointer, // offset
490 string.length + 1 // length
492 for (let i = 0; i < string.length; i++) {
493 stringMemoryView[i] = string.charCodeAt(i);
495 stringMemoryView[string.length] = 0;
496 return stringPointer;
499 const decodeString = (stringPointer: number, free = true) => {
500 const memoryView = new Uint8Array(wasm.memory.buffer, stringPointer);
504 while (memoryView[cursor] !== 0) {
505 result += String.fromCharCode(memoryView[cursor]);
510 wasm.wasm_free(stringPointer);
520 def constr_hu_array(self, ty_info, arr_len):
521 return "new Array(" + arr_len + ").fill(null)"
523 def var_decl_statement(self, ty_string, var_name, statement):
524 return "const " + var_name + ": " + ty_string + " = " + statement
526 def for_n_in_range(self, n, minimum, maximum):
527 return "for (var " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
528 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
529 return (arr_name + ".forEach((" + n + ": " + arr_elem_ty.java_hu_ty + ") => { ", " })")
531 def get_ptr(self, var):
532 return "CommonBase.get_ptr_of(" + var + ")"
533 def set_null_skip_free(self, var):
534 return "CommonBase.set_null_skip_free(" + var + ");"
536 def add_ref(self, holder, referent):
537 return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
539 def obj_defined(self, struct_names, folder):
540 with open(self.outdir + "/index.mts", 'a') as index:
541 index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
542 with open(self.outdir + "/imports.mts.part", 'a') as imports:
543 imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
545 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
546 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
547 out_c = out_c + "\tswitch (ord) {\n"
550 out_typescript_enum_fields = ""
552 for var, var_docs in variants:
553 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
555 if var_docs is not None:
556 out_typescript_enum_fields += f"/**\n * {var_docs}\n */\n"
557 out_typescript_enum_fields += f"{var},\n\t\t\t\t"
558 out_c = out_c + "\t}\n"
559 out_c = out_c + "\tabort();\n"
560 out_c = out_c + "}\n"
562 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
563 out_c = out_c + "\tswitch (val) {\n"
565 for var, _ in variants:
566 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
568 out_c = out_c + "\t\tdefault: abort();\n"
569 out_c = out_c + "\t}\n"
570 out_c = out_c + "}\n"
572 out_typescript = f"""
573 export enum {struct_name} {{
574 {out_typescript_enum_fields}
577 out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
578 self.obj_defined([struct_name], "enums")
579 return (out_c, out_typescript_enum, out_typescript)
581 def c_unitary_enum_to_native_call(self, ty_info):
582 return (ty_info.rust_obj + "_to_js(", ")")
583 def native_unitary_enum_to_c_call(self, ty_info):
584 return (ty_info.rust_obj + "_from_js(", ")")
586 def c_complex_enum_pass_ty(self, struct_name):
589 def c_constr_native_complex_enum(self, struct_name, variant, c_params):
590 ret = "0 /* " + struct_name + " - " + variant + " */"
591 for param in c_params:
592 ret = ret + "; (void) " + param
595 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
596 out_typescript_bindings = "\n\n\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: START\n\n"
598 super_instantiator = ""
599 bindings_instantiator = ""
600 pointer_to_adder = ""
601 impl_constructor_arguments = ""
602 for var in flattened_field_var_conversions:
603 if isinstance(var, ConvInfo):
604 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
605 super_instantiator += first_to_lower(var.arg_name) + ", "
606 if var.from_hu_conv is not None:
607 bindings_instantiator += ", " + var.from_hu_conv[0]
608 if var.from_hu_conv[1] != "":
609 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
611 bindings_instantiator += ", " + first_to_lower(var.arg_name)
613 bindings_instantiator += ", " + first_to_lower(var[1]) + ".bindings_instance"
614 super_instantiator += first_to_lower(var[1]) + "_impl, "
615 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
616 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
618 super_constructor_statements = ""
619 trait_constructor_arguments = ""
620 for var in field_var_conversions:
621 if isinstance(var, ConvInfo):
622 trait_constructor_arguments += ", " + var.arg_name
624 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
625 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".bindings_instance"
626 for suparg in var[2]:
627 if isinstance(suparg, ConvInfo):
628 trait_constructor_arguments += ", " + suparg.arg_name
630 trait_constructor_arguments += ", " + suparg[1]
632 # BUILD INTERFACE METHODS
633 out_java_interface = ""
634 out_interface_implementation_overrides = ""
636 for fn_line in field_function_lines:
637 java_method_descriptor = ""
638 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
639 out_java_interface += "\t" + fn_line.fn_name + "("
640 out_interface_implementation_overrides += f"\t\t\t{fn_line.fn_name} ("
642 for idx, arg_conv_info in enumerate(fn_line.args_ty):
644 out_java_interface += ", "
645 out_interface_implementation_overrides += ", "
646 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
647 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
648 java_method_descriptor += arg_conv_info.java_fn_ty_arg
649 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n"
650 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
651 java_methods.append((fn_line.fn_name, java_method_descriptor))
653 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
655 for arg_info in fn_line.args_ty:
656 if arg_info.to_hu_conv is not None:
657 out_interface_implementation_overrides += "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
659 if fn_line.ret_ty_info.java_ty != "void":
660 out_interface_implementation_overrides += "\t\t\t\tconst ret: " + fn_line.ret_ty_info.java_hu_ty + " = arg." + fn_line.fn_name + "("
662 out_interface_implementation_overrides += f"\t\t\t\targ." + fn_line.fn_name + "("
664 for idx, arg_info in enumerate(fn_line.args_ty):
666 out_interface_implementation_overrides += ", "
667 if arg_info.to_hu_conv_name is not None:
668 out_interface_implementation_overrides += arg_info.to_hu_conv_name
670 out_interface_implementation_overrides += arg_info.arg_name
672 out_interface_implementation_overrides += ");\n"
673 if fn_line.ret_ty_info.java_ty != "void":
674 if fn_line.ret_ty_info.from_hu_conv is not None:
675 out_interface_implementation_overrides += "\t\t\t\t" + f"const result: {fn_line.ret_ty_info.java_ty} = " + fn_line.ret_ty_info.from_hu_conv[0].replace("\n", "\n\t\t\t\t") + ";\n"
676 if fn_line.ret_ty_info.from_hu_conv[1] != "":
677 out_interface_implementation_overrides += "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held").replace("\n", "\n\t\t\t\t") + ";\n"
678 #if fn_line.ret_ty_info.rust_obj in result_types:
679 # XXX: We need to handle this in conversion logic so that its cross-language!
680 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
681 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
682 out_interface_implementation_overrides += "\t\t\t\treturn result;\n"
684 out_interface_implementation_overrides += "\t\t\t\treturn ret;\n"
685 out_interface_implementation_overrides += f"\t\t\t}},\n"
687 out_typescript_human = f"""
688 {self.hu_struct_file_prefix}
690 export interface {struct_name.replace("LDK", "")}Interface {{
691 {out_java_interface}}}
693 class {struct_name}Holder {{
694 held: {struct_name.replace("LDK", "")};
697 export class {struct_name.replace("LDK","")} extends CommonBase {{
699 public bindings_instance?: bindings.{struct_name};
702 constructor(_dummy: object, ptr: number) {{
703 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
704 this.bindings_instance = null;
707 static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
708 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
709 let structImplementation = {{
710 {out_interface_implementation_overrides} }} as bindings.{struct_name};
711 {super_constructor_statements} const ptr: number = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
713 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr);
714 impl_holder.held.bindings_instance = structImplementation;
715 {pointer_to_adder} return impl_holder.held;
718 self.obj_defined([struct_name.replace("LDK", ""), struct_name.replace("LDK", "") + "Interface"], "structs")
720 out_typescript_bindings += "export interface " + struct_name + " {\n"
722 for fn_line in field_function_lines:
723 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
724 out_typescript_bindings += f"\t{fn_line.fn_name} ("
726 for idx, arg_conv_info in enumerate(fn_line.args_ty):
728 out_typescript_bindings = out_typescript_bindings + ", "
729 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
731 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
733 out_typescript_bindings += "}\n\n"
735 out_typescript_bindings += f"export function {struct_name}_new(impl: {struct_name}"
736 for var in flattened_field_var_conversions:
737 if isinstance(var, ConvInfo):
738 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
740 out_typescript_bindings += f", {var[1]}: {var[0]}"
742 out_typescript_bindings += f"""): number {{
743 if(!isWasmInitialized) {{
744 throw new Error("initializeWasm() must be awaited first!");
746 var new_obj_idx = js_objs.length;
747 for (var i = 0; i < js_objs.length; i++) {{
748 if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
750 js_objs[i] = new WeakRef(impl);
751 return wasm.TS_{struct_name}_new(i);
755 out_typescript_bindings += '\n// OUT_TYPESCRIPT_BINDINGS :: MAP_TRAIT :: END\n\n\n'
757 # Now that we've written out our java code (and created java_meths), generate C
758 out_c = "typedef struct " + struct_name + "_JCalls {\n"
759 out_c += "\tatomic_size_t refcnt;\n"
760 out_c += "\tuint32_t instance_ptr;\n"
761 for var in flattened_field_var_conversions:
762 if isinstance(var, ConvInfo):
763 # We're a regular ol' field
767 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
768 out_c = out_c + "} " + struct_name + "_JCalls;\n"
770 for fn_line in field_function_lines:
771 if fn_line.fn_name == "free":
772 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
773 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
774 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
775 out_c = out_c + "\t\tFREE(j_calls);\n"
776 out_c = out_c + "\t}\n}\n"
778 for idx, fn_line in enumerate(field_function_lines):
779 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
780 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
781 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
782 if fn_line.self_is_const:
783 out_c = out_c + "const void* this_arg"
785 out_c = out_c + "void* this_arg"
787 for idx, arg in enumerate(fn_line.args_ty):
788 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
790 out_c = out_c + ") {\n"
791 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
793 for arg_info in fn_line.args_ty:
794 if arg_info.ret_conv is not None:
795 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
796 out_c = out_c + arg_info.arg_name
797 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
799 if fn_line.ret_ty_info.c_ty.endswith("Array"):
800 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
801 out_c += "js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
802 elif fn_line.ret_ty_info.java_ty == "void":
803 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
804 elif fn_line.ret_ty_info.java_ty == "String":
805 out_c = out_c + "\tjstring ret = (jstring)js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
806 elif not fn_line.ret_ty_info.passed_as_ptr:
807 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
809 out_c = out_c + "\tuint32_t ret = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
811 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
812 self.function_ptr_counter += 1
814 for idx, arg_info in enumerate(fn_line.args_ty):
815 if arg_info.ret_conv is not None:
816 out_c = out_c + ", (uint32_t)" + arg_info.ret_conv_name
818 out_c = out_c + ", (uint32_t)" + arg_info.arg_name
819 out_c = out_c + ");\n"
820 if fn_line.ret_ty_info.arg_conv is not None:
821 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"
823 out_c = out_c + "}\n"
825 # Write out a clone function whether we need one or not, as we use them in moving to rust
826 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
827 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
828 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
829 for var in field_var_conversions:
830 if not isinstance(var, ConvInfo):
831 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
832 out_c = out_c + "}\n"
834 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
835 for var in flattened_field_var_conversions:
836 if isinstance(var, ConvInfo):
837 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
839 out_c = out_c + ", JSValue " + var[1]
840 out_c = out_c + ") {\n"
842 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
843 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
844 out_c = out_c + "\tcalls->instance_ptr = o;\n"
846 for (fn_name, java_meth_descr) in java_meths:
847 if fn_name != "free" and fn_name != "cloned":
848 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
849 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
851 for var in flattened_field_var_conversions:
852 if isinstance(var, ConvInfo) and var.arg_conv is not None:
853 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
854 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
855 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
856 for fn_line in field_function_lines:
857 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
858 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
859 elif fn_line.fn_name == "free":
860 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
862 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
863 for var in field_var_conversions:
864 if isinstance(var, ConvInfo):
865 if var.arg_conv_name is not None:
866 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
867 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
869 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
870 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
872 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
873 for suparg in var[2]:
874 if isinstance(suparg, ConvInfo):
875 out_c += ", " + suparg.arg_name
877 out_c += ", " + suparg[1]
879 out_c = out_c + "\t};\n"
880 for var in flattened_field_var_conversions:
881 if not isinstance(var, ConvInfo):
882 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
883 out_c = out_c + "\treturn ret;\n"
884 out_c = out_c + "}\n"
886 out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "JSValue o"
887 for var in flattened_field_var_conversions:
888 if isinstance(var, ConvInfo):
889 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
891 out_c = out_c + ", JSValue " + var[1]
892 out_c = out_c + ") {\n"
893 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
894 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
895 for var in flattened_field_var_conversions:
896 if isinstance(var, ConvInfo):
897 out_c = out_c + ", " + var.arg_name
899 out_c = out_c + ", " + var[1]
900 out_c = out_c + ");\n"
901 out_c = out_c + "\treturn (long)res_ptr;\n"
902 out_c = out_c + "}\n"
904 return (out_typescript_bindings, out_typescript_human, out_c)
906 def trait_struct_inc_refcnt(self, ty_info):
909 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
910 bindings_type = struct_name.replace("LDK", "")
911 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
917 out_java_enum += (self.hu_struct_file_prefix)
920 java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
921 java_hu_class += "\tprotected constructor(_dummy: object, ptr: number) { super(ptr, bindings." + bindings_type + "_free); }\n"
922 java_hu_class += "\t/* @internal */\n"
923 java_hu_class += f"\tpublic static constr_from_ptr(ptr: number): {java_hu_type} {{\n"
924 java_hu_class += f"\t\tconst raw_val: bindings.{struct_name} = bindings." + struct_name + "_ref_from_ptr(ptr);\n"
925 java_hu_subclasses = ""
927 out_java += "export class " + struct_name + " {\n"
928 out_java += "\tprotected constructor() {}\n"
930 for var in variant_list:
931 java_subclasses += "export class " + struct_name + "_" + var.var_name + " extends " + struct_name + " {\n"
932 java_hu_subclasses = java_hu_subclasses + "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
933 java_hu_class += "\t\tif (raw_val instanceof bindings." + struct_name + "_" + var.var_name + ") {\n"
934 java_hu_class += "\t\t\treturn new " + java_hu_type + "_" + var.var_name + "(ptr, raw_val);\n"
935 init_meth_params = ""
937 for idx, (field_ty, field_docs) in enumerate(var.fields):
938 java_hu_subclasses = java_hu_subclasses + "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
939 if field_ty.to_hu_conv is not None:
940 hu_conv_body = hu_conv_body + "\t\tconst " + field_ty.arg_name + f": {field_ty.java_ty} = obj." + field_ty.arg_name + ";\n"
941 hu_conv_body = hu_conv_body + "\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
942 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
944 hu_conv_body = hu_conv_body + "\t\tthis." + field_ty.arg_name + " = obj." + field_ty.arg_name + ";\n"
946 init_meth_params += ", "
947 init_meth_params += "public " + field_ty.arg_name + ": " + field_ty.java_ty
948 java_subclasses += "\tconstructor(" + init_meth_params + ") { super(); }\n"
949 java_subclasses += "}\n"
950 java_hu_class += "\t\t}\n"
951 java_hu_subclasses += "\t/* @internal */\n"
952 java_hu_subclasses += "\tpublic constructor(ptr: number, obj: bindings." + struct_name + "_" + var.var_name + ") {\n\t\tsuper(null, ptr);\n"
953 java_hu_subclasses = java_hu_subclasses + hu_conv_body
954 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
956 out_java += java_subclasses
957 java_hu_class += "\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t}\n\n"
958 out_java += self.fn_call_body(struct_name + "_ref_from_ptr", "uint32_t", "number", "ptr: number", "ptr")
960 out_c += (self.c_fn_ty_pfx + self.c_complex_enum_pass_ty(struct_name) + self.c_fn_name_define_pfx(struct_name + "_ref_from_ptr", True) + self.ptr_c_ty + " ptr) {\n")
961 out_c += ("\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n")
962 out_c += ("\tswitch(obj->tag) {\n")
963 for var in variant_list:
964 out_c += ("\t\tcase " + struct_name + "_" + var.var_name + ": {\n")
966 for idx, (field_map, _) in enumerate(var.fields):
967 if field_map.ret_conv is not None:
968 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
969 if var.tuple_variant:
970 out_c += "obj->" + camel_to_snake(var.var_name)
972 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
973 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
974 c_params.append(field_map.ret_conv_name)
976 if var.tuple_variant:
977 c_params.append("obj->" + camel_to_snake(var.var_name))
979 c_params.append("obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name)
980 out_c += ("\t\t\treturn " + self.c_constr_native_complex_enum(struct_name, var.var_name, c_params) + ";\n")
982 out_c += ("\t\tdefault: abort();\n")
983 out_c += ("\t}\n}\n")
984 out_java_enum += java_hu_class
985 self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
986 self.obj_defined([java_hu_type], "structs")
987 return (out_java, out_java_enum, out_c)
989 def map_opaque_struct(self, struct_name, struct_doc_comment):
993 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
994 out_opaque_struct_human = f"{self.hu_struct_file_prefix}"
995 if struct_name.startswith("LDKLocked"):
996 out_opaque_struct_human += "/** XXX: DO NOT USE THIS - it remains locked until the GC runs (if that ever happens */"
997 out_opaque_struct_human += f"""
998 export class {hu_name} extends CommonBase {implementations}{{
1000 public constructor(_dummy: object, ptr: number) {{
1001 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1005 self.obj_defined([hu_name], "structs")
1006 return out_opaque_struct_human
1008 def map_tuple(self, struct_name):
1009 return self.map_opaque_struct(struct_name, "A Tuple")
1011 def map_result(self, struct_name, res_map, err_map):
1012 human_ty = struct_name.replace("LDKCResult", "Result")
1014 suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1015 if res_map.java_hu_ty != "void":
1016 suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1019 public constructor(_dummy: object, ptr: number) {{
1022 if res_map.java_hu_ty == "void":
1024 elif res_map.to_hu_conv is not None:
1025 suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1026 suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1027 suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1029 suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1030 suffixes += "\t}\n}\n"
1032 suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1033 if err_map.java_hu_ty != "void":
1034 suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1037 public constructor(_dummy: object, ptr: number) {{
1040 if err_map.java_hu_ty == "void":
1042 elif err_map.to_hu_conv is not None:
1043 suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1044 suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1045 suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1047 suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1048 suffixes += "\t}\n}"
1050 self.struct_file_suffixes[human_ty] = suffixes
1051 self.obj_defined([human_ty], "structs")
1053 return f"""{self.hu_struct_file_prefix}
1055 export class {human_ty} extends CommonBase {{
1056 protected constructor(_dummy: object, ptr: number) {{
1057 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1060 public static constr_from_ptr(ptr: number): {human_ty} {{
1061 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1062 return new {human_ty}_OK(null, ptr);
1064 return new {human_ty}_Err(null, ptr);
1069 def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1070 has_return_value = return_c_ty != 'void'
1071 needs_decoding = return_c_ty in self.wasm_decoding_map
1072 return_statement = 'return nativeResponseValue;'
1073 if not has_return_value:
1074 return_statement = '// debug statements here'
1075 elif needs_decoding:
1076 converter = self.wasm_decoding_map[return_c_ty]
1077 return_statement = f"return {converter}(nativeResponseValue);"
1079 return f"""export function {method_name}({method_argument_string}): {return_java_ty} {{
1080 if(!isWasmInitialized) {{
1081 throw new Error("initializeWasm() must be awaited first!");
1083 const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1087 def map_function(self, argument_types, c_call_string, method_name, meth_n, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
1090 out_java_struct = None
1093 out_c += (self.c_fn_ty_pfx)
1094 out_c += (return_type_info.c_ty)
1095 out_java += (return_type_info.java_ty)
1096 if return_type_info.ret_conv is not None:
1097 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1098 out_java += (" " + method_name + "(")
1099 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
1101 method_argument_string = ""
1102 native_call_argument_string = ""
1103 for idx, arg_conv_info in enumerate(argument_types):
1105 method_argument_string += (", ")
1106 native_call_argument_string += ', '
1108 if arg_conv_info.c_ty != "void":
1109 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1110 needs_encoding = arg_conv_info.c_ty in self.wasm_encoding_map
1111 native_argument = arg_conv_info.arg_name
1113 converter = self.wasm_encoding_map[arg_conv_info.c_ty]
1114 native_argument = f"{converter}({arg_conv_info.arg_name})"
1115 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1116 native_call_argument_string += native_argument
1117 out_java = self.fn_call_body(method_name, return_type_info.c_ty, return_type_info.java_ty, method_argument_string, native_call_argument_string)
1119 out_java_struct = ""
1121 out_java_struct += ("\t// Skipped " + method_name + "\n")
1124 out_java_struct += (
1125 "\tpublic static constructor_" + meth_n + "(")
1127 out_java_struct += ("\tpublic " + meth_n + "(")
1128 for idx, arg in enumerate(argument_types):
1130 if not takes_self or idx > 1:
1131 out_java_struct += (", ")
1134 if arg.java_ty != "void":
1135 if arg.arg_name in default_constructor_args:
1136 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1137 if explode_idx != 0:
1138 out_java_struct += (", ")
1139 out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1141 out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1144 if out_java_struct is not None:
1145 out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1146 for info in argument_types:
1147 if info.arg_conv is not None:
1148 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1149 if return_type_info.ret_conv is not None:
1150 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1151 elif return_type_info.c_ty != "void":
1152 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1155 if c_call_string is None:
1156 out_c += (method_name + "(")
1158 out_c += (c_call_string)
1159 for idx, info in enumerate(argument_types):
1160 if info.arg_conv_name is not None:
1163 elif c_call_string is not None:
1165 out_c += (info.arg_conv_name)
1167 if return_type_info.ret_conv is not None:
1168 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1171 for info in argument_types:
1172 if info.arg_conv_cleanup is not None:
1173 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1174 if return_type_info.ret_conv is not None:
1175 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1176 elif return_type_info.c_ty != "void":
1177 out_c += ("\n\treturn ret_val;")
1178 out_c += ("\n}\n\n")
1181 out_java_struct += ("\t\t")
1182 if return_type_info.java_ty != "void":
1183 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1184 out_java_struct += ("bindings." + method_name + "(")
1185 for idx, info in enumerate(argument_types):
1187 out_java_struct += (", ")
1188 if idx == 0 and takes_self:
1189 out_java_struct += ("this.ptr")
1190 elif info.arg_name in default_constructor_args:
1191 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1192 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1193 if explode_idx != 0:
1194 out_java_struct += (", ")
1195 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1196 if explode_arg.from_hu_conv is not None:
1197 out_java_struct += (
1198 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1200 out_java_struct += (expl_arg_name)
1201 out_java_struct += (")")
1202 elif info.from_hu_conv is not None:
1203 out_java_struct += (info.from_hu_conv[0])
1205 out_java_struct += (info.arg_name)
1206 out_java_struct += (");\n")
1207 if return_type_info.to_hu_conv is not None:
1209 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1210 return_type_info.to_hu_conv_name) + "\n")
1212 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1214 for idx, info in enumerate(argument_types):
1215 if idx == 0 and takes_self:
1217 elif info.arg_name in default_constructor_args:
1218 for explode_arg in default_constructor_args[info.arg_name]:
1219 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1220 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1221 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1222 expl_arg_name).replace(
1223 "this", return_type_info.to_hu_conv_name) + ";\n")
1224 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1225 if not takes_self and return_type_info.to_hu_conv_name is not None:
1226 out_java_struct += (
1227 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1229 out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1231 if return_type_info.to_hu_conv_name is not None:
1232 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1233 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1234 out_java_struct += ("\t\treturn ret;\n")
1235 out_java_struct += ("\t}\n\n")
1237 return (out_java, out_c, out_java_struct)
1240 for struct in self.struct_file_suffixes:
1241 with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1242 src.write(self.struct_file_suffixes[struct])
1244 with open(self.outdir + "/bindings.mts", "a") as bindings:
1247 js_invoke = function(obj_ptr: number, fn_id: number, arg1: number, arg2: number, arg3: number, arg4: number, arg5: number, arg6: number, arg7: number, arg8: number, arg9: number, arg10: number) {
1248 const weak: WeakRef<object> = js_objs[obj_ptr];
1249 if (weak == null || weak == undefined) {
1250 console.error("Got function call on unknown/free'd JS object!");
1251 throw new Error("Got function call on unknown/free'd JS object!");
1253 const obj: object = weak.deref();
1254 if (obj == null || obj == undefined) {
1255 console.error("Got function call on GC'd JS object!");
1256 throw new Error("Got function call on GC'd JS object!");
1260 bindings.write("\tswitch (fn_id) {\n")
1261 for f in self.function_ptrs:
1262 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
1264 bindings.write("""\t\tdefault:
1265 console.error("Got unknown function call from C!");
1266 throw new Error("Got unknown function call from C!");
1268 if (fn == null || fn == undefined) {
1269 console.error("Got function call on incorrect JS object!");
1270 throw new Error("Got function call on incorrect JS object!");
1272 return fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);