rune/ast/
item_use.rs

1use crate::ast::prelude::*;
2
3#[test]
4#[cfg(not(miri))]
5fn ast_parse() {
6    rt::<ast::ItemUse>("use foo");
7    rt::<ast::ItemUse>("use foo::bar");
8    rt::<ast::ItemUse>("use foo::bar::baz");
9    rt::<ast::ItemUse>("#[macro_use] use foo::bar::baz");
10    rt::<ast::ItemUse>("#[macro_use] pub(crate) use foo::bar::baz");
11
12    rt::<ast::ItemUsePath>("crate::foo");
13    rt::<ast::ItemUsePath>("foo::bar");
14    rt::<ast::ItemUsePath>("foo::bar::{baz::*, biz}");
15    rt::<ast::ItemUsePath>("{*, bar::*}");
16    rt::<ast::ItemUsePath>("::{*, bar::*}");
17}
18
19/// A `use` item.
20///
21/// * `use <path>`
22#[derive(Debug, TryClone, PartialEq, Eq, Parse, ToTokens, Spanned)]
23#[rune(parse = "meta_only")]
24#[non_exhaustive]
25pub struct ItemUse {
26    /// The attributes on use item
27    #[rune(iter, meta)]
28    pub attributes: Vec<ast::Attribute>,
29    /// The visibility of the `use` item
30    #[rune(option, meta)]
31    pub visibility: ast::Visibility,
32    /// The use token.
33    pub use_token: T![use],
34    /// Item path.
35    pub path: ItemUsePath,
36}
37
38item_parse!(Use, ItemUse, "use item");
39
40/// A single use declaration path.
41///
42/// * `foo::bar::{baz::*, biz}`.
43#[derive(Debug, TryClone, PartialEq, Eq, Parse, ToTokens, Spanned)]
44#[non_exhaustive]
45pub struct ItemUsePath {
46    /// Global prefix.
47    #[rune(iter)]
48    pub global: Option<T![::]>,
49    /// The first use component.
50    pub first: ItemUseSegment,
51    /// Optional segments.
52    #[rune(iter)]
53    pub segments: Vec<(T![::], ItemUseSegment)>,
54    /// The alias of the import.
55    #[rune(iter)]
56    pub alias: Option<(T![as], ast::Ident)>,
57}
58
59/// A use component.
60#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Spanned)]
61#[non_exhaustive]
62pub enum ItemUseSegment {
63    /// A path segment.
64    PathSegment(ast::PathSegment),
65    /// A wildcard import.
66    Wildcard(T![*]),
67    /// A grouped import.
68    Group(ast::Braced<ast::ItemUsePath, T![,]>),
69}
70
71impl Peek for ItemUseSegment {
72    fn peek(p: &mut Peeker<'_>) -> bool {
73        matches!(p.nth(0), K![*] | K!['[']) || ast::PathSegment::peek(p)
74    }
75}
76
77impl Parse for ItemUseSegment {
78    fn parse(p: &mut Parser<'_>) -> Result<Self> {
79        Ok(match p.nth(0)? {
80            K![*] => Self::Wildcard(p.parse()?),
81            K!['{'] => Self::Group(p.parse()?),
82            _ => Self::PathSegment(p.parse()?),
83        })
84    }
85}