freya_router_macro/
hash.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{
    Ident,
    Type,
};

#[derive(Debug)]
pub struct HashFragment {
    pub ident: Ident,
    pub ty: Type,
}

impl HashFragment {
    pub fn contains_ident(&self, ident: &Ident) -> bool {
        self.ident == *ident
    }

    pub fn parse(&self) -> TokenStream2 {
        let ident = &self.ident;
        let ty = &self.ty;
        quote! {
            let #ident = <#ty as freya_router::routable::FromHashFragment>::from_hash_fragment(&*hash);
        }
    }

    pub fn write(&self) -> TokenStream2 {
        let ident = &self.ident;
        quote! {
            {
                let __hash = #ident.to_string();
                if !__hash.is_empty() {
                    write!(f, "#{}", __hash)?;
                }
            }
        }
    }

    pub fn parse_from_str<'a>(
        route_span: proc_macro2::Span,
        mut fields: impl Iterator<Item = (&'a Ident, &'a Type)>,
        hash: &str,
    ) -> syn::Result<Self> {
        // check if the route has a hash string
        let Some(hash) = hash.strip_prefix(':') else {
            return Err(syn::Error::new(
                route_span,
                "Failed to parse `:`. Hash fragments must be in the format '#:<field>'",
            ));
        };

        let hash_ident = Ident::new(hash, proc_macro2::Span::call_site());
        let field = fields.find(|(name, _)| *name == &hash_ident);

        let ty = if let Some((_, ty)) = field {
            ty.clone()
        } else {
            return Err(syn::Error::new(
                route_span,
                format!("Could not find a field with the name '{}'", hash_ident),
            ));
        };

        Ok(Self {
            ident: hash_ident,
            ty,
        })
    }
}