mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-13 04:51:23 +00:00
WebIDL: Handle Invalid Enum Returns (#477)
* move ImportEnum attributes to a property * borrow from_js_value argument * make WebIDL enums non-exhaustive * add more tests for WebIDL enums
This commit is contained in:
committed by
Alex Crichton
parent
5fddcf3868
commit
b3ee71c20b
@ -112,6 +112,8 @@ pub struct ImportEnum {
|
||||
pub variants: Vec<Ident>,
|
||||
/// The JS string values of the variants
|
||||
pub variant_values: Vec<String>,
|
||||
/// Attributes to apply to the Rust enum
|
||||
pub rust_attrs: Vec<syn::Attribute>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
|
||||
|
@ -580,9 +580,10 @@ impl ToTokens for ast::ImportEnum {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
let vis = &self.vis;
|
||||
let name = &self.name;
|
||||
let expect_string = format!("attempted to convert invalid JSValue into {}", name);
|
||||
let expect_string = format!("attempted to convert invalid {} into JSValue", name);
|
||||
let variants = &self.variants;
|
||||
let variant_strings = &self.variant_values;
|
||||
let attrs = &self.rust_attrs;
|
||||
|
||||
let mut current_idx: usize = 0;
|
||||
let variant_indexes: Vec<Literal> = variants
|
||||
@ -609,13 +610,15 @@ impl ToTokens for ast::ImportEnum {
|
||||
|
||||
(quote! {
|
||||
#[allow(bad_style)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
#(#attrs)*
|
||||
#vis enum #name {
|
||||
#(#variants = #variant_indexes_ref,)*
|
||||
#[doc(hidden)]
|
||||
__Nonexhaustive,
|
||||
}
|
||||
|
||||
impl #name {
|
||||
#vis fn from_js_value(obj: ::wasm_bindgen::JsValue) -> Option<#name> {
|
||||
#vis fn from_js_value(obj: &::wasm_bindgen::JsValue) -> Option<#name> {
|
||||
obj.as_string().and_then(|obj_str| match obj_str.as_str() {
|
||||
#(#variant_strings => Some(#variant_paths_ref),)*
|
||||
_ => None,
|
||||
@ -646,14 +649,15 @@ impl ToTokens for ast::ImportEnum {
|
||||
js: Self::Abi,
|
||||
extra: &mut ::wasm_bindgen::convert::Stack,
|
||||
) -> Self {
|
||||
#name::from_js_value(::wasm_bindgen::JsValue::from_abi(js, extra)).expect(#expect_string)
|
||||
#name::from_js_value(&::wasm_bindgen::JsValue::from_abi(js, extra)).unwrap_or(#name::__Nonexhaustive)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<#name> for ::wasm_bindgen::JsValue {
|
||||
fn from(obj: #name) -> ::wasm_bindgen::JsValue {
|
||||
match obj {
|
||||
#(#variant_paths_ref => ::wasm_bindgen::JsValue::from_str(#variant_strings)),*
|
||||
#(#variant_paths_ref => ::wasm_bindgen::JsValue::from_str(#variant_strings),)*
|
||||
#name::__Nonexhaustive => panic!(#expect_string),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user