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
use derive_where::derive_where;
use proc_macro2::{Ident, TokenStream, TokenTree};
use quote::{quote, ToTokens};
use syn::{
    braced,
    ext::IdentExt,
    parse::{Parse, ParseStream},
    token::Brace,
    Error, Result, Token,
};

#[derive_where(Debug)]
#[derive(Clone)]
pub enum IdentOrPounded {
    Ident(Ident),
    Pounded(#[derive_where(skip)] Token![#], TokenTree),
}

impl IdentOrPounded {
    fn is_self(&self) -> bool {
        if let Self::Ident(ident) = self {
            ident == "self"
        } else {
            false
        }
    }

    fn is_ident(&self) -> bool {
        matches!(self, Self::Ident(_))
    }
}

impl ToTokens for IdentOrPounded {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            IdentOrPounded::Ident(ident) => ident.to_tokens(tokens),
            IdentOrPounded::Pounded(pound, tt) => {
                pound.to_tokens(tokens);
                tt.to_tokens(tokens);
            }
        }
    }
}

impl Parse for IdentOrPounded {
    fn parse(input: ParseStream) -> Result<Self> {
        Ident::parse_any(input)
            .map(Self::Ident)
            .or_else(|_| Ok(Self::Pounded(input.parse()?, input.parse()?)))
    }
}

#[derive(Clone, Debug, Default)]
pub struct Path(Vec<IdentOrPounded>);

impl Path {
    fn push(&mut self, value: IdentOrPounded) {
        self.0.push(value);
    }

    fn pop_self(&mut self) -> bool {
        self.0.last().map_or(false, IdentOrPounded::is_self) && {
            self.pop();
            true
        }
    }

    fn get_ident(&self) -> Result<&Ident> {
        match self.0.last().expect("path should contain a segment") {
            IdentOrPounded::Ident(ident) => Ok(ident),
            IdentOrPounded::Pounded(pound, _) => Err(Error::new_spanned(
                pound,
                "expected ident as last path segment",
            )),
        }
    }

    fn pop_ident(&mut self) -> Result<Ident> {
        match self.0.pop().expect("path should contain a segment") {
            IdentOrPounded::Ident(ident) => Ok(ident),
            IdentOrPounded::Pounded(pound, _) => Err(Error::new_spanned(
                pound,
                "expected ident as last path segment",
            )),
        }
    }

    fn pop(&mut self) {
        self.0
            .pop()
            .expect("path should contain at least one segment");
    }
}

impl ToTokens for Path {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let first = self.0.first().expect("path should contain a segment");
        let colons = first.is_ident().then_some(quote!(::));
        let tail = &self.0[1..];
        quote!(#colons #first #(::#tail)*).to_tokens(tokens)
    }
}

#[derive(Clone, Debug)]
pub struct Use(pub Path, pub Ident);

#[derive(Clone, Debug, Default)]
pub struct UseItem(pub Vec<Use>);

// INPUTS:
// a::b::{a::{}, b}
fn parse_use_segment(
    parent: &Path,
    input: ParseStream,
    output: &mut Vec<Use>,
    inner: bool,
) -> Result<()> {
    let mut path = parent.clone();
    let end = || {
        Ok(if input.peek(Token![;]) {
            if inner {
                return Err(input.error("expected ident, `,`, `::` or `{`"));
            } else {
                true
            }
        } else {
            input.is_empty()
        })
    };
    loop {
        if end()? {
            break;
        } else if input.peek(Brace) {
            // A group
            let inner;
            braced!(inner in input);
            parse_use_segment(&path, &inner, output, true)?;
            // A group can only be at the end of a path
            if end()? {
                break;
            } else {
                <Token![,]>::parse(input)?;
                path = parent.clone();
            }
        } else {
            path.push(input.parse()?);

            if <Token![,]>::parse(input).is_ok() || end()? {
                // Last path segment was target of use
                if path.pop_self() {
                    output.push(Use(path.clone(), path.get_ident()?.clone()));
                } else {
                    output.push(Use(path.clone(), path.pop_ident()?));
                }
                if !end()? {
                    path = parent.clone();
                }
            } else if <Token![as]>::parse(input).is_ok() {
                let was_self = path.pop_self();
                // Last path segment was aliased
                output.push(Use(path.clone(), input.parse()?));
                if !was_self {
                    path.pop();
                }
                if end()? {
                    break;
                } else {
                    <Token![,]>::parse(input)?;
                    path = parent.clone();
                }
            } else {
                <Token![::]>::parse(input)?;
            }
        }
    }
    Ok(())
}

impl Parse for UseItem {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.is_empty() {
            return Ok(Self::default());
        }
        let mut output = Vec::new();
        <Token![use]>::parse(input)?;
        Option::<Token![::]>::parse(input)?;

        parse_use_segment(&Default::default(), input, &mut output, false)?;

        <Token![;]>::parse(input)?;

        Ok(Self(output))
    }
}

#[cfg(test)]
mod test {
    use pretty_assertions::assert_eq;
    use quote::ToTokens;
    use syn::{parse::Parser, parse_str};

    use super::*;

    macro_rules! assert_use_item {
        ($use:literal, $($path:literal as $ident:ident),* $(,)*) => {
            let UseItem(uses) = parse_str($use).unwrap();
            let mut uses = uses.into_iter();
            $(
                let Use(path, ident) = uses.next().unwrap();
                assert_eq!(path.into_token_stream().to_string().replace(' ', ""), $path);
                assert_eq!(ident, stringify!($ident));
            )*
        };
    }

    #[test]
    fn use_item() {
        assert_use_item!("use ::a::b;", "::a::b" as b);
        assert_use_item!(
            "use a::{c, self, b};",
            "::a::c" as c,
            "::a" as a,
            "::a::b" as b
        );
        assert_use_item!("use a::{self as c, b as a};", "::a" as c, "::a::b" as a);
        assert_use_item!(
            "use a::{b::{a, b}, c};",
            "::a::b::a" as a,
            "::a::b::b" as b,
            "::a::c" as c
        );
        assert_use_item!("use #var::a;", "#var::a" as a);
        assert_use_item!("use ::a::#var::a;", "::a::#var::a" as a);
        assert_use_item!("use ::a::#var as a;", "::a::#var" as a);
    }

    macro_rules! assert_error {
        ($use:literal) => {
            UseItem::parse.parse_str($use).unwrap_err();
        };
    }

    #[test]
    fn error() {
        assert_error!("use ::a::#b;");
    }
}