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
//! Traits transforming types from tuples

extern crate proc_macro;

use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use std::collections::HashSet;
use syn::{parse_macro_input, Data, DeriveInput, Error, Field};

/// Derive `From` tuples for `struct`s  that have unique field types.
///
/// Because of the restriction that field types must be unique, this derive
/// works best with structs that utilize [newtypes] for data.  Examples of
/// where this may be common is with http request parameters, or web form
/// inputs.
///
/// [newtypes]: https://doc.rust-lang.org/rust-by-example/generics/new_types.html
/// [`From`]: https://doc.rust-lang.org/core/convert/trait.From.html
///
/// # Example
///
/// ```
/// use from_tuple::FromTuple;
///
/// #[derive(FromTuple)]
/// struct Hello {
///     message: String,
///     time: i32,
///     counter: usize
/// }
///
/// fn main() {
///     let h1: Hello = ("world".into(), -1, 42usize).into();
///     assert_eq!(h1.time, -1);
///     assert_eq!(h1.counter, 42);
///     assert_eq!(&h1.message, "world");
///
///     let h2: Hello = (1_000_000_usize, i32::min_value(), "greetings".into()).into();
///     assert_eq!(h2.time, i32::min_value());
///     assert_eq!(h2.counter, 1_000_000);
///     assert_eq!(&h2.message, "greetings");
///
///     let h3: Hello = (-42, "hi".into(), 0usize).into();
///     assert_eq!(h3.time, -42);
///     assert_eq!(h3.counter, 0);
///     assert_eq!(&h3.message, "hi");
///
/// }
/// ```
///
/// ## Non-unique structs
///
/// Structs that have non-unique field types will fail to compile.  This is based
/// on the actual type, and not the alias, so it will fail on e.g. [`c_uchar`]
/// and [`u8`].
///
/// [`c_uchar`]: https://doc.rust-lang.org/std/os/raw/type.c_uchar.html
/// [`u8`]: https://doc.rust-lang.org/std/primitive.u8.html
///
/// ```compile_fail
/// use from_tuple::FromTuple;
///
/// #[derive(FromTuple)]
/// struct NonUnique {
///     first: String,
///     index: usize,
///     second: String,
/// }
/// ```
///
/// Attempting to compile the previous example will result in
///
/// ```bash
/// error: Field types must be unique in a struct deriving `FromTuple`
///   --> src/lib.rs:41:5
///    |
/// 10 |     second: String,
///    |     ^^^^^^^^^^^^^^
/// ```
///
/// ### Considerations
///
/// Support for non-unique types is under consideration for a future version,
/// but has not been implemented because it requires order-dependant fields for
/// structs - a *surprising* behaviour and can accidentally be broken by adding
/// a field in the wrong position unknowingly.
///
/// Requiring unique types may also be *surprising* behaviour, but is able to
/// be caught at compile time easily.  Additionally, I (personally) find it
/// less *surprising* than it being order-dependant.
#[proc_macro_derive(FromTuple)]
pub fn from_tuple(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let derived = parse_macro_input!(input as DeriveInput);
    match do_from_tuple(derived) {
        Ok(ts) => ts,
        Err(e) => e.to_compile_error(),
    }
    .into()
}

fn do_from_tuple(input: DeriveInput) -> syn::Result<TokenStream> {
    let mut permutations = Vec::new();

    if let Data::Struct(r#struct) = input.data {
        check_for_unique_fields(r#struct.fields.iter())?;

        let mut idx = 0;
        let mut stack = vec![0; r#struct.fields.len()];
        let mut fields = r#struct.fields.iter().collect::<Vec<_>>();

        // the first permutation is just the unmodified field order
        permutations.push(impl_fields(&fields, &input.ident));

        // heap's algorithm for generating all permutations
        while idx < fields.len() {
            if stack[idx] < idx {
                if idx % 2 == 0 {
                    fields.swap(0, idx);
                } else {
                    fields.swap(stack[idx], idx);
                }

                stack[idx] += 1;
                idx = 0;

                permutations.push(impl_fields(&fields, &input.ident));
            } else {
                stack[idx] = 0;
                idx += 1;
            }
        }
    } else {
        return Err(Error::new_spanned(
            input,
            "FromTuple currently only supports Struct",
        ));
    }

    Ok(quote! { #(#permutations)* })
}

fn impl_fields(fields: &[&Field], impl_for: &Ident) -> TokenStream {
    // variables used for destructuring the tuple
    let dvars = (0..fields.len())
        .map(|i| Ident::new(&format!("d{}", i), Span::call_site()))
        .collect::<Vec<_>>();

    let idents = fields.iter().map(|&f| f.ident.as_ref());
    let types = fields.iter().map(|&f| &f.ty);

    let destruct = quote! { (#(#dvars), *) };
    let tuple = quote! { (#(#types),*) };
    quote! {
        impl From<#tuple> for #impl_for {
            #[inline]
            fn from(#destruct: #tuple) -> Self {
                Self {
                    #(#idents: #dvars),*
                }
            }
        }
    }
}

fn check_for_unique_fields<'a>(fields: impl Iterator<Item = &'a Field>) -> syn::Result<()> {
    let mut seen = HashSet::new();
    let mut repeats = Vec::new();
    for field in fields {
        if !seen.insert(field.ty.clone()) {
            repeats.push(Error::new_spanned(
                field,
                "Field types must be unique in a struct deriving `FromTuple`",
            ))
        }
    }

    if repeats.len() == 0 {
        Ok(())
    } else {
        let mut repeats = repeats.into_iter();
        let first = repeats
            .next()
            .expect("repeats of non 0 length, but no first value");

        Err(repeats.fold(first, |mut errors, error| {
            errors.combine(error);
            errors
        }))
    }
}