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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
//! [`ExpandedUseTree`], an extension to [`syn::UseTree`].
#[cfg(any(test, feature = "quote"))]
#[cfg_attr(test, macro_use)]
extern crate quote;

#[macro_use]
extern crate syn;

use syn::punctuated::Punctuated;
use syn::{Ident, UseGlob, UseName, UseRename, UseTree};

#[cfg(any(test, feature = "quote"))]
use quote::{ToTokens, Tokens};

/// A leaf node from a [`UseTree`].
#[cfg_attr(feature = "clone-impls", derive(Clone))]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, Hash))]
pub enum UseItem {
    /// A simple item, e.g. `name`.
    Name(UseName),

    /// A renamed item, e.g. `name as renamed`.
    Rename(UseRename),

    /// A glob import, i.e. `*`.
    Glob(UseGlob),
}
impl From<UseName> for UseItem {
    #[inline]
    fn from(name: UseName) -> UseItem {
        UseItem::Name(name)
    }
}
impl From<UseRename> for UseItem {
    #[inline]
    fn from(rename: UseRename) -> UseItem {
        UseItem::Rename(rename)
    }
}
impl From<UseGlob> for UseItem {
    #[inline]
    fn from(glob: UseGlob) -> UseItem {
        UseItem::Glob(glob)
    }
}
#[cfg(any(test, feature = "quote"))]
impl ToTokens for UseItem {
    #[inline]
    fn to_tokens(&self, tokens: &mut Tokens) {
        match *self {
            UseItem::Name(ref name) => name.to_tokens(tokens),
            UseItem::Rename(ref rename) => rename.to_tokens(tokens),
            UseItem::Glob(ref glob) => glob.to_tokens(tokens),
        }
    }
}

/// An expanded item from a [`UseTree`].
#[cfg_attr(feature = "clone-impls", derive(Clone))]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, Hash))]
pub struct ExpandedUseItem {
    /// The path to the item, which may be empty.
    pub prefix: Punctuated<Ident, Token![::]>,

    /// Item itself.
    pub item: UseItem,
}
#[cfg(any(test, feature = "quote"))]
impl ToTokens for ExpandedUseItem {
    #[inline]
    fn to_tokens(&self, tokens: &mut Tokens) {
        self.prefix.to_tokens(tokens);
        self.item.to_tokens(tokens);
    }
}

/// An expanded [`UseTree`].
#[cfg_attr(feature = "clone-impls", derive(Clone))]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, Hash))]
pub struct ExpandedUseTree {
    /// The expanded items.
    pub items: Punctuated<ExpandedUseItem, Token![,]>,
}
impl ExpandedUseTree {
    /// Expands the given [`UseTree`].
    pub fn new(tree: UseTree) -> Self {
        fn expand(
            tree: UseTree,
            expanded: &mut Punctuated<ExpandedUseItem, Token![,]>,
            prefix: &mut Punctuated<Ident, Token![::]>,
        ) {
            match tree {
                UseTree::Name(name) => expanded.push_value(ExpandedUseItem {
                    item: name.into(),
                    prefix: prefix.clone(),
                }),
                UseTree::Rename(rename) => expanded.push_value(ExpandedUseItem {
                    item: rename.into(),
                    prefix: prefix.clone(),
                }),
                UseTree::Glob(glob) => expanded.push_value(ExpandedUseItem {
                    item: glob.into(),
                    prefix: prefix.clone(),
                }),
                UseTree::Path(path) => {
                    prefix.push_value(path.ident);
                    prefix.push_punct(path.colon2_token);
                    expand(*path.tree, expanded, prefix);
                    prefix.pop();
                }
                UseTree::Group(group) => {
                    for pair in group.items.into_pairs() {
                        let (tree, comma) = pair.into_tuple();
                        expand(tree, expanded, prefix);
                        if let Some(comma) = comma {
                            if !expanded.empty_or_trailing() {
                                expanded.push_punct(comma);
                            }
                        }
                    }
                }
            }
        }
        let mut expanded = Punctuated::new();
        let mut prefix = Punctuated::new();
        expand(tree, &mut expanded, &mut prefix);
        ExpandedUseTree { items: expanded }
    }
}
impl<T: Into<UseTree>> From<T> for ExpandedUseTree {
    #[inline]
    fn from(tree: T) -> Self {
        Self::new(tree.into())
    }
}
#[cfg(any(test, feature = "quote"))]
impl ToTokens for ExpandedUseTree {
    #[inline]
    fn to_tokens(&self, tokens: &mut Tokens) {
        self.items.to_tokens(tokens);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! test_tokens {
        ($name:ident: ($($lhs:tt)*) => ($($rhs:tt)*)) => (
            #[test]
            fn $name() {
                let tree: UseTree = parse_quote! { $($lhs)* };
                let expand = ExpandedUseTree::new(tree);
                assert_eq!(expand.into_tokens(), quote! { $($rhs)* });
            }
        )
    }

    test_tokens!(nested_empty:
        ({{}, {{},}, {},}) => ()
    );
    test_tokens!(nested_single1:
        ({a, {b,}, c, d}) => (a, b, c, d)
    );
    test_tokens!(nested_single2:
        ({{a}, {{b}}, {c,}, {}}) => (a, b, c,)
    );
    test_tokens!(nested_multi:
        ({{a, b, c,}, {{d}, {e, f},}, {g,}, {h,}}) => (a, b, c, d, e, f, g, h,)
    );
    test_tokens!(paths1:
        (a::{b, c::{d, e}}) => (a::b, a::c::d, a::c::e)
    );
    test_tokens!(paths2:
        ({a::{b, c}, {d, e}, {f::g::*, h}}) => (a::b, a::c, d, e, f::g::*, h)
    );
}