Skip to main content

bitwarden_ffi_macro/
wasm_record.rs

1use proc_macro2::TokenStream;
2use quote::{ToTokens, quote};
3use syn::{Ident, Item, parse2};
4
5use crate::attrs;
6
7/// Declares a serde DTO: derives `Tsify` under the `wasm` feature and implements the wire traits so
8/// the type crosses as `Ts<Self>`, only from JavaScript with `input`.
9pub(crate) fn wasm_record(attr: TokenStream, item: TokenStream) -> TokenStream {
10    let input_only = match parse_input_only(attr) {
11        Ok(input_only) => input_only,
12        Err(err) => return err.to_compile_error(),
13    };
14
15    let item = match parse2::<Item>(item) {
16        Ok(item) => item,
17        Err(err) => return err.to_compile_error(),
18    };
19
20    if let Err(err) = attrs::check_exportable_type(&item, "wasm_record") {
21        return err.to_compile_error();
22    }
23
24    let ident = match &item {
25        Item::Struct(item) => &item.ident,
26        Item::Enum(item) => &item.ident,
27        _ => unreachable!("check_exportable_type rejects every other item"),
28    };
29
30    // `#[serde(..)]` and `#[tsify(..)]` stay on the item and its fields for `Tsify`'s derive to
31    // read, so the item is emitted as written.
32    let body = item.to_token_stream();
33    let wire_args = if input_only {
34        quote!(#ident, input)
35    } else {
36        quote!(#ident)
37    };
38    quote! {
39        #[cfg_attr(feature = "wasm", derive(::bitwarden_ffi::_macro::Tsify))]
40        #body
41
42        ::bitwarden_ffi::impl_wire_record!(#wire_args);
43    }
44}
45
46fn parse_input_only(attr: TokenStream) -> syn::Result<bool> {
47    if attr.is_empty() {
48        return Ok(false);
49    }
50    match parse2::<Ident>(attr.clone()) {
51        Ok(ident) if ident == "input" => Ok(true),
52        _ => Err(syn::Error::new_spanned(
53            attr,
54            "#[wasm_record] takes no arguments other than `input`",
55        )),
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    fn expand(item: TokenStream) -> String {
64        wasm_record(TokenStream::new(), item)
65            .to_string()
66            .replace(' ', "")
67    }
68
69    #[test]
70    fn derives_tsify_and_implements_the_wire_traits() {
71        let out = expand(quote! {
72            #[derive(Serialize, Deserialize)]
73            pub struct Point { pub x: i32 }
74        });
75
76        assert!(!out.contains("compile_error!"), "{out}");
77        assert!(
78            out.contains("derive(::bitwarden_ffi::_macro::Tsify)"),
79            "{out}"
80        );
81        assert!(
82            out.contains("::bitwarden_ffi::impl_wire_record!(Point);"),
83            "{out}"
84        );
85        assert!(out.contains("feature=\"wasm\""), "{out}");
86    }
87
88    #[test]
89    fn does_not_opt_into_the_deprecated_abi_attributes() {
90        // The leak this macro exists to close: conversion has to happen in the shim body, not in
91        // `FromWasmAbi::from_abi`.
92        let out = expand(quote! {
93            pub struct Point { pub x: i32 }
94        });
95
96        assert!(!out.contains("into_wasm_abi"), "{out}");
97        assert!(!out.contains("from_wasm_abi"), "{out}");
98    }
99
100    #[test]
101    fn leaves_tsify_and_serde_attributes_in_place() {
102        // `Tsify`'s derive reads both, so neither may be consumed here.
103        let out = expand(quote! {
104            #[derive(Serialize, Deserialize)]
105            #[serde(rename_all = "camelCase")]
106            pub struct Cipher {
107                #[cfg_attr(feature = "wasm", tsify(optional))]
108                pub name: Option<String>,
109            }
110        });
111
112        assert!(out.contains("#[serde(rename_all=\"camelCase\")]"), "{out}");
113        assert!(
114            out.contains("#[cfg_attr(feature=\"wasm\",tsify(optional))]"),
115            "{out}"
116        );
117    }
118
119    #[test]
120    fn input_implements_only_the_js_to_rust_direction() {
121        let out = wasm_record(quote!(input), quote! { pub struct Credentials; })
122            .to_string()
123            .replace(' ', "");
124
125        assert!(!out.contains("compile_error!"), "{out}");
126        assert!(
127            out.contains("::bitwarden_ffi::impl_wire_record!(Credentials,input)"),
128            "{out}"
129        );
130        assert!(!out.contains("from_wasm_abi"), "{out}");
131    }
132
133    #[test]
134    fn rejects_other_arguments() {
135        let out = wasm_record(quote!(into_wasm_abi), quote! { pub struct Point; })
136            .to_string()
137            .replace(' ', "");
138
139        assert!(out.contains("compile_error!"), "{out}");
140        assert!(out.contains("takesnoargumentsotherthan`input`"), "{out}");
141    }
142
143    #[test]
144    fn rejects_generics() {
145        let out = expand(quote! {
146            pub struct Wrapper<T> { pub inner: T }
147        });
148
149        assert!(out.contains("compile_error!"), "{out}");
150        assert!(out.contains("doesnotsupportgenerics"), "{out}");
151    }
152
153    #[test]
154    fn rejects_an_item_that_is_not_a_struct_or_an_enum() {
155        let out = expand(quote! {
156            pub fn point() {}
157        });
158
159        assert!(out.contains("compile_error!"), "{out}");
160        assert!(out.contains("appliestoastructoranenum"), "{out}");
161    }
162}