-
Notifications
You must be signed in to change notification settings - Fork 24
/
lib.rs
2365 lines (2253 loc) · 75.4 KB
/
lib.rs
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This crate provides helper types for matching against enum variants, and
//! extracting bindings to each of the fields in the deriving Struct or Enum in
//! a generic way.
//!
//! If you are writing a `#[derive]` which needs to perform some operation on
//! every field, then you have come to the right place!
//!
//! # Example: `WalkFields`
//! ### Trait Implementation
//! ```
//! pub trait WalkFields: std::any::Any {
//! fn walk_fields(&self, walk: &mut FnMut(&WalkFields));
//! }
//! impl WalkFields for i32 {
//! fn walk_fields(&self, _walk: &mut FnMut(&WalkFields)) {}
//! }
//! ```
//!
//! ### Custom Derive
//! ```
//! # use quote::quote;
//! fn walkfields_derive(s: synstructure::Structure) -> proc_macro2::TokenStream {
//! let body = s.each(|bi| quote!{
//! walk(#bi)
//! });
//!
//! s.gen_impl(quote! {
//! extern crate synstructure_test_traits;
//!
//! gen impl synstructure_test_traits::WalkFields for @Self {
//! fn walk_fields(&self, walk: &mut FnMut(&synstructure_test_traits::WalkFields)) {
//! match *self { #body }
//! }
//! }
//! })
//! }
//! # const _IGNORE: &'static str = stringify!(
//! synstructure::decl_derive!([WalkFields] => walkfields_derive);
//! # );
//!
//! /*
//! * Test Case
//! */
//! fn main() {
//! synstructure::test_derive! {
//! walkfields_derive {
//! enum A<T> {
//! B(i32, T),
//! C(i32),
//! }
//! }
//! expands to {
//! #[allow(non_upper_case_globals)]
//! const _DERIVE_synstructure_test_traits_WalkFields_FOR_A: () = {
//! extern crate synstructure_test_traits;
//! impl<T> synstructure_test_traits::WalkFields for A<T>
//! where T: synstructure_test_traits::WalkFields
//! {
//! fn walk_fields(&self, walk: &mut FnMut(&synstructure_test_traits::WalkFields)) {
//! match *self {
//! A::B(ref __binding_0, ref __binding_1,) => {
//! { walk(__binding_0) }
//! { walk(__binding_1) }
//! }
//! A::C(ref __binding_0,) => {
//! { walk(__binding_0) }
//! }
//! }
//! }
//! }
//! };
//! }
//! }
//! }
//! ```
//!
//! # Example: `Interest`
//! ### Trait Implementation
//! ```
//! pub trait Interest {
//! fn interesting(&self) -> bool;
//! }
//! impl Interest for i32 {
//! fn interesting(&self) -> bool { *self > 0 }
//! }
//! ```
//!
//! ### Custom Derive
//! ```
//! # use quote::quote;
//! fn interest_derive(mut s: synstructure::Structure) -> proc_macro2::TokenStream {
//! let body = s.fold(false, |acc, bi| quote!{
//! #acc || synstructure_test_traits::Interest::interesting(#bi)
//! });
//!
//! s.gen_impl(quote! {
//! extern crate synstructure_test_traits;
//! gen impl synstructure_test_traits::Interest for @Self {
//! fn interesting(&self) -> bool {
//! match *self {
//! #body
//! }
//! }
//! }
//! })
//! }
//! # const _IGNORE: &'static str = stringify!(
//! synstructure::decl_derive!([Interest] => interest_derive);
//! # );
//!
//! /*
//! * Test Case
//! */
//! fn main() {
//! synstructure::test_derive!{
//! interest_derive {
//! enum A<T> {
//! B(i32, T),
//! C(i32),
//! }
//! }
//! expands to {
//! #[allow(non_upper_case_globals)]
//! const _DERIVE_synstructure_test_traits_Interest_FOR_A: () = {
//! extern crate synstructure_test_traits;
//! impl<T> synstructure_test_traits::Interest for A<T>
//! where T: synstructure_test_traits::Interest
//! {
//! fn interesting(&self) -> bool {
//! match *self {
//! A::B(ref __binding_0, ref __binding_1,) => {
//! false ||
//! synstructure_test_traits::Interest::interesting(__binding_0) ||
//! synstructure_test_traits::Interest::interesting(__binding_1)
//! }
//! A::C(ref __binding_0,) => {
//! false ||
//! synstructure_test_traits::Interest::interesting(__binding_0)
//! }
//! }
//! }
//! }
//! };
//! }
//! }
//! }
//! ```
//!
//! For more example usage, consider investigating the `abomonation_derive` crate,
//! which makes use of this crate, and is fairly simple.
#[cfg(all(
not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
feature = "proc-macro"
))]
extern crate proc_macro;
use std::collections::HashSet;
use syn::parse::{ParseStream, Parser};
use syn::visit::{self, Visit};
use syn::{
braced, punctuated, token, Attribute, Data, DeriveInput, Error, Expr, Field, Fields,
FieldsNamed, FieldsUnnamed, GenericParam, Generics, Ident, PredicateType, Result, Token,
TraitBound, Type, TypeMacro, TypeParamBound, TypePath, WhereClause, WherePredicate,
};
use quote::{format_ident, quote_spanned, ToTokens};
// re-export the quote! macro so we can depend on it being around in our macro's
// implementations.
#[doc(hidden)]
pub use quote::quote;
use unicode_xid::UnicodeXID;
use proc_macro2::{Span, TokenStream, TokenTree};
// NOTE: This module has documentation hidden, as it only exports macros (which
// always appear in the root of the crate) and helper methods / re-exports used
// in the implementation of those macros.
#[doc(hidden)]
pub mod macros;
/// Changes how bounds are added
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum AddBounds {
/// Add for fields and generics
Both,
/// Fields only
Fields,
/// Generics only
Generics,
/// None
None,
#[doc(hidden)]
__Nonexhaustive,
}
/// The type of binding to use when generating a pattern.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum BindStyle {
/// `x`
Move,
/// `mut x`
MoveMut,
/// `ref x`
Ref,
/// `ref mut x`
RefMut,
}
impl ToTokens for BindStyle {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
BindStyle::Move => {}
BindStyle::MoveMut => quote_spanned!(Span::call_site() => mut).to_tokens(tokens),
BindStyle::Ref => quote_spanned!(Span::call_site() => ref).to_tokens(tokens),
BindStyle::RefMut => quote_spanned!(Span::call_site() => ref mut).to_tokens(tokens),
}
}
}
// Internal method for merging seen_generics arrays together.
fn generics_fuse(res: &mut Vec<bool>, new: &[bool]) {
for (i, &flag) in new.iter().enumerate() {
if i == res.len() {
res.push(false);
}
if flag {
res[i] = true;
}
}
}
// Internal method for extracting the set of generics which have been matched.
fn fetch_generics<'a>(set: &[bool], generics: &'a Generics) -> Vec<&'a Ident> {
let mut tys = vec![];
for (&seen, param) in set.iter().zip(generics.params.iter()) {
if seen {
if let GenericParam::Type(tparam) = param {
tys.push(&tparam.ident)
}
}
}
tys
}
// Internal method for sanitizing an identifier for hygiene purposes.
fn sanitize_ident(s: &str) -> Ident {
let mut res = String::with_capacity(s.len());
for mut c in s.chars() {
if !UnicodeXID::is_xid_continue(c) {
c = '_'
}
// Deduplicate consecutive _ characters.
if res.ends_with('_') && c == '_' {
continue;
}
res.push(c);
}
Ident::new(&res, Span::call_site())
}
// Internal method to merge two Generics objects together intelligently.
fn merge_generics(into: &mut Generics, from: &Generics) -> Result<()> {
// Try to add the param into `into`, and merge parmas with identical names.
for p in &from.params {
for op in &into.params {
match (op, p) {
(GenericParam::Type(otp), GenericParam::Type(tp)) => {
// NOTE: This is only OK because syn ignores the span for equality purposes.
if otp.ident == tp.ident {
return Err(Error::new_spanned(
p,
format!(
"Attempted to merge conflicting generic parameters: {} and {}",
quote!(#op),
quote!(#p)
),
));
}
}
(GenericParam::Lifetime(olp), GenericParam::Lifetime(lp)) => {
// NOTE: This is only OK because syn ignores the span for equality purposes.
if olp.lifetime == lp.lifetime {
return Err(Error::new_spanned(
p,
format!(
"Attempted to merge conflicting generic parameters: {} and {}",
quote!(#op),
quote!(#p)
),
));
}
}
// We don't support merging Const parameters, because that wouldn't make much sense.
_ => (),
}
}
into.params.push(p.clone());
}
// Add any where clauses from the input generics object.
if let Some(from_clause) = &from.where_clause {
into.make_where_clause()
.predicates
.extend(from_clause.predicates.iter().cloned());
}
Ok(())
}
/// Helper method which does the same thing as rustc 1.20's
/// `Option::get_or_insert_with`. This method is used to keep backwards
/// compatibility with rustc 1.15.
fn get_or_insert_with<T, F>(opt: &mut Option<T>, f: F) -> &mut T
where
F: FnOnce() -> T,
{
if opt.is_none() {
*opt = Some(f());
}
match opt {
Some(v) => v,
None => unreachable!(),
}
}
/// Information about a specific binding. This contains both an `Ident`
/// reference to the given field, and the syn `&'a Field` descriptor for that
/// field.
///
/// This type supports `quote::ToTokens`, so can be directly used within the
/// `quote!` macro. It expands to a reference to the matched field.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BindingInfo<'a> {
/// The name which this BindingInfo will bind to.
pub binding: Ident,
/// The type of binding which this BindingInfo will create.
pub style: BindStyle,
field: &'a Field,
// These are used to determine which type parameters are avaliable.
generics: &'a Generics,
seen_generics: Vec<bool>,
}
impl<'a> ToTokens for BindingInfo<'a> {
fn to_tokens(&self, tokens: &mut TokenStream) {
self.binding.to_tokens(tokens);
}
}
impl<'a> BindingInfo<'a> {
/// Returns a reference to the underlying `syn` AST node which this
/// `BindingInfo` references
pub fn ast(&self) -> &'a Field {
self.field
}
/// Generates the pattern fragment for this field binding.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A {
/// B{ a: i32, b: i32 },
/// C(u32),
/// }
/// };
/// let s = Structure::new(&di);
///
/// assert_eq!(
/// s.variants()[0].bindings()[0].pat().to_string(),
/// quote! {
/// ref __binding_0
/// }.to_string()
/// );
/// ```
pub fn pat(&self) -> TokenStream {
let BindingInfo { binding, style, .. } = self;
quote!(#style #binding)
}
/// Returns a list of the type parameters which are referenced in this
/// field's type.
///
/// # Caveat
///
/// If the field contains any macros in type position, all parameters will
/// be considered bound. This is because we cannot determine which type
/// parameters are bound by type macros.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// struct A<T, U> {
/// a: Option<T>,
/// b: U,
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// assert_eq!(
/// s.variants()[0].bindings()[0].referenced_ty_params(),
/// &["e::format_ident!("T")]
/// );
/// ```
pub fn referenced_ty_params(&self) -> Vec<&'a Ident> {
fetch_generics(&self.seen_generics, self.generics)
}
}
/// This type is similar to `syn`'s `Variant` type, however each of the fields
/// are references rather than owned. When this is used as the AST for a real
/// variant, this struct simply borrows the fields of the `syn::Variant`,
/// however this type may also be used as the sole variant for a struct.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct VariantAst<'a> {
pub attrs: &'a [Attribute],
pub ident: &'a Ident,
pub fields: &'a Fields,
pub discriminant: &'a Option<(token::Eq, Expr)>,
}
/// A wrapper around a `syn::DeriveInput`'s variant which provides utilities
/// for destructuring `Variant`s with `match` expressions.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VariantInfo<'a> {
pub prefix: Option<&'a Ident>,
bindings: Vec<BindingInfo<'a>>,
omitted_fields: bool,
ast: VariantAst<'a>,
generics: &'a Generics,
}
/// Helper function used by the VariantInfo constructor. Walks all of the types
/// in `field` and returns a list of the type parameters from `ty_params` which
/// are referenced in the field.
fn get_ty_params(field: &Field, generics: &Generics) -> Vec<bool> {
// Helper type. Discovers all identifiers inside of the visited type,
// and calls a callback with them.
struct BoundTypeLocator<'a> {
result: Vec<bool>,
generics: &'a Generics,
}
impl<'a> Visit<'a> for BoundTypeLocator<'a> {
// XXX: This also (intentionally) captures paths like T::SomeType. Is
// this desirable?
fn visit_ident(&mut self, id: &Ident) {
for (idx, i) in self.generics.params.iter().enumerate() {
if let GenericParam::Type(tparam) = i {
if tparam.ident == *id {
self.result[idx] = true;
}
}
}
}
fn visit_type_macro(&mut self, x: &'a TypeMacro) {
// If we see a type_mac declaration, then we can't know what type parameters
// it might be binding, so we presume it binds all of them.
for r in &mut self.result {
*r = true;
}
visit::visit_type_macro(self, x)
}
}
let mut btl = BoundTypeLocator {
result: vec![false; generics.params.len()],
generics,
};
btl.visit_type(&field.ty);
btl.result
}
impl<'a> VariantInfo<'a> {
fn new(ast: VariantAst<'a>, prefix: Option<&'a Ident>, generics: &'a Generics) -> Self {
let bindings = match ast.fields {
Fields::Unit => vec![],
Fields::Unnamed(FieldsUnnamed {
unnamed: fields, ..
})
| Fields::Named(FieldsNamed { named: fields, .. }) => {
fields
.into_iter()
.enumerate()
.map(|(i, field)| {
BindingInfo {
// XXX: This has to be call_site to avoid privacy
// when deriving on private fields.
binding: format_ident!("__binding_{}", i),
style: BindStyle::Ref,
field,
generics,
seen_generics: get_ty_params(field, generics),
}
})
.collect::<Vec<_>>()
}
};
VariantInfo {
prefix,
bindings,
omitted_fields: false,
ast,
generics,
}
}
/// Returns a slice of the bindings in this Variant.
pub fn bindings(&self) -> &[BindingInfo<'a>] {
&self.bindings
}
/// Returns a mut slice of the bindings in this Variant.
pub fn bindings_mut(&mut self) -> &mut [BindingInfo<'a>] {
&mut self.bindings
}
/// Returns a `VariantAst` object which contains references to the
/// underlying `syn` AST node which this `Variant` was created from.
pub fn ast(&self) -> VariantAst<'a> {
self.ast
}
/// True if any bindings were omitted due to a `filter` call.
pub fn omitted_bindings(&self) -> bool {
self.omitted_fields
}
/// Generates the match-arm pattern which could be used to match against this Variant.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A {
/// B(i32, i32),
/// C(u32),
/// }
/// };
/// let s = Structure::new(&di);
///
/// assert_eq!(
/// s.variants()[0].pat().to_string(),
/// quote!{
/// A::B(ref __binding_0, ref __binding_1,)
/// }.to_string()
/// );
/// ```
pub fn pat(&self) -> TokenStream {
let mut t = TokenStream::new();
if let Some(prefix) = self.prefix {
prefix.to_tokens(&mut t);
quote!(::).to_tokens(&mut t);
}
self.ast.ident.to_tokens(&mut t);
match self.ast.fields {
Fields::Unit => {
assert!(self.bindings.is_empty());
}
Fields::Unnamed(..) => token::Paren(Span::call_site()).surround(&mut t, |t| {
for binding in &self.bindings {
binding.pat().to_tokens(t);
quote!(,).to_tokens(t);
}
if self.omitted_fields {
quote!(..).to_tokens(t);
}
}),
Fields::Named(..) => token::Brace(Span::call_site()).surround(&mut t, |t| {
for binding in &self.bindings {
binding.field.ident.to_tokens(t);
quote!(:).to_tokens(t);
binding.pat().to_tokens(t);
quote!(,).to_tokens(t);
}
if self.omitted_fields {
quote!(..).to_tokens(t);
}
}),
}
t
}
/// Generates the token stream required to construct the current variant.
///
/// The init array initializes each of the fields in the order they are
/// written in `variant.ast().fields`.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A {
/// B(usize, usize),
/// C{ v: usize },
/// }
/// };
/// let s = Structure::new(&di);
///
/// assert_eq!(
/// s.variants()[0].construct(|_, i| quote!(#i)).to_string(),
///
/// quote!{
/// A::B(0usize, 1usize,)
/// }.to_string()
/// );
///
/// assert_eq!(
/// s.variants()[1].construct(|_, i| quote!(#i)).to_string(),
///
/// quote!{
/// A::C{ v: 0usize, }
/// }.to_string()
/// );
/// ```
pub fn construct<F, T>(&self, mut func: F) -> TokenStream
where
F: FnMut(&Field, usize) -> T,
T: ToTokens,
{
let mut t = TokenStream::new();
if let Some(prefix) = self.prefix {
quote!(#prefix ::).to_tokens(&mut t);
}
self.ast.ident.to_tokens(&mut t);
match &self.ast.fields {
Fields::Unit => (),
Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => {
token::Paren::default().surround(&mut t, |t| {
for (i, field) in unnamed.into_iter().enumerate() {
func(field, i).to_tokens(t);
quote!(,).to_tokens(t);
}
})
}
Fields::Named(FieldsNamed { named, .. }) => {
token::Brace::default().surround(&mut t, |t| {
for (i, field) in named.into_iter().enumerate() {
field.ident.to_tokens(t);
quote!(:).to_tokens(t);
func(field, i).to_tokens(t);
quote!(,).to_tokens(t);
}
})
}
}
t
}
/// Runs the passed-in function once for each bound field, passing in a `BindingInfo`.
/// and generating a `match` arm which evaluates the returned tokens.
///
/// This method will ignore fields which are ignored through the `filter`
/// method.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A {
/// B(i32, i32),
/// C(u32),
/// }
/// };
/// let s = Structure::new(&di);
///
/// assert_eq!(
/// s.variants()[0].each(|bi| quote!(println!("{:?}", #bi))).to_string(),
///
/// quote!{
/// A::B(ref __binding_0, ref __binding_1,) => {
/// { println!("{:?}", __binding_0) }
/// { println!("{:?}", __binding_1) }
/// }
/// }.to_string()
/// );
/// ```
pub fn each<F, R>(&self, mut f: F) -> TokenStream
where
F: FnMut(&BindingInfo<'_>) -> R,
R: ToTokens,
{
let pat = self.pat();
let mut body = TokenStream::new();
for binding in &self.bindings {
token::Brace::default().surround(&mut body, |body| {
f(binding).to_tokens(body);
});
}
quote!(#pat => { #body })
}
/// Runs the passed-in function once for each bound field, passing in the
/// result of the previous call, and a `BindingInfo`. generating a `match`
/// arm which evaluates to the resulting tokens.
///
/// This method will ignore fields which are ignored through the `filter`
/// method.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A {
/// B(i32, i32),
/// C(u32),
/// }
/// };
/// let s = Structure::new(&di);
///
/// assert_eq!(
/// s.variants()[0].fold(quote!(0), |acc, bi| quote!(#acc + #bi)).to_string(),
///
/// quote!{
/// A::B(ref __binding_0, ref __binding_1,) => {
/// 0 + __binding_0 + __binding_1
/// }
/// }.to_string()
/// );
/// ```
pub fn fold<F, I, R>(&self, init: I, mut f: F) -> TokenStream
where
F: FnMut(TokenStream, &BindingInfo<'_>) -> R,
I: ToTokens,
R: ToTokens,
{
let pat = self.pat();
let body = self.bindings.iter().fold(quote!(#init), |i, bi| {
let r = f(i, bi);
quote!(#r)
});
quote!(#pat => { #body })
}
/// Filter the bindings created by this `Variant` object. This has 2 effects:
///
/// * The bindings will no longer appear in match arms generated by methods
/// on this `Variant` or its subobjects.
///
/// * Impl blocks created with the `bound_impl` or `unsafe_bound_impl`
/// method only consider type parameters referenced in the types of
/// non-filtered fields.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A {
/// B{ a: i32, b: i32 },
/// C{ a: u32 },
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.variants_mut()[0].filter(|bi| {
/// bi.ast().ident == Some(quote::format_ident!("b"))
/// });
///
/// assert_eq!(
/// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
///
/// quote!{
/// A::B{ b: ref __binding_1, .. } => {
/// { println!("{:?}", __binding_1) }
/// }
/// A::C{ a: ref __binding_0, } => {
/// { println!("{:?}", __binding_0) }
/// }
/// }.to_string()
/// );
/// ```
pub fn filter<F>(&mut self, f: F) -> &mut Self
where
F: FnMut(&BindingInfo<'_>) -> bool,
{
let before_len = self.bindings.len();
self.bindings.retain(f);
if self.bindings.len() != before_len {
self.omitted_fields = true;
}
self
}
/// Remove the binding at the given index.
///
/// # Panics
///
/// Panics if the index is out of range.
pub fn remove_binding(&mut self, idx: usize) -> &mut Self {
self.bindings.remove(idx);
self.omitted_fields = true;
self
}
/// Updates the `BindStyle` for each of the passed-in fields by calling the
/// passed-in function for each `BindingInfo`.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A {
/// B(i32, i32),
/// C(u32),
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.variants_mut()[0].bind_with(|bi| BindStyle::RefMut);
///
/// assert_eq!(
/// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
///
/// quote!{
/// A::B(ref mut __binding_0, ref mut __binding_1,) => {
/// { println!("{:?}", __binding_0) }
/// { println!("{:?}", __binding_1) }
/// }
/// A::C(ref __binding_0,) => {
/// { println!("{:?}", __binding_0) }
/// }
/// }.to_string()
/// );
/// ```
pub fn bind_with<F>(&mut self, mut f: F) -> &mut Self
where
F: FnMut(&BindingInfo<'_>) -> BindStyle,
{
for binding in &mut self.bindings {
binding.style = f(&binding);
}
self
}
/// Updates the binding name for each fo the passed-in fields by calling the
/// passed-in function for each `BindingInfo`.
///
/// The function will be called with the `BindingInfo` and its index in the
/// enclosing variant.
///
/// The default name is `__binding_{}` where `{}` is replaced with an
/// increasing number.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A {
/// B{ a: i32, b: i32 },
/// C{ a: u32 },
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.variants_mut()[0].binding_name(|bi, i| bi.ident.clone().unwrap());
///
/// assert_eq!(
/// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
///
/// quote!{
/// A::B{ a: ref a, b: ref b, } => {
/// { println!("{:?}", a) }
/// { println!("{:?}", b) }
/// }
/// A::C{ a: ref __binding_0, } => {
/// { println!("{:?}", __binding_0) }
/// }
/// }.to_string()
/// );
/// ```
pub fn binding_name<F>(&mut self, mut f: F) -> &mut Self
where
F: FnMut(&Field, usize) -> Ident,
{
for (it, binding) in self.bindings.iter_mut().enumerate() {
binding.binding = f(binding.field, it);
}
self
}
/// Returns a list of the type parameters which are referenced in this
/// field's type.
///
/// # Caveat
///
/// If the field contains any macros in type position, all parameters will
/// be considered bound. This is because we cannot determine which type
/// parameters are bound by type macros.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// struct A<T, U> {
/// a: Option<T>,
/// b: U,
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// assert_eq!(
/// s.variants()[0].bindings()[0].referenced_ty_params(),
/// &["e::format_ident!("T")]
/// );
/// ```
pub fn referenced_ty_params(&self) -> Vec<&'a Ident> {
let mut flags = Vec::new();
for binding in &self.bindings {
generics_fuse(&mut flags, &binding.seen_generics);
}
fetch_generics(&flags, self.generics)
}
}
/// A wrapper around a `syn::DeriveInput` which provides utilities for creating
/// custom derive trait implementations.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Structure<'a> {
variants: Vec<VariantInfo<'a>>,
omitted_variants: bool,
ast: &'a DeriveInput,
extra_impl: Vec<GenericParam>,
extra_predicates: Vec<WherePredicate>,
add_bounds: AddBounds,
}
impl<'a> Structure<'a> {
/// Create a new `Structure` with the variants and fields from the passed-in
/// `DeriveInput`.
///
/// # Panics
///
/// This method will panic if the provided AST node represents an untagged
/// union.
pub fn new(ast: &'a DeriveInput) -> Self {
Self::try_new(ast).expect("Unable to create synstructure::Structure")
}
/// Create a new `Structure` with the variants and fields from the passed-in
/// `DeriveInput`.
///
/// Unlike `Structure::new`, this method does not panic if the provided AST
/// node represents an untagged union.
pub fn try_new(ast: &'a DeriveInput) -> Result<Self> {
let variants = match &ast.data {
Data::Enum(data) => (&data.variants)
.into_iter()
.map(|v| {
VariantInfo::new(
VariantAst {
attrs: &v.attrs,
ident: &v.ident,
fields: &v.fields,
discriminant: &v.discriminant,
},
Some(&ast.ident),
&ast.generics,
)
})
.collect::<Vec<_>>(),
Data::Struct(data) => {
// SAFETY NOTE: Normally putting an `Expr` in static storage
// wouldn't be safe, because it could contain `Term` objects
// which use thread-local interning. However, this static always
// contains the value `None`. Thus, it will never contain any
// unsafe values.
struct UnsafeMakeSync(Option<(token::Eq, Expr)>);
unsafe impl Sync for UnsafeMakeSync {}
static NONE_DISCRIMINANT: UnsafeMakeSync = UnsafeMakeSync(None);
vec![VariantInfo::new(
VariantAst {
attrs: &ast.attrs,
ident: &ast.ident,
fields: &data.fields,
discriminant: &NONE_DISCRIMINANT.0,
},
None,
&ast.generics,
)]
}
Data::Union(_) => {
return Err(Error::new_spanned(
ast,
"unexpected unsupported untagged union",
));