zbus_macros/
error.rs

1use proc_macro2::TokenStream;
2use quote::{quote, ToTokens};
3use syn::{spanned::Spanned, Data, DeriveInput, Error, Fields, Ident, Variant};
4use zvariant_utils::def_attrs;
5
6def_attrs! {
7    crate zbus;
8
9    pub StructAttributes("struct") {
10        prefix str,
11        impl_display bool
12    };
13
14    pub VariantAttributes("enum variant") {
15        name str,
16        error none
17    };
18}
19
20use crate::utils::*;
21
22pub fn expand_derive(input: DeriveInput) -> Result<TokenStream, Error> {
23    let StructAttributes {
24        prefix,
25        impl_display,
26    } = StructAttributes::parse(&input.attrs)?;
27    let prefix = prefix.unwrap_or_else(|| "org.freedesktop.DBus".to_string());
28    let generate_display = impl_display.unwrap_or(true);
29
30    let (_vis, name, _generics, data) = match input.data {
31        Data::Enum(data) => (input.vis, input.ident, input.generics, data),
32        _ => return Err(Error::new(input.span(), "only enums supported")),
33    };
34
35    let zbus = zbus_path();
36    let mut replies = quote! {};
37    let mut error_names = quote! {};
38    let mut error_descriptions = quote! {};
39    let mut error_converts = quote! {};
40
41    let mut zbus_error_variant = None;
42
43    for variant in data.variants {
44        let VariantAttributes { name, error } = VariantAttributes::parse(&variant.attrs)?;
45        let ident = &variant.ident;
46        let name = name.unwrap_or_else(|| ident.to_string());
47
48        let fqn = if !error {
49            format!("{prefix}.{name}")
50        } else {
51            // The ZBus error variant will always be a hardcoded string.
52            String::from("org.freedesktop.zbus.Error")
53        };
54
55        let error_name = quote! {
56            #zbus::names::ErrorName::from_static_str_unchecked(#fqn)
57        };
58        let e = match variant.fields {
59            Fields::Unit => quote! {
60                Self::#ident => #error_name,
61            },
62            Fields::Unnamed(_) => quote! {
63                Self::#ident(..) => #error_name,
64            },
65            Fields::Named(_) => quote! {
66                Self::#ident { .. } => #error_name,
67            },
68        };
69        error_names.extend(e);
70
71        if error {
72            if zbus_error_variant.is_some() {
73                panic!("More than 1 `#[zbus(error)]` variant found");
74            }
75
76            zbus_error_variant = Some(quote! { #ident });
77        }
78
79        // FIXME: this will error if the first field is not a string as per the dbus spec, but we
80        // may support other cases?
81        let e = match &variant.fields {
82            Fields::Unit => quote! {
83                Self::#ident => None,
84            },
85            Fields::Unnamed(_) => {
86                if error {
87                    quote! {
88                        Self::#ident(e) => e.description(),
89                    }
90                } else {
91                    quote! {
92                        Self::#ident(desc, ..) => Some(&desc),
93                    }
94                }
95            }
96            Fields::Named(n) => {
97                let f = &n
98                    .named
99                    .first()
100                    .ok_or_else(|| Error::new(n.span(), "expected at least one field"))?
101                    .ident;
102                quote! {
103                    Self::#ident { #f, } => Some(#f),
104                }
105            }
106        };
107        error_descriptions.extend(e);
108
109        // The conversion for #[zbus(error)] variant is handled separately/explicitly.
110        if !error {
111            // FIXME: deserialize msg to error field instead, to support variable args
112            let e = match &variant.fields {
113                Fields::Unit => quote! {
114                    #fqn => Self::#ident,
115                },
116                Fields::Unnamed(_) => quote! {
117                    #fqn => { Self::#ident(::std::clone::Clone::clone(desc).unwrap_or_default()) },
118                },
119                Fields::Named(n) => {
120                    let f = &n
121                        .named
122                        .first()
123                        .ok_or_else(|| Error::new(n.span(), "expected at least one field"))?
124                        .ident;
125                    quote! {
126                        #fqn => {
127                            let desc = ::std::clone::Clone::clone(desc).unwrap_or_default();
128
129                            Self::#ident { #f: desc }
130                        }
131                    }
132                }
133            };
134            error_converts.extend(e);
135        }
136
137        let r = gen_reply_for_variant(&variant, error)?;
138        replies.extend(r);
139    }
140
141    let from_zbus_error_impl = zbus_error_variant
142        .map(|ident| {
143            quote! {
144                impl ::std::convert::From<#zbus::Error> for #name {
145                    fn from(value: #zbus::Error) -> #name {
146                        if let #zbus::Error::MethodError(name, desc, _) = &value {
147                            match name.as_str() {
148                                #error_converts
149                                _ => Self::#ident(value),
150                            }
151                        } else {
152                            Self::#ident(value)
153                        }
154                    }
155                }
156            }
157        })
158        .unwrap_or_default();
159
160    let display_impl = if generate_display {
161        quote! {
162            impl ::std::fmt::Display for #name {
163                fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
164                    let name = #zbus::DBusError::name(self);
165                    let description = #zbus::DBusError::description(self).unwrap_or("no description");
166                    ::std::write!(f, "{}: {}", name, description)
167                }
168            }
169        }
170    } else {
171        quote! {}
172    };
173
174    Ok(quote! {
175        impl #zbus::DBusError for #name {
176            fn name(&self) -> #zbus::names::ErrorName {
177                match self {
178                    #error_names
179                }
180            }
181
182            fn description(&self) -> Option<&str> {
183                match self {
184                    #error_descriptions
185                }
186            }
187
188            fn create_reply(&self, call: &#zbus::message::Header) -> #zbus::Result<#zbus::message::Message> {
189                let name = self.name();
190                match self {
191                    #replies
192                }
193            }
194        }
195
196        #display_impl
197
198        impl ::std::error::Error for #name {}
199
200        #from_zbus_error_impl
201    })
202}
203
204fn gen_reply_for_variant(
205    variant: &Variant,
206    zbus_error_variant: bool,
207) -> Result<TokenStream, Error> {
208    let zbus = zbus_path();
209    let ident = &variant.ident;
210    match &variant.fields {
211        Fields::Unit => Ok(quote! {
212            Self::#ident => #zbus::message::Message::error(call, name)?.build(&()),
213        }),
214        Fields::Unnamed(f) => {
215            // Name the unnamed fields as the number of the field with an 'f' in front.
216            let in_fields = (0..f.unnamed.len())
217                .map(|n| Ident::new(&format!("f{n}"), ident.span()).to_token_stream())
218                .collect::<Vec<_>>();
219            let out_fields = if zbus_error_variant {
220                let error_field = in_fields.first().ok_or_else(|| {
221                    Error::new(
222                        ident.span(),
223                        "expected at least one field for #[zbus(error)] variant",
224                    )
225                })?;
226                vec![quote! {
227                    match #error_field {
228                        #zbus::Error::MethodError(name, desc, _) => {
229                            ::std::clone::Clone::clone(desc)
230                        }
231                        _ => None,
232                    }
233                    .unwrap_or_else(|| ::std::string::ToString::to_string(#error_field))
234                }]
235            } else {
236                // FIXME: Workaround for https://github.com/rust-lang/rust-clippy/issues/10577
237                #[allow(clippy::redundant_clone)]
238                in_fields.clone()
239            };
240
241            Ok(quote! {
242                Self::#ident(#(#in_fields),*) => #zbus::message::Message::error(call, name)?.build(&(#(#out_fields),*)),
243            })
244        }
245        Fields::Named(f) => {
246            let fields = f.named.iter().map(|v| v.ident.as_ref()).collect::<Vec<_>>();
247            Ok(quote! {
248                Self::#ident { #(#fields),* } => #zbus::message::Message::error(call, name)?.build(&(#(#fields),*)),
249            })
250        }
251    }
252}