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
//! Proc-macros for [`quote-use`](https://docs.rs/quote-use/).

use proc_macro2::{Punct, Spacing, TokenStream, TokenTree};
use quote::{format_ident, quote, ToTokens};
use syn::parse::{Parse, ParseStream};
#[cfg(feature = "namespace_idents")]
use syn::LitStr;
use syn::{parse_macro_input, Expr, Result, Token};
use use_parser::{Use, UseItem};

mod prelude;

mod use_parser;

/// [`quote!`] replacement that allows [using](https://doc.rust-lang.org/std/keyword.use.html) paths to be
/// automaticly replaced.
///
/// It supports both the explicit use via `use some::path::Type;` and the use of
/// the rust prelude:
/// ```
/// # use quote_use::quote_use;
/// quote_use! {
///     ## use std::fs::read;
///
///     read("src/main.rs")
///
///     Some(20)
/// }
/// # ;
/// ```
#[proc_macro]
pub fn quote_use(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let uses = parse_macro_input!(input as QuoteUse);

    quote! {
        ::quote_use::__private::quote::quote!{
            #uses
        }
    }
    .into()
}

/// Like [`quote_use!`] but using [`quote_spanned!`](quote::quote_spanned)
/// ```
/// # use quote_use::quote_spanned_use;
/// # use proc_macro2::Span;
/// #
/// # let span = Span::call_site();
/// quote_spanned_use! {span=>
///     ## use std::fs::read;
///
///     read("src/main.rs")
///
///     Some(20)
/// }
/// # ;
/// ```
#[proc_macro]
pub fn quote_spanned_use(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let UsesSpanned(spanned, uses) = parse_macro_input!(input as UsesSpanned);

    quote! {
        ::quote_use::__private::quote::quote_spanned!{
            #spanned
            #uses
        }
    }
    .into()
}

/// Like [`quote_use!`] but using [`parse_quote!`](syn::parse_quote!)
/// ```
/// # use quote_use::parse_quote_use;
/// # use syn::{Expr, parse_quote};
/// # use quote::ToTokens;
/// #
/// let expr: Expr = parse_quote_use!{
///     ## use std::fs::read;
///     
///     read("src/main.rs")
/// }
/// # ;
/// # let expected: Expr = parse_quote!(::std::fs::read("src/main.rs"));
/// # assert_eq!{
/// #   expr.to_token_stream().to_string(),
/// #   expected.to_token_stream().to_string()
/// # };
/// ```
#[proc_macro]
pub fn parse_quote_use(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let uses = parse_macro_input!(input as QuoteUse);

    quote! {
        ::quote_use::__private::syn::parse_quote!{
            #uses
        }
    }
    .into()
}

/// Like [`quote_spanned_use!`] but using
/// [`parse_quote_spanned!`](syn::parse_quote_spanned)
/// ```
/// # use quote_use::parse_quote_spanned_use;
/// # use syn::{parse_quote_spanned, Expr, spanned::Spanned};
/// # use proc_macro2::Span;
/// # use quote::ToTokens;
/// #
/// # let span = Span::call_site();
/// let expr: Expr = parse_quote_spanned_use!{span=>
///     ## use std::fs::read;
///     
///     read("src/main.rs")
/// }
/// # ;
/// # let expected: Expr = parse_quote_spanned!(span=> ::std::fs::read("src/main.rs"));
/// # assert_eq!{
/// #   expr.to_token_stream().to_string(),
/// #   expected.to_token_stream().to_string()
/// # };
/// ```
#[proc_macro]
pub fn parse_quote_spanned_use(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let UsesSpanned(spanned, uses) = parse_macro_input!(input as UsesSpanned);

    quote! {
        ::quote_use::__private::syn::parse_quote_spanned!{
            #spanned
            #uses
        }
    }
    .into()
}

/// [`format_ident!`](quote::format_ident) replacement that allows the auto
/// namespacing matching the `quote!` macros of this crate.
/// ```
/// # use quote_use::format_ident_namespaced;
/// format_ident_namespaced!("$ident_{}", 2usize)
/// # ;
/// ```
#[proc_macro]
#[cfg(feature = "namespace_idents")]
pub fn format_ident_namespaced(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let format_input = parse_macro_input!(input as FormatInput);

    quote! {
        ::quote_use::__private::quote::format_ident!(#format_input)
    }
    .into()
}

#[cfg(feature = "namespace_idents")]
struct FormatInput(LitStr, TokenStream);
#[cfg(feature = "namespace_idents")]
impl Parse for FormatInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let lit = input.parse()?;

        Ok(Self(lit, input.parse()?))
    }
}
#[cfg(feature = "namespace_idents")]
impl ToTokens for FormatInput {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self(lit, tail) = self;

        let lit_span = lit.span();

