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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
//! [`ExpandedItemUse`], an extension to [`syn::UseTree`].
#![forbid(missing_docs)]
#![cfg_attr(feature = "extra-traits", forbid(missing_debug_implementations))]

#[cfg(any(test, feature = "quote"))]
#[cfg_attr(test, macro_use)]
extern crate quote;

#[macro_use]
extern crate syn;

use std::iter::FromIterator;

use syn::punctuated::Punctuated;
use syn::token::Brace;
use syn::{Attribute, File, Ident, Item, ItemUse, UseGlob, UseName, UseRename, UseTree, Visibility};

#[cfg(any(test, feature = "quote"))]
use quote::{ToTokens, Tokens};
#[cfg(all(feature = "parsing", feature = "printing"))]
use syn::spanned::Spanned;

/// 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 [`ItemUse`].
#[cfg_attr(feature = "clone-impls", derive(Clone))]
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq, Hash))]
pub struct ExpandedItemUse {
    /// The attributes on the [`ItemUse`].
    pub attrs: Vec<Attribute>,

    /// The visibility of the [`ItemUse`].
    pub vis: Visibility,

    /// The use token.
    pub use_token: Token![use],

    /// A brace token around the expanded items.
    pub brace_token: Brace,

    /// The expanded items.
    pub items: Punctuated<ExpandedUseItem, Token![,]>,

    /// The semicolon.
    pub semi_token: Token![;],
}
impl ExpandedItemUse {
    /// Expands all the item-level [`ItemUse`]s in the given file, with paths relative to the file.
    ///
    /// This only includes [`ItemUse`] statements at the top level or within [`ItemMod`]s. It also
    /// prunes empty [`ItemUse`]s
    ///
    /// [`ItemMod`]: syn::ItemMod
    pub fn all_from_file(file: File) -> Vec<Self> {
        let mut expanded = Vec::new();
        let mut prefix = Punctuated::new();
        Self::expand_items(file.items, &mut expanded, &mut prefix);
        expanded
    }

    /// Expands the given [`ItemUse`], assuming the given prefix.
    pub fn with_prefix(item: ItemUse, mut prefix: Punctuated<Ident, Token![::]>) -> Self {
        let mut expanded = Punctuated::new();
        let mut brace = None;
        Self::expand(item.tree, &mut brace, &mut expanded, &mut prefix);
        ExpandedItemUse {
            attrs: item.attrs,
            vis: item.vis,
            use_token: item.use_token,
            brace_token: brace.unwrap_or_default(),
            items: expanded,
            semi_token: item.semi_token,
        }
    }

    /// Expands the given [`ItemUse`].
    pub fn new(item: ItemUse) -> Self {
        Self::with_prefix(item, Punctuated::new())
    }

    fn expand_items(
        items: Vec<Item>,
        expanded: &mut Vec<Self>,
        prefix: &mut Punctuated<Ident, Token![::]>,
    ) {
        for item in items {
            match item {
                Item::Use(item) => {
                    let mut inner = Punctuated::new();
                    let mut brace = None;
                    Self::expand(item.tree, &mut brace, &mut inner, prefix);
                    if !inner.is_empty() {
                        expanded.push(ExpandedItemUse {
                            attrs: item.attrs,
                            vis: item.vis,
                            use_token: item.use_token,
                            brace_token: brace.unwrap_or_default(),
                            items: inner,
                            semi_token: item.semi_token,
                        });
                    }
                }
                Item::Mod(item) => {
                    // only pay attention to modules with content
                    if let Some((_, list)) = item.content {
                        // in most cases, the `default` token will be replaced with a real one
                        prefix.push_value(item.ident);
                        prefix.push_punct(<Token![::]>::default());
                        Self::expand_items(list, expanded, prefix);
                        prefix.pop();
                    }
                }
                _ => {}
            }
        }
    }

