bitwarden_error_macro/full/attribute.rs
1use darling::Error;
2use quote::quote;
3
4pub(crate) fn bitwarden_error_full(
5 input: &syn::DeriveInput,
6 type_identifier: &proc_macro2::Ident,
7 export_as_identifier: &proc_macro2::Ident,
8) -> proc_macro::TokenStream {
9 if type_identifier != export_as_identifier {
10 return Error::custom("`bitwarden_error(full)` does not currently support `export_as`")
11 .write_errors()
12 .into();
13 }
14
15 // Hand-written rather than via `#[tsify(into_wasm_abi)]`: that attribute is deprecated, and its
16 // generated conversion panics when serialization fails, which on wasm aborts the instance.
17 // Only `From<E> for JsValue` is actually needed here, since wasm_bindgen requires no more than
18 // that of a `Result`'s error type.
19 let wasm_conversion = {
20 let export_as_identifier_str = export_as_identifier.to_string();
21 quote! {
22 #[cfg(feature = "wasm")]
23 const _: () = {
24 use bitwarden_error::wasm_bindgen::JsValue;
25
26 #[automatically_derived]
27 impl From<#type_identifier> for JsValue {
28 fn from(error: #type_identifier) -> Self {
29 match bitwarden_error::tsify::Tsify::into_js(&error) {
30 Ok(js) => js.into(),
31 // `From` cannot report failure, so surface a named error rather than
32 // unwinding out of the conversion. The name is deliberately *not* the
33 // error's own: JavaScript narrows on it and then reads `variant`, which
34 // this value does not have. Deliberately does not use
35 // `error.to_string()` either: `full` does not require `Display`.
36 Err(err) => {
37 let js_error = ::bitwarden_error::wasm::SdkJsError::new(
38 format!(
39 "Failed to serialize `{}`: {}",
40 #export_as_identifier_str, err,
41 ),
42 );
43 js_error.set_name(
44 ::bitwarden_error::wasm::CONVERSION_ERROR_NAME.to_owned(),
45 );
46 js_error.into()
47 }
48 }
49 }
50 }
51 };
52 }
53 };
54
55 quote! {
56 #[derive(serde::Serialize)]
57 #[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
58 #[cfg_attr(feature = "wasm", derive(bitwarden_error::tsify::Tsify))]
59 #input
60
61 #wasm_conversion
62 }
63 .into()
64}