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
use serde::{Deserialize, Serialize};
use std::fmt;

use super::Ident;

#[derive(Hash, Eq, PartialEq, Deserialize, Serialize, Clone, Debug, Ord, PartialOrd)]
#[non_exhaustive]
pub struct Path {
    pub elements: Vec<Ident>,
}

impl Path {
    pub fn get_super(&self) -> Path {
        let mut new_elements = self.elements.clone();
        new_elements.remove(new_elements.len() - 1);
        Path {
            elements: new_elements,
        }
    }

    pub fn sub_path(&self, ident: Ident) -> Path {
        let mut new_elements = self.elements.clone();
        new_elements.push(ident);
        Path {
            elements: new_elements,
        }
    }

    pub fn to_syn(&self) -> syn::Path {
        syn::Path {
            leading_colon: None,
            segments: self
                .elements
                .iter()
                .map(|s| syn::PathSegment {
                    ident: s.to_syn(),
                    arguments: syn::PathArguments::None,
                })
                .collect(),
        }
    }

    pub fn from_syn(path: &syn::Path) -> Path {
        Path {
            elements: path
                .segments
                .iter()
                .map(|seg| (&seg.ident).into())
                .collect(),
        }
    }

    pub fn empty() -> Path {
        Path { elements: vec![] }
    }
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some((head, tail)) = self.elements.split_first() {
            head.fmt(f)?;
            for seg in tail {
                "::".fmt(f)?;
                seg.fmt(f)?;
            }
        }
        Ok(())
    }
}

impl FromIterator<Ident> for Path {
    fn from_iter<T: IntoIterator<Item = Ident>>(iter: T) -> Self {
        Path {
            elements: iter.into_iter().collect(),
        }
    }
}