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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
use crate::ir::Identifier;
use quote::ToTokens;
use quote::TokenStreamExt;
use quote::quote;
use proc_macro2::TokenStream;

/// A fully qualified path.
#[derive(Debug, Clone, PartialEq)]
pub struct Path {
    /// The path segments.
    pub segments: Vec<Identifier>
}

impl Path {
    /// Get the last segment of the path.
    pub fn last(&self) -> Identifier {
        self.segments.last().unwrap().clone()
    }
}

impl From<&str> for Path {
    fn from(string: &str) -> Path {
        let segments = string
            .split("::")
            .into_iter()
            .map(|segment| Identifier::new(segment))
            .collect();
        Self { segments }
    }
}

impl From<String> for Path {
    fn from(string: String) -> Path {
        string.as_str().into()
    }
}

impl From<syn::Path> for Path {
    fn from(path: syn::Path) -> Self {
        let segments = path
            .segments
            .iter()
            .map(|segment| segment.ident.clone().into())
            .collect();
        Self { segments }
    }
}

impl From<Identifier> for Path {
    fn from(identifier: Identifier) -> Self {
        let segments = vec![identifier];
        Self { segments }
    }
}

impl From<syn::Ident> for Path {
    fn from(identifier: syn::Ident) -> Self {
        let segments = vec![identifier.into()];
        Self { segments }
    }
}

impl ToTokens for Path {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let mut segments = self.segments.iter();
        tokens.append_all(segments.next().unwrap().to_token_stream());
        for segment in segments {
            tokens.append_all(quote! { ::#segment })
        }
    }
}

#[cfg(test)]
mod test {
    use quote::quote;
    use syn::parse_quote::parse;
    use crate::ir::Path;
    use crate::ir::Identifier;

    #[test]
    fn identifier_as_path() {
        let path: Path = parse::<syn::Path>(quote! { u8 }).into();
        assert_eq!(path.segments.first(), Some(&Identifier::new("u8")));
    }

    #[test]
    fn path() {
        let path: Path = parse::<syn::Path>(quote! { std::convert::TryFrom }).into();
        let segments: Vec<_> = vec!["std", "convert", "TryFrom"].into_iter().map(Identifier::from).collect();
        assert_eq!(path.segments, segments);
    }

    #[test]
    fn path_from_string() {
        let path: Path = "std::convert::TryFrom".into();
        let segments: Vec<_> = vec!["std", "convert", "TryFrom"].into_iter().map(Identifier::from).collect();
        assert_eq!(path.segments, segments);
    }

}