1 | // Take a look at the license at the top of the repository in the LICENSE file. |
2 | |
3 | use proc_macro2::TokenStream; |
4 | use proc_macro_error::abort_call_site; |
5 | use quote::quote; |
6 | use syn::Data; |
7 | |
8 | use crate::utils::{crate_ident_new, gen_enum_from_glib, parse_nested_meta_items, NestedMetaItem}; |
9 | |
10 | pub fn impl_error_domain(input: &syn::DeriveInput) -> TokenStream { |
11 | let name = &input.ident; |
12 | |
13 | let enum_variants = match input.data { |
14 | Data::Enum(ref e) => &e.variants, |
15 | _ => abort_call_site!("#[derive(glib::ErrorDomain)] only supports enums" ), |
16 | }; |
17 | |
18 | let mut domain_name = NestedMetaItem::<syn::LitStr>::new("name" ) |
19 | .required() |
20 | .value_required(); |
21 | let found = parse_nested_meta_items(&input.attrs, "error_domain" , &mut [&mut domain_name]); |
22 | |
23 | match found { |
24 | Ok(None) => { |
25 | abort_call_site!( |
26 | "#[derive(glib::ErrorDomain)] requires #[error_domain(name = \"domain-name \")]" |
27 | ) |
28 | } |
29 | Err(e) => return e.to_compile_error(), |
30 | Ok(_) => (), |
31 | }; |
32 | let domain_name = domain_name.value.unwrap(); |
33 | let crate_ident = crate_ident_new(); |
34 | |
35 | let from_glib = gen_enum_from_glib(name, enum_variants); |
36 | |
37 | quote! { |
38 | impl #crate_ident::error::ErrorDomain for #name { |
39 | #[inline] |
40 | fn domain() -> #crate_ident::Quark { |
41 | use #crate_ident::translate::from_glib; |
42 | |
43 | static QUARK: #crate_ident::once_cell::sync::Lazy<#crate_ident::Quark> = |
44 | #crate_ident::once_cell::sync::Lazy::new(|| unsafe { |
45 | from_glib(#crate_ident::ffi::g_quark_from_static_string(concat!(#domain_name, " \0" ) as *const ::core::primitive::str as *const _)) |
46 | }); |
47 | *QUARK |
48 | } |
49 | |
50 | #[inline] |
51 | fn code(self) -> i32 { |
52 | self as i32 |
53 | } |
54 | |
55 | #[inline] |
56 | fn from(value: i32) -> ::core::option::Option<Self> |
57 | where |
58 | Self: ::std::marker::Sized |
59 | { |
60 | #from_glib |
61 | } |
62 | } |
63 | } |
64 | } |
65 | |