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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
//! Utilities for extracting specific types of fields.
use proc_macro2::Span;
use sealed::sealed;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{
Data, DataEnum, DataStruct, DataUnion, Error, Field, Fields, FieldsNamed, FieldsUnnamed, Token,
};
type PunctuatedFields = Punctuated<Field, Token![,]>;
/// Convert this rejection to/into a [`syn::Error`].
#[sealed]
pub trait ToSynError {
/// Convert this rejection to a [`syn::Error`].
fn to_syn_err(&self) -> Error;
/// Convert this rejection into a [`syn::Error`].
#[inline]
fn into_syn_err(self) -> Error
where
Self: Sized,
{
self.to_syn_err()
}
}
/// [`Data`] extensions.
#[sealed]
pub trait DataExtractExt {
/// Extract a union from a [`DeriveInput`](syn::DeriveInput)'s data.
///
/// # Errors
/// If there's a container mismatch.
///
/// # Example
///
/// ```
/// # use macroific_core::extract_fields::*;
/// # use syn::{DeriveInput, parse_quote};
///
/// let input: DeriveInput = parse_quote!(struct MyStruct;);
/// let err: syn::Error = input.data.extract_union().unwrap_err().into();
/// assert_eq!(err.to_string(), "Only unions supported");
///
/// let input: DeriveInput = parse_quote!(union MyUnion { foo: u8 });
/// input.data.extract_union().unwrap(); // Ok
/// ```
fn extract_union(self) -> Result<DataUnion, Rejection<DataStruct, DataEnum>>;
/// Extract a struct from a [`DeriveInput`](syn::DeriveInput)'s data.
///
/// # Errors
/// If there's a container mismatch.
///
/// # Example
///
/// ```
/// # use macroific_core::extract_fields::*;
/// # use syn::{DeriveInput, parse_quote};
///
/// let input: DeriveInput = parse_quote!(enum MyEnum { Foo });
/// let err: syn::Error = input.data.extract_struct().unwrap_err().into();
/// assert_eq!(err.to_string(), "Only structs supported");
///
/// let input: DeriveInput = parse_quote!(struct MyStruct;);
/// input.data.extract_struct().unwrap(); // Ok
/// ```
fn extract_struct(self) -> Result<DataStruct, Rejection<DataEnum, DataUnion>>;
/// Extract an enum from a [`DeriveInput`](syn::DeriveInput)'s data.
///
/// # Errors
/// If there's a container mismatch.
///
/// ```
/// # use macroific_core::extract_fields::*;
/// # use syn::{DeriveInput, parse_quote};
///
/// let input: DeriveInput = parse_quote!(struct MyStruct;);
/// let err: syn::Error = input.data.extract_enum().unwrap_err().into();
/// assert_eq!(err.to_string(), "Only enums supported");
///
/// let input: DeriveInput = parse_quote!(enum MyEnum { Foo });
/// input.data.extract_enum().unwrap(); // Ok
/// ```
fn extract_enum(self) -> Result<DataEnum, Rejection<DataStruct, DataUnion>>;
/// [`extract_struct`](crate::extract_fields::DataExtractExt::extract_struct) and then
/// [`extract_any_fields`](FieldsExtractExt::extract_any_fields).
///
/// # Errors
/// If there's a container mismatch.
///
/// # Example
///
/// ```
/// # use macroific_core::extract_fields::*;
/// # use syn::{DeriveInput, Fields, parse_quote};
/// #
/// let input: DeriveInput = parse_quote!(struct Foo { foo: u8 });
/// assert!(input.data.extract_struct_fields().is_ok());
///
/// let input: DeriveInput = parse_quote!(struct Foo;);
/// let err: syn::Error = input.data.extract_struct_fields().unwrap_err().into();
/// assert_eq!(err.to_string(), "Unit structs not supported");
///
/// let input: DeriveInput = parse_quote!(enum Foo { A(u8) });
/// let err: syn::Error = input.data.extract_struct_fields().unwrap_err().into();
/// assert_eq!(err.to_string(), "Only structs supported");
/// ```
fn extract_struct_fields(self) -> syn::Result<PunctuatedFields>
where
Self: Sized,
{
self.extract_struct()?.fields.extract_any_fields()
}
/// [`extract_struct`](DataExtractExt::extract_struct) and then
/// [`extract_named_fields`](FieldsExtractExt::extract_named_fields).
///
/// # Errors
/// If there's a container mismatch.
///
/// # Example
///
/// ```
/// # use macroific_core::extract_fields::*;
/// # use syn::{DeriveInput, Fields, parse_quote};
/// #
/// let input: DeriveInput = parse_quote!(struct Foo { foo: u8 });
/// assert!(input.data.extract_struct_named().is_ok());
///
/// let input: DeriveInput = parse_quote!(struct Foo(u8););
/// let err: syn::Error = input.data.extract_struct_named().unwrap_err().into();
/// assert_eq!(err.to_string(), "Only named fields supported");
///
/// let input: DeriveInput = parse_quote!(enum Foo { A(u8) });
/// let err: syn::Error = input.data.extract_struct_named().unwrap_err().into();
/// assert_eq!(err.to_string(), "Only structs supported");
/// ```
fn extract_struct_named(self) -> syn::Result<PunctuatedFields>
where
Self: Sized,
{
self.extract_struct()
.map_err(Error::from)?
.fields
.extract_named_fields()
.map_err(Error::from)
}
/// [`extract_struct`](DataExtractExt::extract_struct) and then
/// [`extract_unnamed_fields`](FieldsExtractExt::extract_unnamed_fields).
///
/// # Errors
/// If there's a container mismatch.
///
/// # Example
///
/// ```
/// # use macroific_core::extract_fields::*;
/// # use syn::{DeriveInput, Fields, parse_quote};
/// #
/// let input: DeriveInput = parse_quote!(struct Foo(u8););
/// assert!(input.data.extract_struct_unnamed().is_ok());
///
/// let input: DeriveInput = parse_quote!(struct Foo { foo: u8 });
/// let err: syn::Error = input.data.extract_struct_unnamed().unwrap_err().into();
/// assert_eq!(err.to_string(), "Only unnamed fields supported");
///
/// let input: DeriveInput = parse_quote!(enum Foo { A(u8) });
/// let err: syn::Error = input.data.extract_struct_unnamed().unwrap_err().into();
/// assert_eq!(err.to_string(), "Only structs supported");
/// ```
fn extract_struct_unnamed(self) -> syn::Result<PunctuatedFields>
where
Self: Sized,
{
self.extract_struct()
.map_err(Error::from)?
.fields
.extract_unnamed_fields()
.map_err(Error::from)
}
}
#[sealed]
impl DataExtractExt for Data {
fn extract_union(self) -> Result<DataUnion, Rejection<DataStruct, DataEnum>> {
match self {
Data::Struct(data) => Err(Rejection::A(data)),
Data::Enum(data) => Err(Rejection::B(data)),
Data::Union(data) => Ok(data),
}
}
fn extract_struct(self) -> Result<DataStruct, Rejection<DataEnum, DataUnion>> {
match self {
Data::Struct(data) => Ok(data),
Data::Enum(data) => Err(Rejection::A(data)),
Data::Union(data) => Err(Rejection::B(data)),
}
}
fn extract_enum(self) -> Result<DataEnum, Rejection<DataStruct, DataUnion>> {
match self {
Data::Struct(data) => Err(Rejection::A(data)),
Data::Enum(data) => Ok(data),
Data::Union(data) => Err(Rejection::B(data)),
}
}
}
/// [`Fields`] extensions
#[sealed]
pub trait FieldsExtractExt {
/// Extract named fields from [`Fields`]. `()` is returned for unit structs.
///
/// # Errors
/// If the fields are unnamed, `Err(Rejection::A)` is returned. If the fields are unit,
/// `Err(Rejection::B)` is returned.
///
/// # Example
///
/// ```
/// # use macroific_core::extract_fields::*;
/// # use syn::{Fields, parse_quote};
/// #
/// let input = Fields::Unnamed(parse_quote!((u8)));
/// let err: syn::Error = input.extract_named_fields().unwrap_err().into();
///
/// assert_eq!(err.to_string(), "Only named fields supported");
///
/// let input = Fields::Named(parse_quote!({ bar: u8 }));
/// input.extract_named_fields().unwrap(); // Ok
/// ```
fn extract_named_fields(self) -> Result<PunctuatedFields, Rejection<FieldsUnnamed, ()>>;
/// Extract unnamed fields from [`Fields`]. `()` is returned for unit structs.
///
/// # Errors
/// If the fields are named, `Err(Rejection::A)` is returned. If the fields are unit,
/// `Err(Rejection::B)` is returned.
///
/// # Example
///
/// ```
/// # use macroific_core::extract_fields::*;
/// # use syn::{Fields, parse_quote};
/// #
/// let input = Fields::Named(parse_quote!({ bar: u8 }));
/// let err: syn::Error = input.extract_unnamed_fields().unwrap_err().into();
/// assert_eq!(err.to_string(), "Only unnamed fields supported");
///
/// let input = Fields::Unnamed(parse_quote!((u8)));
/// input.extract_unnamed_fields().unwrap(); // Ok
/// ```
fn extract_unnamed_fields(self) -> Result<PunctuatedFields, Rejection<FieldsNamed, ()>>;
/// Extract named or unnamed fields
///
/// # Errors
/// If it's a unit struct
///
/// # Example
///
/// ```
/// # use macroific_core::extract_fields::*;
/// # use syn::Fields;
/// #
/// let err: syn::Error = Fields::Unit.extract_any_fields().unwrap_err().into();
/// assert_eq!(err.to_string(), "Unit structs not supported");
/// ```
fn extract_any_fields(self) -> syn::Result<PunctuatedFields>
where
Self: Sized,
{
match self.extract_named_fields() {
Ok(fields) => Ok(fields),
Err(Rejection::A(fields)) => Ok(fields.unnamed),
Err(e) => Err(Error::new(
e.into_syn_err().span(),
"Unit structs not supported",
)),
}
}
}
#[sealed]
impl FieldsExtractExt for Fields {
/// Extract named fields from [`Fields`]. `()` is returned for unit structs.
fn extract_named_fields(self) -> Result<PunctuatedFields, Rejection<FieldsUnnamed, ()>> {
match self {
Fields::Named(fields) => Ok(fields.named),
Fields::Unnamed(fields) => Err(Rejection::A(fields)),
Fields::Unit => Err(Rejection::B(())),
}
}
/// Extract unnamed fields from [`Fields`]. `()` is returned for unit structs.
fn extract_unnamed_fields(self) -> Result<PunctuatedFields, Rejection<FieldsNamed, ()>> {
match self {
Fields::Named(fields) => Err(Rejection::A(fields)),
Fields::Unnamed(fields) => Ok(fields.unnamed),
Fields::Unit => Err(Rejection::B(())),
}
}
}
/// One of two error states
#[allow(missing_docs)]
#[derive(Debug, Eq, PartialEq)]
pub enum Rejection<A, B> {
A(A),
B(B),
}
impl<A, B> From<Rejection<A, B>> for Error
where
Rejection<A, B>: ToSynError,
{
#[inline]
fn from(value: Rejection<A, B>) -> Self {
value.into_syn_err()
}
}
#[sealed]
impl ToSynError for Rejection<FieldsUnnamed, ()> {
fn to_syn_err(&self) -> Error {
Error::new(
match *self {
Self::A(ref f) => f.span(),
Self::B(()) => Span::call_site(),
},
"Only named fields supported",
)
}
}
#[sealed]
impl ToSynError for Rejection<FieldsNamed, ()> {
fn to_syn_err(&self) -> Error {
Error::new(
match *self {
Self::A(ref f) => f.span(),
Self::B(()) => Span::call_site(),
},
"Only unnamed fields supported",
)
}
}
macro_rules! impl_reject {
($msg: literal => [$a: ty => $p_a: ident, $b: ty => $p_b: ident]) => {
#[sealed]
impl ToSynError for Rejection<$a, $b> {
fn to_syn_err(&self) -> Error {
Error::new(
match self {
Self::A(v) => v.$p_a.span(),
Self::B(v) => v.$p_b.span(),
},
$msg,
)
}
}
};
}
impl_reject!("Only structs supported" => [DataEnum => enum_token, DataUnion => union_token]);
impl_reject!("Only enums supported" => [DataStruct => struct_token, DataUnion => union_token]);
impl_reject!("Only unions supported" => [DataStruct => struct_token, DataEnum => enum_token]);