Skip to content

Overload function names for use in JS #4107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
devrosch opened this issue Sep 6, 2024 · 1 comment
Closed

Overload function names for use in JS #4107

devrosch opened this issue Sep 6, 2024 · 1 comment
Labels

Comments

@devrosch
Copy link

devrosch commented Sep 6, 2024

Summary

The documentation explains very well how to use polymorphic, i.e., overloaded, JavaScript functions in Rust with js_name.

Is a way to do it the other way around too and make multiple Rust functions available to JS under the same name but with different arguments?

Additional Details

Here is minimalistic example that fails to compile.

use js_sys::Uint8Array;
use wasm_bindgen::prelude::wasm_bindgen;
use web_sys::Blob;

#[wasm_bindgen(js_name = Scanner)]
pub struct JsScanner {}

#[wasm_bindgen(js_class = Scanner)]
impl JsScanner {
    #[wasm_bindgen(constructor)]
    pub fn new() -> JsScanner {
        JsScanner {}
    }

    #[wasm_bindgen(js_name = isRecognized)]
    pub fn js_is_recognized_blob(input: &Blob) -> bool {
        todo!()
    }

    #[wasm_bindgen(js_name = isRecognized)]
    pub fn js_is_recognized_uint8array(input: &Uint8Array) -> bool {
        todo!()
    }
}

The error is:

error: symbol `scanner_isRecognized` is already defined
 --> src/lib.rs:8:1
  |
8 | #[wasm_bindgen(js_class = Scanner)]
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: this error originates in the attribute macro `wasm_bindgen::prelude::__wasm_bindgen_class_marker` (in Nightly builds, run with -Z macro-backtrace for more info)

If any one of the the #[wasm_bindgen(js_name = isRecognized)] names are changed the error does not appear. For symmetry with using polymorphic JS functions, it would be very nice to have this work. This question is somewhat related to #1139 but the case here is a bit simpler, I believe.

Is there a way to make this work? Alternatively, is there any workaround?

Thank you for any input on this!

@daxpedda
Copy link
Collaborator

daxpedda commented Sep 7, 2024

You could just take JsValues as arguments and figure out which type it is at runtime, but otherwise this isn't supported.

I'm going to close this in favor of #1339, while it is true that this proposal is a bit simpler, the implementation would be the same and its just API design at this point.

@daxpedda daxpedda closed this as not planned Won't fix, can't repro, duplicate, stale Sep 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants