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
extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro_error::abort;
use quote::quote;
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    spanned::Spanned,
    Error, Ident, LitStr, Pat, PatIdent, Result,
};

struct MacroInput {
    use_std: bool,
    pat: Pat,
}

impl Parse for MacroInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let std_mode: Ident = input.parse()?;
        let pat = input.parse()?;

        Ok(Self {
            use_std: if std_mode == "std" {
                true
            } else if std_mode == "no_std" {
                false
            } else {
                return Err(Error::new_spanned(std_mode, ""));
            },
            pat,
        })
    }
}

#[proc_macro_hack::proc_macro_hack]
#[proc_macro_error::proc_macro_error]
pub fn collect_captures(input: TokenStream) -> TokenStream {
    let MacroInput { use_std, pat } = parse_macro_input!(input);

    let mut idents = Vec::new();
    collect_pat_ident(&pat, &mut idents);

    // Check if bound variables are all like `_0`, `_1`, in which case
    // collect them in a tuple
    if let Some(tokens) = check_tuple_captures(&idents) {
        return tokens.into();
    }

    // Decide what to do based on the number of bound variables
    let output = match &idents[..] {
        [] => {
            quote! {()}
        }
        [single] => {
            quote! {#single}
        }
        multi => {
            // `var1`, `var2`, ...
            let idents: Vec<_> = multi.iter().map(|p| p.ident.clone()).collect();

            // `_M_0`, `_M_1`, ...
            let ty_params: Vec<_> = (0..idents.len())
                .map(|i| Ident::new(&format!("_M_{}", i), Span::call_site()))
                .collect();

            // `"var1"`, `"var2"`, ...
            let ident_strs: Vec<_> = idents
                .iter()
                .map(|i| LitStr::new(&format!("{}", i), i.span()))
                .collect();

            let ty_name = Ident::new("__Match", Span::call_site());

            let debug_impl = if use_std {
                let fmt = quote! { ::std::fmt };
                quote! {
                    impl<#(#ty_params),*> #fmt::Debug for #ty_name<#(#ty_params),*>
                    where
                        #(#ty_params: #fmt::Debug),*
                    {
                        fn fmt(&self, f: &mut #fmt::Formatter<'_>) -> #fmt::Result {
                            f.debug_struct("<anonymous>")
                                #(.field(#ident_strs, &self.#idents))*
                                .finish()
                        }
                    }
                }
            } else {
                quote! {}
            };

            quote! {{
                #[derive(Clone, Copy)]
                struct #ty_name<#(#ty_params),*> {
                    #(
                        #idents: #ty_params
                    ),*
                }

                #debug_impl

                #ty_name { #(#idents),* }
            }}
        }
    };

    TokenStream::from(output)
}

/// Check if `idents` contains a tuple binding (e.g., `_4`). If it does, returns
/// a `TokenStream` that collects the bound variables (e.g., `(_0, _1)`).
fn check_tuple_captures(idents: &Vec<&PatIdent>) -> Option<proc_macro2::TokenStream> {
    let mut some_tuple_cap = None;
    let mut some_non_tuple_cap = None;

    let mut indices: Vec<(u128, &Ident)> = idents
        .iter()
        .map(|i| {
            let index = {
                let text = i.ident.to_string();
                if text.starts_with("_") {
                    // assuming the index fits in `u128`...
                    text[1..].parse().ok()
                } else {
                    None
                }
            };

            if let Some(index) = index {
                some_tuple_cap = Some(*i);
                (index, &i.ident)
            } else {
                some_non_tuple_cap = Some(*i);
                (0 /* dummy */, &i.ident)
            }
        })
        .collect();

    if let (Some(i1), Some(i2)) = (some_tuple_cap, some_non_tuple_cap) {
        abort!(
            i1.span(),
            "can't have both of a tuple binding `{}` and a non-tuple binding \
             `{}` at the same time",
            i1.ident,
            i2.ident
        );
    }

    if some_tuple_cap.is_some() {
        // Create a reverse map from tuple fields to bound variables
        indices.sort_unstable_by_key(|e| e.0);

        for (&(ind, ref ident), i) in indices.iter().zip(0u128..) {
            if ind > i {
                if ind - 1 == i {
                    abort!(
                        ident.span(),
                        "non-contiguous tuple binding: `_{}` is missing",
                        ind - 1
                    );
                } else {
                    abort!(
                        ident.span(),
                        "non-contiguous tuple binding: `_{}` .. `_{}` are missing",
                        i,
                        ind - 1
                    );
                }
            } else if ind < i {
                assert_eq!(i - 1, ind);
                abort!(
                    ident.span(),
                    "duplicate tuple binding: `_{}` is defined for multiple times",
                    ind
                );
            }
        }

        // `var1`, `var2`, ...
        let idents: Vec<_> = indices.into_iter().map(|p| p.1).collect();

        Some(quote! { ( #(#idents),* ) })
    } else {
        None
    }
}

fn collect_pat_ident<'a>(pat: &'a Pat, out: &mut Vec<&'a PatIdent>) {
    match pat {
        Pat::Box(pat) => collect_pat_ident(&pat.pat, out),
        Pat::Ident(pat) => {
            out.push(pat);
            if let Some((_, subpat)) = &pat.subpat {
                collect_pat_ident(&subpat, out);
            }
        }
        Pat::Lit(_) => {}
        Pat::Macro(_) => {}
        Pat::Or(pat) => {
            for case in pat.cases.iter() {
                collect_pat_ident(&case, out);
            }
        }
        Pat::Path(_) => {}
        Pat::Range(_) => {}
        Pat::Reference(pat) => collect_pat_ident(&pat.pat, out),
        Pat::Rest(_) => {}
        Pat::Slice(pat) => {
            for elem in pat.elems.iter() {
                collect_pat_ident(&elem, out);
            }
        }
        Pat::Struct(pat) => {
            for field in pat.fields.iter() {
                collect_pat_ident(&field.pat, out);
            }
        }
        Pat::Tuple(pat) => {
            for elem in pat.elems.iter() {
                collect_pat_ident(&elem, out);
            }
        }
        Pat::TupleStruct(pat) => {
            for elem in pat.pat.elems.iter() {
                collect_pat_ident(&elem, out);
            }
        }
        Pat::Type(pat) => collect_pat_ident(&pat.pat, out),
        Pat::Wild(_) => {}
        // `Pat` can't be covered exhaustively
        Pat::Verbatim(_) | _ => abort!(pat.span(), "unsupported pattern"),
    }
}