        if let Some(lit) = lit.value().strip_prefix('$') {
            LitStr::new(&format!("{}{}", ident_prefix(), lit), lit_span).to_tokens(tokens);
        } else {
            lit.to_tokens(tokens)
        };

        tail.to_tokens(tokens);
    }
}

#[cfg(feature = "namespace_idents")]
fn ident_prefix() -> String {
    if let Ok(crate_name) = std::env::var("CARGO_PKG_NAME") {
        format!("__{}_", crate_name.replace('-', "_"))
    } else {
        String::from("___procmacro_")
    }
}

struct UsesSpanned(TokenStream, QuoteUse);
impl Parse for UsesSpanned {
    fn parse(input: ParseStream) -> Result<Self> {
        let expr = Expr::parse(input)?;
        let arrow = <Token!(=>)>::parse(input)?;

        Ok(Self(quote!(#expr #arrow), QuoteUse::parse(input)?))
    }
}

struct QuoteUse(Vec<Use>, TokenStream);
impl Parse for QuoteUse {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut uses = Vec::new();
        while input.peek(Token![#]) && input.peek2(Token![use]) {
            input.parse::<Token![#]>().expect("# was peeked before");
            uses.extend_from_slice(&UseItem::parse(input)?.0);
        }

        Ok(QuoteUse(uses, input.parse()?))
    }
}

impl ToTokens for QuoteUse {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self(uses, tail) = self;
        let mut uses = uses.to_vec();
        uses.extend(prelude::prelude());

        #[cfg(feature = "namespace_idents")]
        let ident_prefix = Some(ident_prefix());

        #[cfg(not(feature = "namespace_idents"))]
        let ident_prefix: Option<String> = None;

        tokens.extend(replace_in_group(
            &uses,
            tail.clone(),
            ident_prefix.as_deref(),
        ));
    }
}

fn replace_in_group(uses: &[Use], tokens: TokenStream, ident_prefix: Option<&str>) -> TokenStream {
    use State::*;
    #[derive(Clone, Copy)]
    enum State {
        Path,
        Pound,
        Dollar,
        DollarQuote,
        Normal,
    }
    impl ToTokens for State {
        fn to_tokens(&self, tokens: &mut TokenStream) {
            match self {
                Path | Normal | Pound => {}
                Dollar => quote!($).to_tokens(tokens),
                DollarQuote => unreachable!("lifetime `'` must be followed by ident"),
            }
        }
    }
    let mut state = Normal;

    tokens
        .into_iter()
        .flat_map(|token| {
            let mut prev = Normal;
            match (&token, state) {
                (TokenTree::Ident(ident), Dollar) if ident != "crate" => {
                    state = Normal;
                    return format_ident!("{}{ident}", ident_prefix.expect("ident prefix is set"))
                        .into_token_stream();
                }
                (TokenTree::Ident(ident), DollarQuote) => {
                    state = Normal;
                    return [
                        TokenTree::from(Punct::new('\'', Spacing::Joint)),
                        format_ident!("{}{ident}", ident_prefix.expect("ident prefix is set"))
                            .into(),
                    ]
                    .into_iter()
                    .collect();
                }
                (TokenTree::Ident(ident), Normal) => {
                    if let Some(Use(path, _)) = uses.iter().find(|item| &item.1 == ident) {
                        return quote!(#path);
                    }
                }
                // first colon
                (TokenTree::Punct(punct), _)
                    if punct.spacing() == Spacing::Joint && punct.as_char() == ':' =>
                {
                    prev = state;
                    state = Path;
                }
                // second colon
                (TokenTree::Punct(punct), _) if punct.as_char() == ':' => (),
                // quote var `#ident`
                (TokenTree::Punct(punct), _) if punct.as_char() == '#' => {
                    prev = state;
                    state = Pound;
                }
                // $$ escapes to just $
                (TokenTree::Punct(punct), Dollar) if punct.as_char() == '$' => {
                    state = Normal;
                }
                (TokenTree::Punct(punct), Normal | Pound | Path)
                    if punct.as_char() == '$' && ident_prefix.is_some() =>
                {
                    state = Dollar;
                    return quote!();
                }
                (TokenTree::Punct(punct), Dollar)
                    if punct.as_char() == '\'' && ident_prefix.is_some() =>
                {
                    state = DollarQuote;
                    return quote!();
                }
                (TokenTree::Group(group), _) => {
                    let tokens = replace_in_group(uses, group.stream(), ident_prefix);
                    return match group.delimiter() {
                        proc_macro2::Delimiter::Parenthesis => quote!((#tokens)),
                        proc_macro2::Delimiter::Brace => quote!({#tokens}),
                        proc_macro2::Delimiter::Bracket => quote!([#tokens]),
                        proc_macro2::Delimiter::None => tokens,
                    };
                }
                _ => {
                    prev = state;
                    state = Normal;
                }
            };
            quote!(#prev #token)
        })
        .collect()
}