[TS] Slightly improve logging in TS trait calls that fail
[ldk-java] / typescript_strings.py
index 64eae1fa4de7542a57e8fbe70586c14186ade47a..59b1e40211548d566e4ef3995e75f076b7fc6501 100644 (file)
@@ -17,6 +17,7 @@ class Consts:
         self.function_ptr_counter = 0
         self.function_ptrs = {}
         self.c_type_map = dict(
+            bool = ['boolean', 'boolean', 'XXX'],
             uint8_t = ['number', 'number', 'Uint8Array'],
             uint16_t = ['number', 'number', 'Uint16Array'],
             uint32_t = ['number', 'number', 'Uint32Array'],
@@ -126,7 +127,7 @@ async function finishInitializeWasm(wasmInstance: WebAssembly.Instance) {
 }
 
 const fn_list = ["uuuuuu", "buuuuu", "bbuuuu", "bbbuuu", "bbbbuu",
-       "bbbbbb", "ubuubu", "ubuuuu", "ubbuuu", "uubuuu", "uububu"];
+       "bbbbbb", "ubuubu", "ubuuuu", "ubbuuu", "uubuuu", "uububu", "ububuu"];
 
 /* @internal */
 export async function initializeWasmFromUint8Array(wasmBinary: Uint8Array) {
@@ -166,6 +167,16 @@ export function WitnessVersionArrToBytes(inputArray: Array<WitnessVersion>): Uin
 
 
 
+/* @internal */
+export function encodeUint128 (inputVal: bigint): number {
+       if (inputVal >= 0x10000000000000000000000000000000n) throw "U128s cannot exceed 128 bits";
+       const cArrayPointer = wasm.TS_malloc(16 + 8);
+       const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
+       arrayLengthView[0] = BigInt(16);
+       const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 8, 16);
+       for (var i = 0; i < 16; i++) arrayMemoryView[i] = Number((inputVal >> BigInt(i)*8n) & 0xffn);
+       return cArrayPointer;
+}
 /* @internal */
 export function encodeUint8Array (inputArray: Uint8Array|null): number {
        if (inputArray == null) return 0;
@@ -177,6 +188,16 @@ export function encodeUint8Array (inputArray: Uint8Array|null): number {
        return cArrayPointer;
 }
 /* @internal */
+export function encodeUint16Array (inputArray: Uint16Array|Array<number>|null): number {
+       if (inputArray == null) return 0;
+       const cArrayPointer = wasm.TS_malloc((inputArray.length + 4) * 2);
+       const arrayLengthView = new BigUint64Array(wasm.memory.buffer, cArrayPointer, 1);
+       arrayLengthView[0] = BigInt(inputArray.length);
+       const arrayMemoryView = new Uint16Array(wasm.memory.buffer, cArrayPointer + 8, inputArray.length);
+       arrayMemoryView.set(inputArray);
+       return cArrayPointer;
+}
+/* @internal */
 export function encodeUint32Array (inputArray: Uint32Array|Array<number>|null): number {
        if (inputArray == null) return 0;
        const cArrayPointer = wasm.TS_malloc((inputArray.length + 2) * 4);
@@ -202,6 +223,12 @@ export function check_arr_len(arr: Uint8Array|null, len: number): Uint8Array|nul
        return arr;
 }
 
+/* @internal */
+export function check_16_arr_len(arr: Uint16Array|null, len: number): Uint16Array|null {
+       if (arr !== null && arr.length != len) { throw new Error("Expected array of length " + len + " got " + arr.length); }
+       return arr;
+}
+
 /* @internal */
 export function getArrayLength(arrayPointer: number): number {
        const arraySizeViewer = new BigUint64Array(wasm.memory.buffer, arrayPointer, 1);
@@ -210,6 +237,21 @@ export function getArrayLength(arrayPointer: number): number {
        return Number(len % (2n ** 32n));
 }
 /* @internal */
+export function decodeUint128 (arrayPointer: number, free = true): bigint {
+       const arraySize = getArrayLength(arrayPointer);
+       if (arraySize != 16) throw "Need 16 bytes for a uint128";
+       const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
+       var val = 0n;
+       for (var i = 0; i < 16; i++) {
+               val <<= 8n;
+               val |= BigInt(actualArrayViewer[i]!);
+       }
+       if (free) {
+               wasm.TS_free(arrayPointer);
+       }
+       return val;
+}
+/* @internal */
 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
        const arraySize = getArrayLength(arrayPointer);
        const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
@@ -222,15 +264,13 @@ export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array
        }
        return actualArray;
 }