    fn expand(
        tree: UseTree,
        brace: &mut Option<Brace>,
        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) => {
                match path.ident.as_ref() {
                    // self doesn't affect the path
                    "self" => {
                        // if we can, replace the `::` token for a more accurate span
                        if let Some(parent) = prefix.pop() {
                            let (ident, colon2) = parent.into_tuple();
                            prefix.push_value(ident);
                            prefix.push_punct(path.colon2_token);
                            Self::expand(*path.tree, brace, expanded, prefix);

                            // but restore the old one after
                            prefix.pop();
                            prefix.push_value(ident);
                            if let Some(c2) = colon2 {
                                prefix.push_punct(c2);
                            }
                            return;
                        } else {
                            return Self::expand(*path.tree, brace, expanded, prefix);
                        }
                    }

                    // super removes one layer of the path if it exists
                    "super" => {
                        if let Some(pair) = prefix.pop() {
                            let (ident, colon2) = pair.into_tuple();
                            Self::expand(*path.tree, brace, expanded, prefix);
                            prefix.push_value(ident);
                            if let Some(c2) = colon2 {
                                prefix.push_punct(c2);
                            }
                            return;
                        }
                    }
                    _ => {}
                }

                // neither self nor super with a path segment to cancel
                prefix.push_value(path.ident);
                prefix.push_punct(path.colon2_token);
                Self::expand(*path.tree, brace, expanded, prefix);
                prefix.pop();
            }
            UseTree::Group(group) => {
                if brace.is_none() {
                    *brace = Some(group.brace_token);
                }
                for pair in group.items.into_pairs() {
                    let (tree, comma) = pair.into_tuple();
                    Self::expand(tree, brace, expanded, prefix);
                    if let Some(comma) = comma {
                        if !expanded.empty_or_trailing() {
                            expanded.push_punct(comma);
                        }
                    }
                }
            }
        }
    }
}
impl From<ItemUse> for ExpandedItemUse {
    #[inline]
    fn from(item: ItemUse) -> Self {
        Self::new(item)
    }
}
impl Extend<ExpandedItemUse> for ExpandedItemUse {
    #[cfg(all(feature = "parsing", feature = "printing"))]
    fn extend<I: IntoIterator<Item = ExpandedItemUse>>(&mut self, iter: I) {
        let mut tokens = Tokens::new();
        for item in iter {
            self.brace_token.surround(&mut tokens, |_| {});
            self.items.extend(item.items);
        }
        self.brace_token.0 = Spanned::span(&tokens);
    }

    #[cfg(not(all(feature = "parsing", feature = "printing")))]
    fn extend<I: IntoIterator<Item = ExpandedItemUse>>(&mut self, iter: I) {
        self.items
            .extend(iter.into_iter().flat_map(|item| item.items));
    }
}
impl FromIterator<ExpandedItemUse> for ExpandedItemUse {
    fn from_iter<I: IntoIterator<Item = ExpandedItemUse>>(iter: I) -> Self {
        let mut iter = iter.into_iter();
        let mut first = iter.next().unwrap_or_else(|| ExpandedItemUse {
            attrs: Vec::new(),
            vis: Visibility::Inherited,
            use_token: Default::default(),
            brace_token: Default::default(),
            items: Punctuated::new(),
            semi_token: Default::default(),
        });
        first.extend(iter);
        first
    }
}
#[cfg(any(test, feature = "quote"))]
impl ToTokens for ExpandedItemUse {
    #[inline]
    fn to_tokens(&self, tokens: &mut Tokens) {
        for attr in &self.attrs {
            attr.to_tokens(tokens);
        }
        self.vis.to_tokens(tokens);
        self.use_token.to_tokens(tokens);
        self.brace_token
            .surround(tokens, |tokens| self.items.to_tokens(tokens));
        self.semi_token.to_tokens(tokens);
    }
}

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

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

    macro_rules! test_file_tokens {
        ($name:ident: ($($lhs:tt)*) => ($($rhs:tt)*)) => (
            #[test]
            fn $name() {
                let file: File = parse_quote! { $($lhs)* };
                let expand = ExpandedItemUse::all_from_file(file);
                let mut tokens = Tokens::new();
                tokens.append_all(expand);
                assert_eq!(tokens, quote! { $($rhs)* });
            }
        )
    }

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

    test_tokens!(relative:
        (use {self::a::self::super::b::self::c};) => (use {b::c};)
    );

    test_file_tokens!(just_glob:
        (
            mod a {
                mod b {
                    use super::super::{self::{}};
                }
                use self::{};
            }
            use self::*;
        ) => (
            use {*};
        )
    );

    test_file_tokens!(not_just_glob:
        (
            mod a {
                mod b {
                    use super::super::{self::{a, b::*}};
                }
                use self::c;
            }
            use self::*;
        ) => (
            use {a, b::*};
            use {a::c};
            use {*};
        )
    );
}