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
use proc_macro::*;
use z::TokenStreamExt;

#[proc_macro]
pub fn gen_inner(input: TokenStream) -> TokenStream {
    let mut tokens = input.into_iter();
    let crate_path = match tokens.next().unwrap() {
        TokenTree::Group(group) => group.stream(),
        _ => unimplemented!(),
    };

    let mut has_yielded = false;
    let output = out(tokens, &mut has_yielded);
    {
        let mut s = TokenStream::new();

        s.extend(crate_path.clone());
        s.append_colon2();
        s.append_ident("gen");

        s.append({
            let mut s = TokenStream::new();
            s.append_punct('|');
            s.append_ident("mut");
            s.append_ident("yield_");

            if !has_yielded {
                s.append_punct(':');
                s.extend(crate_path);
                s.append_colon2();
                s.append_ident("Yield");
            }

            s.append_punct('|');
            s.append_ident("async");
            s.append({
                let mut s = TokenStream::new();
                s.append_ident("let");
                s.append_ident("v");
                s.append_punct('=');
                s.append_ident("async");

                s.append(output);

                s.append_punct('.');
                s.append_ident("await");
                s.append_punct(';');
                s.append_ident("yield_");
                s.append_punct('.');
                s.append_ident("return_");
                s.append({
                    let mut s = TokenStream::new();
                    s.append_ident("v");
                    Group::new(Delimiter::Parenthesis, s)
                });
                Group::new(Delimiter::Brace, s)
            });
            Group::new(Delimiter::Parenthesis, s)
        });
        s
    }
}

fn out(mut tokens: token_stream::IntoIter, has_yielded: &mut bool) -> Group {
    let mut o = TokenStream::new();

    while let Some(tt) = tokens.next() {
        match tt {
            TokenTree::Ident(name) if name.to_string() == "yield" => {
                *has_yielded = true;
                let mut expr = TokenStream::new();
                for tt in &mut tokens {
                    match tt {
                        TokenTree::Punct(p) if p.as_char() == ';' => break,
                        _ => expr.append(tt),
                    }
                }
                o.append_ident("yield_");
                o.append_punct('.');
                o.append_ident("yield_");
                o.append(Group::new(Delimiter::Parenthesis, expr));
                o.append_punct('.');
                o.append_ident("await");
                o.append_punct(';');
            }
            TokenTree::Group(g) if g.delimiter() == Delimiter::Brace => {
                o.append(out(g.stream().into_iter(), has_yielded));
            }
            _ => o.append(tt),
        }
    }
    Group::new(Delimiter::Brace, o)
}

mod z {
    use super::*;

    pub trait TokenStreamExt {
        fn append<U>(&mut self, token: U)
        where
            U: Into<TokenTree>;

        #[inline]
        fn append_punct(&mut self, ch: char) {
            self.append(Punct::new(ch, Spacing::Alone))
        }

        #[inline]
        fn append_ident(&mut self, name: &str) {
            self.append(Ident::new(name, Span::call_site()))
        }

        #[inline]
        fn append_colon2(&mut self) {
            self.append(Punct::new(':', Spacing::Joint));
            self.append(Punct::new(':', Spacing::Alone));
        }
    }

    impl TokenStreamExt for TokenStream {
        #[inline]
        fn append<U>(&mut self, token: U)
        where
            U: Into<TokenTree>,
        {
            self.extend(std::iter::once(token.into()));
        }
    }
}