aboutsummaryrefslogtreecommitdiff
path: root/src/token_stream.rs
blob: 1bbf431f716d5ed9d159bba0280fe5a02fbb92d0 (plain)
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
use proc_macro2::{Group, Ident, TokenStream, TokenTree};

use crate::iter::IteratorExt;

#[allow(clippy::module_name_repetitions)]
pub trait TokenStreamExt
{
    /// Recursively replaces all occurences of a identifier with a token tree.
    fn replace_ident(
        &self,
        target_ident: &Ident,
        substitution: &TokenTree,
    ) -> TokenStream;
}

impl TokenStreamExt for TokenStream
{
    fn replace_ident(&self, target_ident: &Ident, substitution: &TokenTree)
        -> TokenStream
    {
        recurse_replace_ident(self.clone(), target_ident, substitution, '#')
    }
}

fn recurse_replace_ident(
    token_stream: TokenStream,
    target_ident: &Ident,
    substitution: &TokenTree,
    prefix: char,
) -> TokenStream
{
    let mut prev_token_was_prefix = false;

    token_stream
        .into_iter()
        .windows()
        .filter_map(|(token_tree, next_token_tree)| match token_tree {
            TokenTree::Punct(punct) if punct.as_char() == prefix => {
                if matches!(next_token_tree, Some(TokenTree::Ident(ident)) if &ident == target_ident) {
                    prev_token_was_prefix = true;

                    None
                }
                else {
                    prev_token_was_prefix = false;

                    Some(TokenTree::Punct(punct))
                }
            }
            TokenTree::Ident(ident) if prev_token_was_prefix && &ident == target_ident => {
                prev_token_was_prefix = false;

                Some(substitution.clone())
            }
            TokenTree::Ident(_) if prev_token_was_prefix => {
                prev_token_was_prefix = false;

                Some(substitution.clone())
            }
            TokenTree::Group(group) => {
                prev_token_was_prefix = false;

                Some(TokenTree::Group(Group::new(
                    group.delimiter(),
                    recurse_replace_ident(group.stream(), target_ident, substitution, prefix),
                )))
            }
            tt => {
                prev_token_was_prefix = false;

                Some(tt)
            }
        })
        .collect()
}

#[cfg(test)]
mod tests
{
    extern crate test;

    use std::hint::black_box;

    use proc_macro2::{Punct, Spacing, Span};
    use quote::{format_ident, quote};
    use test::Bencher;

    use super::*;

    #[test]
    fn replace_ident_works()
    {
        let ht = Punct::new('#', Spacing::Alone);

        assert_eq!(
            quote! {
                let abc = #ht xyz;
            }
            .replace_ident(
                &format_ident!("xyz"),
                &TokenTree::Ident(Ident::new("foo", Span::call_site())),
            )
            .to_string(),
            quote! {
                let abc = foo;
            }
            .to_string()
        );

        assert_eq!(
            quote! {
                let abc = (#ht xyz, "123");
            }
            .replace_ident(
                &format_ident!("xyz"),
                &TokenTree::Ident(Ident::new("foo", Span::call_site())),
            )
            .to_string(),
            quote! {
                let abc = (foo, "123");
            }
            .to_string()
        );

        assert_eq!(
            quote! {
                let abc = (hello, "123").iter_map(|_| #ht xyz);
            }
            .replace_ident(
                &format_ident!("xyz"),
                &TokenTree::Ident(Ident::new("foo", Span::call_site())),
            )
            .to_string(),
            quote! {
                let abc = (hello, "123").iter_map(|_| foo);
            }
            .to_string()
        );

        assert_eq!(
            quote! {
                fn #ht xyz(bar: &Bar) {
                    let foo = "baz";

                    foo
                }

                let xyz = "123";

                println!("Hello {}", #ht xyz());
            }
            .replace_ident(
                &format_ident!("xyz"),
                &TokenTree::Ident(Ident::new("foo", Span::call_site())),
            )
            .to_string(),
            quote! {
                fn foo(bar: &Bar) {
                    let foo = "baz";

                    foo
                }

                let xyz = "123";

                println!("Hello {}", foo());
            }
            .to_string()
        );
    }

    #[bench]
    fn bench_replace_ident(bencher: &mut Bencher)
    {
        let ht = Punct::new('#', Spacing::Alone);

        let input_strem = quote! {
            let #ht foo = |abc| {
                let x = "foo";

                let y = a_foo;

                let #ht foo = "Hello";

                #ht foo.to_string()
            };
        };

        bencher.iter(|| {
            input_strem.replace_ident(
                black_box(&format_ident!("foo")),
                black_box(&TokenTree::Ident(format_ident!("foobar"))),
            )
        });
    }
}