-const decodeUint32Array = (arrayPointer: number, free = true) => {
+/* @internal */
+export function decodeUint16Array (arrayPointer: number, free = true): Uint16Array {
        const arraySize = getArrayLength(arrayPointer);
-       const actualArrayViewer = new Uint32Array(
-               wasm.memory.buffer, // value
-               arrayPointer + 8, // offset (ignoring length bytes)
-               arraySize // uint32 count
-       );
+       const actualArrayViewer = new Uint16Array(wasm.memory.buffer, arrayPointer + 8, arraySize);
        // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
        // will free the underlying memory when it becomes unreachable instead of copying here.
+       // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
        const actualArray = actualArrayViewer.slice(0, arraySize);
        if (free) {
                wasm.TS_free(arrayPointer);
@@ -327,8 +367,6 @@ export async function initializeWasmFromBinary(bin: Uint8Array) {
        return "<git_version_ldk_garbagecollected>";
 }"""
 
-        self.bindings_footer = ""
-
         self.common_base = """
 function freer(f: () => void) { f() }
 const finalizer = new FinalizationRegistry(freer);
@@ -619,6 +657,7 @@ _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
 DECL_ARR_TYPE(int64_t, int64_t);
 DECL_ARR_TYPE(uint64_t, uint64_t);
 DECL_ARR_TYPE(int8_t, int8_t);
+DECL_ARR_TYPE(int16_t, int16_t);
 DECL_ARR_TYPE(uint32_t, uint32_t);
 DECL_ARR_TYPE(void*, ptr);
 DECL_ARR_TYPE(char, char);
@@ -672,12 +711,14 @@ import { CommonBase, UInt5, WitnessVersion, UnqualifiedError } from './CommonBas
 import * as bindings from '../bindings.mjs'
 
 """
+        self.hu_struct_file_suffix = ""
         self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
         self.util_fn_sfx = "}"
         self.c_fn_ty_pfx = ""
         self.file_ext = ".mts"
         self.ptr_c_ty = "uint64_t"
         self.ptr_native_ty = "bigint"
+        self.u128_native_ty = "bigint"
         self.usize_c_ty = "uint32_t"
         self.usize_native_ty = "number"
         self.native_zero_ptr = "0n"
@@ -686,21 +727,29 @@ import * as bindings from '../bindings.mjs'
         self.is_arr_some_check = ("", " != 0")
         self.get_native_arr_len_call = ("", "->arr_len")
 
+    def bindings_footer(self):
+        return ""
+
     def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
         return None
     def create_native_arr_call(self, arr_len, ty_info):
         if ty_info.c_ty == "ptrArray":
-            assert ty_info.rust_obj == "LDKCVec_u5Z" or (ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"))
+            assert ty_info.rust_obj == "LDKCVec_U5Z" or (ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"))
         return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
         if ty_info.c_ty == "int8_tArray":
             return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
+        elif ty_info.c_ty == "int16_tArray":
+            return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + " * 2)")
         else:
             assert False
     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
-        if ty_info.c_ty == "int8_tArray":
+        if ty_info.c_ty == "int8_tArray" or ty_info.c_ty == "int16_tArray":
             if copy:
-                return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + "); FREE(" + arr_name + ")"
+                byte_len = arr_len
+                if ty_info.c_ty == "int16_tArray":
+                    byte_len = arr_len + " * 2"
+                return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + byte_len + "); FREE(" + arr_name + ")"
         assert not copy
         if ty_info.c_ty == "ptrArray":
             return "(void*) " + arr_name + "->elems"
@@ -721,7 +770,7 @@ import * as bindings from '../bindings.mjs'
             return "FREE(" + arr_name + ")"
 
     def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
-        if elem_ty.rust_obj == "LDKu5":
+        if elem_ty.rust_obj == "LDKU5":
             return arr_name + " != null ? bindings.uint5ArrToBytes(" + arr_name + ") : null"
         assert elem_ty.c_ty == "uint64_t" or elem_ty.c_ty.endswith("Array")
         return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
@@ -748,7 +797,7 @@ import * as bindings from '../bindings.mjs'
             return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
         elif elem_ty.c_ty == "uint64_t":
             return "bindings.getU64ArrayElem(" + arr_name + ", " + idx + ")"
-        elif elem_ty.rust_obj == "LDKu5":
+        elif elem_ty.rust_obj == "LDKU5":
             return "bindings.getU8ArrayElem(" + arr_name + ", " + idx + ")"
         else:
             assert False
@@ -757,15 +806,22 @@ import * as bindings from '../bindings.mjs'
     def cleanup_converted_native_array(self, ty_info, arr_name):
         return "bindings.freeWasmMemory(" + arr_name + ")"
 
-    def primitive_arr_from_hu(self, mapped_ty, fixed_len, arr_name):
+    def primitive_arr_from_hu(self, arr_ty, fixed_len, arr_name):
+        mapped_ty = arr_ty.subty
         inner = arr_name
+        if arr_ty.rust_obj == "LDKU128":
+            return ("bindings.encodeUint128(" + inner + ")", "")
         if fixed_len is not None:
-            assert mapped_ty.c_ty == "int8_t"
-            inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
+            if mapped_ty.c_ty == "int8_t":
+                inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
+            elif mapped_ty.c_ty == "int16_t":
+                inner = "bindings.check_16_arr_len(" + arr_name + ", " + fixed_len + ")"
         if mapped_ty.c_ty.endswith("Array"):
             return ("bindings.encodeUint32Array(" + inner + ")", "")
         elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
             return ("bindings.encodeUint8Array(" + inner + ")", "")
+        elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
+            return ("bindings.encodeUint16Array(" + inner + ")", "")
         elif mapped_ty.c_ty == "uint32_t":
             return ("bindings.encodeUint32Array(" + inner + ")", "")
         elif mapped_ty.c_ty == "int64_t" or mapped_ty.c_ty == "uint64_t":
@@ -774,9 +830,14 @@ import * as bindings from '../bindings.mjs'
             print(mapped_ty.c_ty)
             assert False
 
-    def primitive_arr_to_hu(self, mapped_ty, fixed_len, arr_name, conv_name):
-        if mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
+    def primitive_arr_to_hu(self, arr_ty, fixed_len, arr_name, conv_name):
+        mapped_ty = arr_ty.subty
+        if arr_ty.rust_obj == "LDKU128":
+            return "const " + conv_name + ": bigint = bindings.decodeUint128(" + arr_name + ");"
+        elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
             return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
+        elif mapped_ty.c_ty == "uint16_t" or mapped_ty.c_ty == "int16_t":
+            return "const " + conv_name + ": Uint16Array = bindings.decodeUint16Array(" + arr_name + ");"
         elif mapped_ty.c_ty == "uint64_t" or mapped_ty.c_ty == "int64_t":
             return "const " + conv_name + ": bigint[] = bindings.decodeUint64Array(" + arr_name + ");"
         else:
@@ -891,6 +952,8 @@ export enum {struct_name} {{
                     if isinstance(suparg, ConvInfo):
                         trait_constructor_arguments += ", " + suparg.arg_name
                     else:
+                        # Blindly assume that we can just strip the first arg to build the args for the supertrait
+                        super_constructor_statements += "\t\tconst " + first_to_lower(suparg[1]) + " = " + suparg[1] + ".new_impl(" + super_instantiator.split(", ", 1)[1] + ");\n"
                         trait_constructor_arguments += ", " + suparg[1]
 
         # BUILD INTERFACE METHODS
@@ -1075,7 +1138,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
                         out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
 
                 fn_suffix = ""
-                assert len(fn_line.args_ty) < 6
+                assert len(fn_line.args_ty) < 7
                 for arg_info in fn_line.args_ty:
                     if arg_info.c_ty == "uint64_t" or arg_info.c_ty == "int64_t":
                         fn_suffix += "b"
@@ -1119,9 +1182,9 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
         out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
         out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
         out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
-        for var in field_var_conversions:
+        for var in flattened_field_var_conversions:
             if not isinstance(var, ConvInfo):
-                out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
+                out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[2].replace(".", "->") + "->refcnt, 1, memory_order_release);\n"
         out_c = out_c + "}\n"
 
         out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
@@ -1172,7 +1235,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
         out_c = out_c + "\t};\n"
         for var in flattened_field_var_conversions:
             if not isinstance(var, ConvInfo):
-                out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
+                out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[2] + ".this_arg;\n"
         out_c = out_c + "\treturn ret;\n"
         out_c = out_c + "}\n"
 
@@ -1282,7 +1345,6 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
         return (out_java, out_java_enum, out_c)
 
     def map_opaque_struct(self, struct_name, struct_doc_comment):
-        implementations = ""
         method_header = ""
 
         hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
@@ -1304,7 +1366,7 @@ export class {struct_name.replace("LDK","")} extends CommonBase {{
 /**{extra_docs}
  * {formatted_doc_comment}
  */
-export class {hu_name} extends CommonBase {implementations}{{
+export class {hu_name} extends CommonBase {{
        /* @internal */
        public constructor(_dummy: null, ptr: bigint) {{
                {constructor_body}
@@ -1568,12 +1630,12 @@ js_invoke = function(obj_ptr: number, fn_id: number, arg1: bigint|number, arg2:
                 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
 
             bindings.write("""\t\tdefault:
-                       console.error("Got unknown function call from C!");
-                       throw new Error("Got unknown function call from C!");
+                       console.error("Got unknown function call with id " + fn_id + " from C!");
+                       throw new Error("Got unknown function call with id " + fn_id + " from C!");
        }
        if (fn == null || fn == undefined) {
-               console.error("Got function call on incorrect JS object!");
-               throw new Error("Got function call on incorrect JS object!");
+               console.error("Got function call with id " + fn_id + " on incorrect JS object: " + obj);
+               throw new Error("Got function call with id " + fn_id + " on incorrect JS object: " + obj);
        }
        const ret = fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
        if (ret === undefined || ret === null) return BigInt(0);