wasm-bindgen icon indicating copy to clipboard operation
wasm-bindgen copied to clipboard

Added type annotations for a few glue code functions

Open RunDevelopment opened this issue 4 months ago • 3 comments

I added type annotations to a few commonly-used JS glue code functions. This makes it a lot easier to understand the glue, because I have TS to help me out.

Those type annotations also make it easier to verify the correctness of glue. And just to prove that: TS found 2 minor bugs in the JS glue code of our tests:

Fixes moved to #4192.

  1. ~debugString (this is the JS glue code version of format!("{:?}", value)) had a bug where it checked for a regex mismatch incorrectly. This would lead to dereferencing null at runtime, which throws a TypeError.~

  2. ~_assertClass returned instance.ptr. Here's the full code of the function:~

    function _assertClass(instance, klass) {
        if (!(instance instanceof klass)) {
            throw new Error(`expected instance of ${klass.name}`);
        }
        return instance.ptr;
    }
    

    ~Returning instance.ptr is weird for 2 reasons:~

    • ~It's not used anywhere in the code. _assertClass is only used in one place and its return value is ignored.~
    • ~There is no ptr field. The author probably meant __wbg_ptr to get the internal pointer of a JS object.~

    ~So I just removed the return statement and instance.ptr.~


Aside from that, I did one additional change: I inline lTextDecoder:

// before

const lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder;

let cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true });

// after

/** @type {TextDecoder} */
let cachedTextDecoder = new (typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder)('utf-8', { ignoreBOM: true, fatal: true });

This just made typing easier, but the expression something to get used to...

RunDevelopment avatar Oct 12 '24 16:10 RunDevelopment