Skip to content

Commit

Permalink
Avoid errors if vendor-prefixed APIs do not exist
Browse files Browse the repository at this point in the history
Avoid errors in the generated vendor-prefix code if neither the
standard API nor the vendor-prefixed API exists. Instead, fall back
to undefined, which will give the Rust module a chance to run and
handle the error when it tries to use the API.
  • Loading branch information
Herschel committed Jan 29, 2021
1 parent 743135f commit b6ee9e4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
10 changes: 5 additions & 5 deletions crates/cli-support/src/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2095,18 +2095,18 @@ impl<'a> Context<'a> {
self.imports_post.push_str(";\n");

fn switch(dst: &mut String, name: &str, prefix: &str, left: &[String]) {
if left.len() == 0 {
dst.push_str(prefix);
return dst.push_str(name);
}
dst.push_str("(typeof ");
dst.push_str(prefix);
dst.push_str(name);
dst.push_str(" !== 'undefined' ? ");
dst.push_str(prefix);
dst.push_str(name);
dst.push_str(" : ");
switch(dst, name, &left[0], &left[1..]);
if left.len() > 0 {
switch(dst, name, &left[0], &left[1..]);
} else {
dst.push_str("undefined");
}
dst.push_str(")");
}
format!("l{}", name)
Expand Down
8 changes: 8 additions & 0 deletions tests/wasm/vendor_prefix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ extern "C" {
fn new() -> MySpecialApi3;
#[wasm_bindgen(method)]
fn foo(this: &MySpecialApi3) -> u32;

// This API does not exist at all;
// test that Rust gets a chance to catch the error (#2437)
#[wasm_bindgen(vendor_prefix = a, vendor_prefix = b)]
type MyMissingApi;
#[wasm_bindgen(constructor, catch)]
fn new() -> Result<MyMissingApi, JsValue>;
}

#[wasm_bindgen_test]
Expand All @@ -37,4 +44,5 @@ pub fn polyfill_works() {
assert_eq!(MySpecialApi::new().foo(), 123);
assert_eq!(MySpecialApi2::new().foo(), 124);
assert_eq!(MySpecialApi3::new().foo(), 125);
assert!(MyMissingApi::new().is_err());
}

0 comments on commit b6ee9e4

Please sign in to comment.