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
#[allow(unused_imports)]
use {
    ::core::{
        ops::Not as _,
    },
    ::proc_macro::{*,
        TokenStream,
    },
};

#[proc_macro_attribute] pub
fn named (
    params: TokenStream,
    input: TokenStream,
) -> TokenStream
{
    named_impl(params.into(), input.into())
        .unwrap_or_else(|err| {
            let err = Some(TokenTree::from(Literal::string(err)));
            quote!(
                ::core::compile_error! { #err }
            )
        })
        .into()
}

fn named_impl (
    params: TokenStream,
    input: TokenStream,
) -> Result<TokenStream, &'static str>
{
    // parse::Nothing for `params`.
    if let Some(_) = params.into_iter().next() {
        return Err("unexpected attribute arguments".into());
    }

    let ref mut tts = input.into_iter().peekable();

    let mut input = Vec::<TokenTree>::new();

    // `#` `[…]` attributes:
    while matches!(tts.peek(), Some(TokenTree::Punct(p)) if p.as_char() == '#') {
        input.extend(tts.take(2));
    }

    // rest but scan the tt right after `fn`.
    let fname = loop {
        let tt = tts.next().unwrap();
        if matches!(tt, TokenTree::Ident(ref ident) if ident.to_string() == "fn") {
            input.push(tt);
            let fname = tts.peek().unwrap().to_string();
            input.extend(tts);
            break Some(TokenTree::from(Literal::string(&fname)));
        }
        input.push(tt);
    };

    let g = match input.last_mut() {
        | Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace => g,
        | _ => return Err("expected a `fn`"),
    };
    let g_span = g.span();
    *g = Group::new(g.delimiter(), {
        let mut body = quote!(
            macro_rules! function_name {() => (
                #fname
            )}
        );
        body.extend(g.stream());
        body
    });
    g.set_span(g_span);
    Ok(input.into_iter().collect())
}

/// Mini `quote!` implementation,
/// can only interpolate `impl IntoIterator<Item = TokenTree>`.
macro_rules! quote_ {
    (
        @$q:tt
        { $($code:tt)* } $($rest:tt)*
    ) => (
        $q.push(
            TokenTree::Group(Group::new(
                Delimiter::Brace,
                quote!($($code)*)
            ))
        );
        quote!(@$q $($rest)*);
    );

    (
        @$q:tt
        [ $($code:tt)* ]
        $($rest:tt)*
    ) => (
        $q.push(
            TokenTree::Group(Group::new(
                Delimiter::Bracket,
                quote!($($code)*)
            ))
        );
        quote!(@$q $($rest)*);
    );

    (
        @$q:tt
        ( $($code:tt)* )
        $($rest:tt)*
    ) => (
        $q.push(
            TokenTree::Group(Group::new(
                Delimiter::Parenthesis,
                quote!($($code)*)
            ))
        );
        quote!(@$q $($rest)*);
    );

    (
        @$q:tt
        #$var:ident
        $($rest:tt)*
    ) => (
        $q.extend($var);
        quote!(@$q $($rest)*);
    );

    (
        @$q:tt
        $tt:tt $($rest:tt)*
    ) => (
        $q.extend(
            stringify!($tt)
                .parse::<TokenStream>()
                .unwrap()
        );
        quote!(@$q $($rest)*);
    );

    (
        @$q:tt
        /* nothign left */
    ) => ();

    (
        $($code:tt)*
    ) => ({
        let mut _q = Vec::<TokenTree>::new();
        quote!(@_q $($code)*);
        _q.into_iter().collect::<TokenStream>()
    });
} use quote_ as quote;