From b6ee9e40d2a308980e4d4aff9b47eda730a6ad91 Mon Sep 17 00:00:00 2001 From: Mike Welsh Date: Thu, 28 Jan 2021 18:22:53 -0800 Subject: [PATCH] Avoid errors if vendor-prefixed APIs do not exist 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. --- crates/cli-support/src/js/mod.rs | 10 +++++----- tests/wasm/vendor_prefix.rs | 8 ++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/cli-support/src/js/mod.rs b/crates/cli-support/src/js/mod.rs index 75b027256336..2fc6a4f66932 100644 --- a/crates/cli-support/src/js/mod.rs +++ b/crates/cli-support/src/js/mod.rs @@ -2095,10 +2095,6 @@ 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); @@ -2106,7 +2102,11 @@ impl<'a> Context<'a> { 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) diff --git a/tests/wasm/vendor_prefix.rs b/tests/wasm/vendor_prefix.rs index d824800aae63..29627190607b 100644 --- a/tests/wasm/vendor_prefix.rs +++ b/tests/wasm/vendor_prefix.rs @@ -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; } #[wasm_bindgen_test] @@ -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()); }