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
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};
#[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<_>>();
permutations.push(impl_fields(&fields, &input.ident));
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 {
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
}))
}
}