1//! This crate provides helper types for matching against enum variants, and
2//! extracting bindings to each of the fields in the deriving Struct or Enum in
3//! a generic way.
4//!
5//! If you are writing a `#[derive]` which needs to perform some operation on
6//! every field, then you have come to the right place!
7//!
8//! # Example: `WalkFields`
9//! ### Trait Implementation
10//! ```
11//! pub trait WalkFields: std::any::Any {
12//! fn walk_fields(&self, walk: &mut FnMut(&WalkFields));
13//! }
14//! impl WalkFields for i32 {
15//! fn walk_fields(&self, _walk: &mut FnMut(&WalkFields)) {}
16//! }
17//! ```
18//!
19//! ### Custom Derive
20//! ```
21//! # use quote::quote;
22//! fn walkfields_derive(s: synstructure::Structure) -> proc_macro2::TokenStream {
23//! let body = s.each(|bi| quote!{
24//! walk(#bi)
25//! });
26//!
27//! s.gen_impl(quote! {
28//! extern crate synstructure_test_traits;
29//!
30//! gen impl synstructure_test_traits::WalkFields for @Self {
31//! fn walk_fields(&self, walk: &mut FnMut(&synstructure_test_traits::WalkFields)) {
32//! match *self { #body }
33//! }
34//! }
35//! })
36//! }
37//! # const _IGNORE: &'static str = stringify!(
38//! synstructure::decl_derive!([WalkFields] => walkfields_derive);
39//! # );
40//!
41//! /*
42//! * Test Case
43//! */
44//! fn main() {
45//! synstructure::test_derive! {
46//! walkfields_derive {
47//! enum A<T> {
48//! B(i32, T),
49//! C(i32),
50//! }
51//! }
52//! expands to {
53//! #[allow(non_upper_case_globals)]
54//! const _DERIVE_synstructure_test_traits_WalkFields_FOR_A: () = {
55//! extern crate synstructure_test_traits;
56//! impl<T> synstructure_test_traits::WalkFields for A<T>
57//! where T: synstructure_test_traits::WalkFields
58//! {
59//! fn walk_fields(&self, walk: &mut FnMut(&synstructure_test_traits::WalkFields)) {
60//! match *self {
61//! A::B(ref __binding_0, ref __binding_1,) => {
62//! { walk(__binding_0) }
63//! { walk(__binding_1) }
64//! }
65//! A::C(ref __binding_0,) => {
66//! { walk(__binding_0) }
67//! }
68//! }
69//! }
70//! }
71//! };
72//! }
73//! }
74//! }
75//! ```
76//!
77//! # Example: `Interest`
78//! ### Trait Implementation
79//! ```
80//! pub trait Interest {
81//! fn interesting(&self) -> bool;
82//! }
83//! impl Interest for i32 {
84//! fn interesting(&self) -> bool { *self > 0 }
85//! }
86//! ```
87//!
88//! ### Custom Derive
89//! ```
90//! # use quote::quote;
91//! fn interest_derive(mut s: synstructure::Structure) -> proc_macro2::TokenStream {
92//! let body = s.fold(false, |acc, bi| quote!{
93//! #acc || synstructure_test_traits::Interest::interesting(#bi)
94//! });
95//!
96//! s.gen_impl(quote! {
97//! extern crate synstructure_test_traits;
98//! gen impl synstructure_test_traits::Interest for @Self {
99//! fn interesting(&self) -> bool {
100//! match *self {
101//! #body
102//! }
103//! }
104//! }
105//! })
106//! }
107//! # const _IGNORE: &'static str = stringify!(
108//! synstructure::decl_derive!([Interest] => interest_derive);
109//! # );
110//!
111//! /*
112//! * Test Case
113//! */
114//! fn main() {
115//! synstructure::test_derive!{
116//! interest_derive {
117//! enum A<T> {
118//! B(i32, T),
119//! C(i32),
120//! }
121//! }
122//! expands to {
123//! #[allow(non_upper_case_globals)]
124//! const _DERIVE_synstructure_test_traits_Interest_FOR_A: () = {
125//! extern crate synstructure_test_traits;
126//! impl<T> synstructure_test_traits::Interest for A<T>
127//! where T: synstructure_test_traits::Interest
128//! {
129//! fn interesting(&self) -> bool {
130//! match *self {
131//! A::B(ref __binding_0, ref __binding_1,) => {
132//! false ||
133//! synstructure_test_traits::Interest::interesting(__binding_0) ||
134//! synstructure_test_traits::Interest::interesting(__binding_1)
135//! }
136//! A::C(ref __binding_0,) => {
137//! false ||
138//! synstructure_test_traits::Interest::interesting(__binding_0)
139//! }
140//! }
141//! }
142//! }
143//! };
144//! }
145//! }
146//! }
147//! ```
148//!
149//! For more example usage, consider investigating the `abomonation_derive` crate,
150//! which makes use of this crate, and is fairly simple.
151
152#![allow(
153 clippy::default_trait_access,
154 clippy::missing_errors_doc,
155 clippy::missing_panics_doc,
156 clippy::must_use_candidate,
157 clippy::needless_pass_by_value
158)]
159
160#[cfg(all(
161 not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
162 feature = "proc-macro"
163))]
164extern crate proc_macro;
165
166use std::collections::HashSet;
167
168use syn::parse::{ParseStream, Parser};
169use syn::visit::{self, Visit};
170use syn::{
171 braced, punctuated, token, Attribute, Data, DeriveInput, Error, Expr, Field, Fields,
172 FieldsNamed, FieldsUnnamed, GenericParam, Generics, Ident, PredicateType, Result, Token,
173 TraitBound, Type, TypeMacro, TypeParamBound, TypePath, WhereClause, WherePredicate,
174};
175
176use quote::{format_ident, quote_spanned, ToTokens};
177// re-export the quote! macro so we can depend on it being around in our macro's
178// implementations.
179#[doc(hidden)]
180pub use quote::quote;
181
182use unicode_xid::UnicodeXID;
183
184use proc_macro2::{Span, TokenStream, TokenTree};
185
186// NOTE: This module has documentation hidden, as it only exports macros (which
187// always appear in the root of the crate) and helper methods / re-exports used
188// in the implementation of those macros.
189#[doc(hidden)]
190pub mod macros;
191
192/// Changes how bounds are added
193#[allow(clippy::manual_non_exhaustive)]
194#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
195pub enum AddBounds {
196 /// Add for fields and generics
197 Both,
198 /// Fields only
199 Fields,
200 /// Generics only
201 Generics,
202 /// None
203 None,
204 #[doc(hidden)]
205 __Nonexhaustive,
206}
207
208/// The type of binding to use when generating a pattern.
209#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
210pub enum BindStyle {
211 /// `x`
212 Move,
213 /// `mut x`
214 MoveMut,
215 /// `ref x`
216 Ref,
217 /// `ref mut x`
218 RefMut,
219}
220
221impl ToTokens for BindStyle {
222 fn to_tokens(&self, tokens: &mut TokenStream) {
223 match self {
224 BindStyle::Move => {}
225 BindStyle::MoveMut => quote_spanned!(Span::call_site() => mut).to_tokens(tokens),
226 BindStyle::Ref => quote_spanned!(Span::call_site() => ref).to_tokens(tokens),
227 BindStyle::RefMut => quote_spanned!(Span::call_site() => ref mut).to_tokens(tokens),
228 }
229 }
230}
231
232// Internal method for merging seen_generics arrays together.
233fn generics_fuse(res: &mut Vec<bool>, new: &[bool]) {
234 for (i: usize, &flag: bool) in new.iter().enumerate() {
235 if i == res.len() {
236 res.push(false);
237 }
238 if flag {
239 res[i] = true;
240 }
241 }
242}
243
244// Internal method for extracting the set of generics which have been matched.
245fn fetch_generics<'a>(set: &[bool], generics: &'a Generics) -> Vec<&'a Ident> {
246 let mut tys: Vec<&Ident> = vec![];
247 for (&seen: bool, param: &GenericParam) in set.iter().zip(generics.params.iter()) {
248 if seen {
249 if let GenericParam::Type(tparam: &TypeParam) = param {
250 tys.push(&tparam.ident);
251 }
252 }
253 }
254 tys
255}
256
257// Internal method for sanitizing an identifier for hygiene purposes.
258fn sanitize_ident(s: &str) -> Ident {
259 let mut res: String = String::with_capacity(s.len());
260 for mut c: char in s.chars() {
261 if !UnicodeXID::is_xid_continue(self:c) {
262 c = '_';
263 }
264 // Deduplicate consecutive _ characters.
265 if res.ends_with('_') && c == '_' {
266 continue;
267 }
268 res.push(ch:c);
269 }
270 Ident::new(&res, Span::call_site())
271}
272
273// Internal method to merge two Generics objects together intelligently.
274fn merge_generics(into: &mut Generics, from: &Generics) -> Result<()> {
275 // Try to add the param into `into`, and merge parmas with identical names.
276 for p in &from.params {
277 for op in &into.params {
278 match (op, p) {
279 (GenericParam::Type(otp), GenericParam::Type(tp)) => {
280 // NOTE: This is only OK because syn ignores the span for equality purposes.
281 if otp.ident == tp.ident {
282 return Err(Error::new_spanned(
283 p,
284 format!(
285 "Attempted to merge conflicting generic parameters: {} and {}",
286 quote!(#op),
287 quote!(#p)
288 ),
289 ));
290 }
291 }
292 (GenericParam::Lifetime(olp), GenericParam::Lifetime(lp)) => {
293 // NOTE: This is only OK because syn ignores the span for equality purposes.
294 if olp.lifetime == lp.lifetime {
295 return Err(Error::new_spanned(
296 p,
297 format!(
298 "Attempted to merge conflicting generic parameters: {} and {}",
299 quote!(#op),
300 quote!(#p)
301 ),
302 ));
303 }
304 }
305 // We don't support merging Const parameters, because that wouldn't make much sense.
306 _ => (),
307 }
308 }
309 into.params.push(p.clone());
310 }
311
312 // Add any where clauses from the input generics object.
313 if let Some(from_clause) = &from.where_clause {
314 into.make_where_clause()
315 .predicates
316 .extend(from_clause.predicates.iter().cloned());
317 }
318
319 Ok(())
320}
321
322/// Helper method which does the same thing as rustc 1.20's
323/// `Option::get_or_insert_with`. This method is used to keep backwards
324/// compatibility with rustc 1.15.
325fn get_or_insert_with<T, F>(opt: &mut Option<T>, f: F) -> &mut T
326where
327 F: FnOnce() -> T,
328{
329 if opt.is_none() {
330 *opt = Some(f());
331 }
332
333 match opt {
334 Some(v: &mut T) => v,
335 None => unreachable!(),
336 }
337}
338
339/// Information about a specific binding. This contains both an `Ident`
340/// reference to the given field, and the syn `&'a Field` descriptor for that
341/// field.
342///
343/// This type supports `quote::ToTokens`, so can be directly used within the
344/// `quote!` macro. It expands to a reference to the matched field.
345#[derive(Debug, Clone, PartialEq, Eq, Hash)]
346pub struct BindingInfo<'a> {
347 /// The name which this BindingInfo will bind to.
348 pub binding: Ident,
349
350 /// The type of binding which this BindingInfo will create.
351 pub style: BindStyle,
352
353 field: &'a Field,
354
355 // These are used to determine which type parameters are avaliable.
356 generics: &'a Generics,
357 seen_generics: Vec<bool>,
358 // The original index of the binding
359 // this will not change when .filter() is called
360 index: usize,
361}
362
363impl<'a> ToTokens for BindingInfo<'a> {
364 fn to_tokens(&self, tokens: &mut TokenStream) {
365 self.binding.to_tokens(tokens);
366 }
367}
368
369impl<'a> BindingInfo<'a> {
370 /// Returns a reference to the underlying `syn` AST node which this
371 /// `BindingInfo` references
372 pub fn ast(&self) -> &'a Field {
373 self.field
374 }
375
376 /// Generates the pattern fragment for this field binding.
377 ///
378 /// # Example
379 /// ```
380 /// # use synstructure::*;
381 /// let di: syn::DeriveInput = syn::parse_quote! {
382 /// enum A {
383 /// B{ a: i32, b: i32 },
384 /// C(u32),
385 /// }
386 /// };
387 /// let s = Structure::new(&di);
388 ///
389 /// assert_eq!(
390 /// s.variants()[0].bindings()[0].pat().to_string(),
391 /// quote! {
392 /// ref __binding_0
393 /// }.to_string()
394 /// );
395 /// ```
396 pub fn pat(&self) -> TokenStream {
397 let BindingInfo { binding, style, .. } = self;
398 quote!(#style #binding)
399 }
400
401 /// Returns a list of the type parameters which are referenced in this
402 /// field's type.
403 ///
404 /// # Caveat
405 ///
406 /// If the field contains any macros in type position, all parameters will
407 /// be considered bound. This is because we cannot determine which type
408 /// parameters are bound by type macros.
409 ///
410 /// # Example
411 /// ```
412 /// # use synstructure::*;
413 /// let di: syn::DeriveInput = syn::parse_quote! {
414 /// struct A<T, U> {
415 /// a: Option<T>,
416 /// b: U,
417 /// }
418 /// };
419 /// let mut s = Structure::new(&di);
420 ///
421 /// assert_eq!(
422 /// s.variants()[0].bindings()[0].referenced_ty_params(),
423 /// &[&quote::format_ident!("T")]
424 /// );
425 /// ```
426 pub fn referenced_ty_params(&self) -> Vec<&'a Ident> {
427 fetch_generics(&self.seen_generics, self.generics)
428 }
429}
430
431/// This type is similar to `syn`'s `Variant` type, however each of the fields
432/// are references rather than owned. When this is used as the AST for a real
433/// variant, this struct simply borrows the fields of the `syn::Variant`,
434/// however this type may also be used as the sole variant for a struct.
435#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
436pub struct VariantAst<'a> {
437 pub attrs: &'a [Attribute],
438 pub ident: &'a Ident,
439 pub fields: &'a Fields,
440 pub discriminant: &'a Option<(token::Eq, Expr)>,
441}
442
443/// A wrapper around a `syn::DeriveInput`'s variant which provides utilities
444/// for destructuring `Variant`s with `match` expressions.
445#[derive(Debug, Clone, PartialEq, Eq, Hash)]
446pub struct VariantInfo<'a> {
447 pub prefix: Option<&'a Ident>,
448 bindings: Vec<BindingInfo<'a>>,
449 ast: VariantAst<'a>,
450 generics: &'a Generics,
451 // The original length of `bindings` before any `.filter()` calls
452 original_length: usize,
453}
454
455/// Helper function used by the `VariantInfo` constructor. Walks all of the types
456/// in `field` and returns a list of the type parameters from `ty_params` which
457/// are referenced in the field.
458fn get_ty_params(field: &Field, generics: &Generics) -> Vec<bool> {
459 // Helper type. Discovers all identifiers inside of the visited type,
460 // and calls a callback with them.
461 struct BoundTypeLocator<'a> {
462 result: Vec<bool>,
463 generics: &'a Generics,
464 }
465
466 impl<'a> Visit<'a> for BoundTypeLocator<'a> {
467 // XXX: This also (intentionally) captures paths like T::SomeType. Is
468 // this desirable?
469 fn visit_ident(&mut self, id: &Ident) {
470 for (idx, i) in self.generics.params.iter().enumerate() {
471 if let GenericParam::Type(tparam) = i {
472 if tparam.ident == *id {
473 self.result[idx] = true;
474 }
475 }
476 }
477 }
478
479 fn visit_type_macro(&mut self, x: &'a TypeMacro) {
480 // If we see a type_mac declaration, then we can't know what type parameters
481 // it might be binding, so we presume it binds all of them.
482 for r in &mut self.result {
483 *r = true;
484 }
485 visit::visit_type_macro(self, x);
486 }
487 }
488
489 let mut btl = BoundTypeLocator {
490 result: vec![false; generics.params.len()],
491 generics,
492 };
493
494 btl.visit_type(&field.ty);
495
496 btl.result
497}
498
499impl<'a> VariantInfo<'a> {
500 fn new(ast: VariantAst<'a>, prefix: Option<&'a Ident>, generics: &'a Generics) -> Self {
501 let bindings = match ast.fields {
502 Fields::Unit => vec![],
503 Fields::Unnamed(FieldsUnnamed {
504 unnamed: fields, ..
505 })
506 | Fields::Named(FieldsNamed { named: fields, .. }) => {
507 fields
508 .into_iter()
509 .enumerate()
510 .map(|(i, field)| {
511 BindingInfo {
512 // XXX: This has to be call_site to avoid privacy
513 // when deriving on private fields.
514 binding: format_ident!("__binding_{}", i),
515 style: BindStyle::Ref,
516 field,
517 generics,
518 seen_generics: get_ty_params(field, generics),
519 index: i,
520 }
521 })
522 .collect::<Vec<_>>()
523 }
524 };
525
526 let original_length = bindings.len();
527 VariantInfo {
528 prefix,
529 bindings,
530 ast,
531 generics,
532 original_length,
533 }
534 }
535
536 /// Returns a slice of the bindings in this Variant.
537 pub fn bindings(&self) -> &[BindingInfo<'a>] {
538 &self.bindings
539 }
540
541 /// Returns a mut slice of the bindings in this Variant.
542 pub fn bindings_mut(&mut self) -> &mut [BindingInfo<'a>] {
543 &mut self.bindings
544 }
545
546 /// Returns a `VariantAst` object which contains references to the
547 /// underlying `syn` AST node which this `Variant` was created from.
548 pub fn ast(&self) -> VariantAst<'a> {
549 self.ast
550 }
551
552 /// True if any bindings were omitted due to a `filter` call.
553 pub fn omitted_bindings(&self) -> bool {
554 self.original_length != self.bindings.len()
555 }
556
557 /// Generates the match-arm pattern which could be used to match against this Variant.
558 ///
559 /// # Example
560 /// ```
561 /// # use synstructure::*;
562 /// let di: syn::DeriveInput = syn::parse_quote! {
563 /// enum A {
564 /// B(i32, i32),
565 /// C(u32),
566 /// }
567 /// };
568 /// let s = Structure::new(&di);
569 ///
570 /// assert_eq!(
571 /// s.variants()[0].pat().to_string(),
572 /// quote!{
573 /// A::B(ref __binding_0, ref __binding_1,)
574 /// }.to_string()
575 /// );
576 /// ```
577 pub fn pat(&self) -> TokenStream {
578 let mut t = TokenStream::new();
579 if let Some(prefix) = self.prefix {
580 prefix.to_tokens(&mut t);
581 quote!(::).to_tokens(&mut t);
582 }
583 self.ast.ident.to_tokens(&mut t);
584 match self.ast.fields {
585 Fields::Unit => {
586 assert!(self.bindings.is_empty());
587 }
588 Fields::Unnamed(..) => token::Paren(Span::call_site()).surround(&mut t, |t| {
589 let mut expected_index = 0;
590 for binding in &self.bindings {
591 while expected_index < binding.index {
592 quote!(_,).to_tokens(t);
593 expected_index += 1;
594 }
595 binding.pat().to_tokens(t);
596 quote!(,).to_tokens(t);
597 expected_index += 1;
598 }
599 if expected_index != self.original_length {
600 quote!(..).to_tokens(t);
601 }
602 }),
603 Fields::Named(..) => token::Brace(Span::call_site()).surround(&mut t, |t| {
604 for binding in &self.bindings {
605 binding.field.ident.to_tokens(t);
606 quote!(:).to_tokens(t);
607 binding.pat().to_tokens(t);
608 quote!(,).to_tokens(t);
609 }
610 if self.omitted_bindings() {
611 quote!(..).to_tokens(t);
612 }
613 }),
614 }
615 t
616 }
617
618 /// Generates the token stream required to construct the current variant.
619 ///
620 /// The init array initializes each of the fields in the order they are
621 /// written in `variant.ast().fields`.
622 ///
623 /// # Example
624 /// ```
625 /// # use synstructure::*;
626 /// let di: syn::DeriveInput = syn::parse_quote! {
627 /// enum A {
628 /// B(usize, usize),
629 /// C{ v: usize },
630 /// }
631 /// };
632 /// let s = Structure::new(&di);
633 ///
634 /// assert_eq!(
635 /// s.variants()[0].construct(|_, i| quote!(#i)).to_string(),
636 ///
637 /// quote!{
638 /// A::B(0usize, 1usize,)
639 /// }.to_string()
640 /// );
641 ///
642 /// assert_eq!(
643 /// s.variants()[1].construct(|_, i| quote!(#i)).to_string(),
644 ///
645 /// quote!{
646 /// A::C{ v: 0usize, }
647 /// }.to_string()
648 /// );
649 /// ```
650 pub fn construct<F, T>(&self, mut func: F) -> TokenStream
651 where
652 F: FnMut(&Field, usize) -> T,
653 T: ToTokens,
654 {
655 let mut t = TokenStream::new();
656 if let Some(prefix) = self.prefix {
657 quote!(#prefix ::).to_tokens(&mut t);
658 }
659 self.ast.ident.to_tokens(&mut t);
660
661 match &self.ast.fields {
662 Fields::Unit => (),
663 Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => {
664 token::Paren::default().surround(&mut t, |t| {
665 for (i, field) in unnamed.into_iter().enumerate() {
666 func(field, i).to_tokens(t);
667 quote!(,).to_tokens(t);
668 }
669 });
670 }
671 Fields::Named(FieldsNamed { named, .. }) => {
672 token::Brace::default().surround(&mut t, |t| {
673 for (i, field) in named.into_iter().enumerate() {
674 field.ident.to_tokens(t);
675 quote!(:).to_tokens(t);
676 func(field, i).to_tokens(t);
677 quote!(,).to_tokens(t);
678 }
679 });
680 }
681 }
682 t
683 }
684
685 /// Runs the passed-in function once for each bound field, passing in a `BindingInfo`.
686 /// and generating a `match` arm which evaluates the returned tokens.
687 ///
688 /// This method will ignore fields which are ignored through the `filter`
689 /// method.
690 ///
691 /// # Example
692 /// ```
693 /// # use synstructure::*;
694 /// let di: syn::DeriveInput = syn::parse_quote! {
695 /// enum A {
696 /// B(i32, i32),
697 /// C(u32),
698 /// }
699 /// };
700 /// let s = Structure::new(&di);
701 ///
702 /// assert_eq!(
703 /// s.variants()[0].each(|bi| quote!(println!("{:?}", #bi))).to_string(),
704 ///
705 /// quote!{
706 /// A::B(ref __binding_0, ref __binding_1,) => {
707 /// { println!("{:?}", __binding_0) }
708 /// { println!("{:?}", __binding_1) }
709 /// }
710 /// }.to_string()
711 /// );
712 /// ```
713 pub fn each<F, R>(&self, mut f: F) -> TokenStream
714 where
715 F: FnMut(&BindingInfo<'_>) -> R,
716 R: ToTokens,
717 {
718 let pat = self.pat();
719 let mut body = TokenStream::new();
720 for binding in &self.bindings {
721 token::Brace::default().surround(&mut body, |body| {
722 f(binding).to_tokens(body);
723 });
724 }
725 quote!(#pat => { #body })
726 }
727
728 /// Runs the passed-in function once for each bound field, passing in the
729 /// result of the previous call, and a `BindingInfo`. generating a `match`
730 /// arm which evaluates to the resulting tokens.
731 ///
732 /// This method will ignore fields which are ignored through the `filter`
733 /// method.
734 ///
735 /// # Example
736 /// ```
737 /// # use synstructure::*;
738 /// let di: syn::DeriveInput = syn::parse_quote! {
739 /// enum A {
740 /// B(i32, i32),
741 /// C(u32),
742 /// }
743 /// };
744 /// let s = Structure::new(&di);
745 ///
746 /// assert_eq!(
747 /// s.variants()[0].fold(quote!(0), |acc, bi| quote!(#acc + #bi)).to_string(),
748 ///
749 /// quote!{
750 /// A::B(ref __binding_0, ref __binding_1,) => {
751 /// 0 + __binding_0 + __binding_1
752 /// }
753 /// }.to_string()
754 /// );
755 /// ```
756 pub fn fold<F, I, R>(&self, init: I, mut f: F) -> TokenStream
757 where
758 F: FnMut(TokenStream, &BindingInfo<'_>) -> R,
759 I: ToTokens,
760 R: ToTokens,
761 {
762 let pat = self.pat();
763 let body = self.bindings.iter().fold(quote!(#init), |i, bi| {
764 let r = f(i, bi);
765 quote!(#r)
766 });
767 quote!(#pat => { #body })
768 }
769
770 /// Filter the bindings created by this `Variant` object. This has 2 effects:
771 ///
772 /// * The bindings will no longer appear in match arms generated by methods
773 /// on this `Variant` or its subobjects.
774 ///
775 /// * Impl blocks created with the `bound_impl` or `unsafe_bound_impl`
776 /// method only consider type parameters referenced in the types of
777 /// non-filtered fields.
778 ///
779 /// # Example
780 /// ```
781 /// # use synstructure::*;
782 /// let di: syn::DeriveInput = syn::parse_quote! {
783 /// enum A {
784 /// B{ a: i32, b: i32 },
785 /// C{ a: u32 },
786 /// }
787 /// };
788 /// let mut s = Structure::new(&di);
789 ///
790 /// s.variants_mut()[0].filter(|bi| {
791 /// bi.ast().ident == Some(quote::format_ident!("b"))
792 /// });
793 ///
794 /// assert_eq!(
795 /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
796 ///
797 /// quote!{
798 /// A::B{ b: ref __binding_1, .. } => {
799 /// { println!("{:?}", __binding_1) }
800 /// }
801 /// A::C{ a: ref __binding_0, } => {
802 /// { println!("{:?}", __binding_0) }
803 /// }
804 /// }.to_string()
805 /// );
806 /// ```
807 pub fn filter<F>(&mut self, f: F) -> &mut Self
808 where
809 F: FnMut(&BindingInfo<'_>) -> bool,
810 {
811 self.bindings.retain(f);
812 self
813 }
814
815 /// Iterates all the bindings of this `Variant` object and uses a closure to determine if a
816 /// binding should be removed. If the closure returns `true` the binding is removed from the
817 /// variant. If the closure returns `false`, the binding remains in the variant.
818 ///
819 /// All the removed bindings are moved to a new `Variant` object which is otherwise identical
820 /// to the current one. To understand the effects of removing a binding from a variant check
821 /// the [`VariantInfo::filter`] documentation.
822 ///
823 /// # Example
824 /// ```
825 /// # use synstructure::*;
826 /// let di: syn::DeriveInput = syn::parse_quote! {
827 /// enum A {
828 /// B{ a: i32, b: i32 },
829 /// C{ a: u32 },
830 /// }
831 /// };
832 /// let mut s = Structure::new(&di);
833 ///
834 /// let mut with_b = &mut s.variants_mut()[0];
835 ///
836 /// let with_a = with_b.drain_filter(|bi| {
837 /// bi.ast().ident == Some(quote::format_ident!("a"))
838 /// });
839 ///
840 /// assert_eq!(
841 /// with_a.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
842 ///
843 /// quote!{
844 /// A::B{ a: ref __binding_0, .. } => {
845 /// { println!("{:?}", __binding_0) }
846 /// }
847 /// }.to_string()
848 /// );
849 ///
850 /// assert_eq!(
851 /// with_b.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
852 ///
853 /// quote!{
854 /// A::B{ b: ref __binding_1, .. } => {
855 /// { println!("{:?}", __binding_1) }
856 /// }
857 /// }.to_string()
858 /// );
859 /// ```
860 #[allow(clippy::return_self_not_must_use)]
861 pub fn drain_filter<F>(&mut self, mut f: F) -> Self
862 where
863 F: FnMut(&BindingInfo<'_>) -> bool,
864 {
865 let mut other = VariantInfo {
866 prefix: self.prefix,
867 bindings: vec![],
868 ast: self.ast,
869 generics: self.generics,
870 original_length: self.original_length,
871 };
872
873 let (other_bindings, self_bindings) = self.bindings.drain(..).partition(&mut f);
874 other.bindings = other_bindings;
875 self.bindings = self_bindings;
876
877 other
878 }
879
880 /// Remove the binding at the given index.
881 ///
882 /// # Panics
883 ///
884 /// Panics if the index is out of range.
885 pub fn remove_binding(&mut self, idx: usize) -> &mut Self {
886 self.bindings.remove(idx);
887 self
888 }
889
890 /// Updates the `BindStyle` for each of the passed-in fields by calling the
891 /// passed-in function for each `BindingInfo`.
892 ///
893 /// # Example
894 /// ```
895 /// # use synstructure::*;
896 /// let di: syn::DeriveInput = syn::parse_quote! {
897 /// enum A {
898 /// B(i32, i32),
899 /// C(u32),
900 /// }
901 /// };
902 /// let mut s = Structure::new(&di);
903 ///
904 /// s.variants_mut()[0].bind_with(|bi| BindStyle::RefMut);
905 ///
906 /// assert_eq!(
907 /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
908 ///
909 /// quote!{
910 /// A::B(ref mut __binding_0, ref mut __binding_1,) => {
911 /// { println!("{:?}", __binding_0) }
912 /// { println!("{:?}", __binding_1) }
913 /// }
914 /// A::C(ref __binding_0,) => {
915 /// { println!("{:?}", __binding_0) }
916 /// }
917 /// }.to_string()
918 /// );
919 /// ```
920 pub fn bind_with<F>(&mut self, mut f: F) -> &mut Self
921 where
922 F: FnMut(&BindingInfo<'_>) -> BindStyle,
923 {
924 for binding in &mut self.bindings {
925 binding.style = f(binding);
926 }
927 self
928 }
929
930 /// Updates the binding name for each fo the passed-in fields by calling the
931 /// passed-in function for each `BindingInfo`.
932 ///
933 /// The function will be called with the `BindingInfo` and its index in the
934 /// enclosing variant.
935 ///
936 /// The default name is `__binding_{}` where `{}` is replaced with an
937 /// increasing number.
938 ///
939 /// # Example
940 /// ```
941 /// # use synstructure::*;
942 /// let di: syn::DeriveInput = syn::parse_quote! {
943 /// enum A {
944 /// B{ a: i32, b: i32 },
945 /// C{ a: u32 },
946 /// }
947 /// };
948 /// let mut s = Structure::new(&di);
949 ///
950 /// s.variants_mut()[0].binding_name(|bi, i| bi.ident.clone().unwrap());
951 ///
952 /// assert_eq!(
953 /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
954 ///
955 /// quote!{
956 /// A::B{ a: ref a, b: ref b, } => {
957 /// { println!("{:?}", a) }
958 /// { println!("{:?}", b) }
959 /// }
960 /// A::C{ a: ref __binding_0, } => {
961 /// { println!("{:?}", __binding_0) }
962 /// }
963 /// }.to_string()
964 /// );
965 /// ```
966 pub fn binding_name<F>(&mut self, mut f: F) -> &mut Self
967 where
968 F: FnMut(&Field, usize) -> Ident,
969 {
970 for (it, binding) in self.bindings.iter_mut().enumerate() {
971 binding.binding = f(binding.field, it);
972 }
973 self
974 }
975
976 /// Returns a list of the type parameters which are referenced in this
977 /// field's type.
978 ///
979 /// # Caveat
980 ///
981 /// If the field contains any macros in type position, all parameters will
982 /// be considered bound. This is because we cannot determine which type
983 /// parameters are bound by type macros.
984 ///
985 /// # Example
986 /// ```
987 /// # use synstructure::*;
988 /// let di: syn::DeriveInput = syn::parse_quote! {
989 /// struct A<T, U> {
990 /// a: Option<T>,
991 /// b: U,
992 /// }
993 /// };
994 /// let mut s = Structure::new(&di);
995 ///
996 /// assert_eq!(
997 /// s.variants()[0].bindings()[0].referenced_ty_params(),
998 /// &[&quote::format_ident!("T")]
999 /// );
1000 /// ```
1001 pub fn referenced_ty_params(&self) -> Vec<&'a Ident> {
1002 let mut flags = Vec::new();
1003 for binding in &self.bindings {
1004 generics_fuse(&mut flags, &binding.seen_generics);
1005 }
1006 fetch_generics(&flags, self.generics)
1007 }
1008}
1009
1010/// A wrapper around a `syn::DeriveInput` which provides utilities for creating
1011/// custom derive trait implementations.
1012#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1013pub struct Structure<'a> {
1014 variants: Vec<VariantInfo<'a>>,
1015 omitted_variants: bool,
1016 underscore_const: bool,
1017 ast: &'a DeriveInput,
1018 extra_impl: Vec<GenericParam>,
1019 extra_predicates: Vec<WherePredicate>,
1020 add_bounds: AddBounds,
1021}
1022
1023impl<'a> Structure<'a> {
1024 /// Create a new `Structure` with the variants and fields from the passed-in
1025 /// `DeriveInput`.
1026 ///
1027 /// # Panics
1028 ///
1029 /// This method will panic if the provided AST node represents an untagged
1030 /// union.
1031 pub fn new(ast: &'a DeriveInput) -> Self {
1032 Self::try_new(ast).expect("Unable to create synstructure::Structure")
1033 }
1034
1035 /// Create a new `Structure` with the variants and fields from the passed-in
1036 /// `DeriveInput`.
1037 ///
1038 /// Unlike `Structure::new`, this method does not panic if the provided AST
1039 /// node represents an untagged union.
1040 pub fn try_new(ast: &'a DeriveInput) -> Result<Self> {
1041 let variants = match &ast.data {
1042 Data::Enum(data) => (&data.variants)
1043 .into_iter()
1044 .map(|v| {
1045 VariantInfo::new(
1046 VariantAst {
1047 attrs: &v.attrs,
1048 ident: &v.ident,
1049 fields: &v.fields,
1050 discriminant: &v.discriminant,
1051 },
1052 Some(&ast.ident),
1053 &ast.generics,
1054 )
1055 })
1056 .collect::<Vec<_>>(),
1057 Data::Struct(data) => {
1058 vec![VariantInfo::new(
1059 VariantAst {
1060 attrs: &ast.attrs,
1061 ident: &ast.ident,
1062 fields: &data.fields,
1063 discriminant: &None,
1064 },
1065 None,
1066 &ast.generics,
1067 )]
1068 }
1069 Data::Union(_) => {
1070 return Err(Error::new_spanned(
1071 ast,
1072 "unexpected unsupported untagged union",
1073 ));
1074 }
1075 };
1076
1077 Ok(Structure {
1078 variants,
1079 omitted_variants: false,
1080 underscore_const: false,
1081 ast,
1082 extra_impl: vec![],
1083 extra_predicates: vec![],
1084 add_bounds: AddBounds::Both,
1085 })
1086 }
1087
1088 /// Returns a slice of the variants in this Structure.
1089 pub fn variants(&self) -> &[VariantInfo<'a>] {
1090 &self.variants
1091 }
1092
1093 /// Returns a mut slice of the variants in this Structure.
1094 pub fn variants_mut(&mut self) -> &mut [VariantInfo<'a>] {
1095 &mut self.variants
1096 }
1097
1098 /// Returns a reference to the underlying `syn` AST node which this
1099 /// `Structure` was created from.
1100 pub fn ast(&self) -> &'a DeriveInput {
1101 self.ast
1102 }
1103
1104 /// True if any variants were omitted due to a `filter_variants` call.
1105 pub fn omitted_variants(&self) -> bool {
1106 self.omitted_variants
1107 }
1108
1109 /// Runs the passed-in function once for each bound field, passing in a `BindingInfo`.
1110 /// and generating `match` arms which evaluate the returned tokens.
1111 ///
1112 /// This method will ignore variants or fields which are ignored through the
1113 /// `filter` and `filter_variant` methods.
1114 ///
1115 /// # Example
1116 /// ```
1117 /// # use synstructure::*;
1118 /// let di: syn::DeriveInput = syn::parse_quote! {
1119 /// enum A {
1120 /// B(i32, i32),
1121 /// C(u32),
1122 /// }
1123 /// };
1124 /// let s = Structure::new(&di);
1125 ///
1126 /// assert_eq!(
1127 /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
1128 ///
1129 /// quote!{
1130 /// A::B(ref __binding_0, ref __binding_1,) => {
1131 /// { println!("{:?}", __binding_0) }
1132 /// { println!("{:?}", __binding_1) }
1133 /// }
1134 /// A::C(ref __binding_0,) => {
1135 /// { println!("{:?}", __binding_0) }
1136 /// }
1137 /// }.to_string()
1138 /// );
1139 /// ```
1140 pub fn each<F, R>(&self, mut f: F) -> TokenStream
1141 where
1142 F: FnMut(&BindingInfo<'_>) -> R,
1143 R: ToTokens,
1144 {
1145 let mut t = TokenStream::new();
1146 for variant in &self.variants {
1147 variant.each(&mut f).to_tokens(&mut t);
1148 }
1149 if self.omitted_variants {
1150 quote!(_ => {}).to_tokens(&mut t);
1151 }
1152 t
1153 }
1154
1155 /// Runs the passed-in function once for each bound field, passing in the
1156 /// result of the previous call, and a `BindingInfo`. generating `match`
1157 /// arms which evaluate to the resulting tokens.
1158 ///
1159 /// This method will ignore variants or fields which are ignored through the
1160 /// `filter` and `filter_variant` methods.
1161 ///
1162 /// If a variant has been ignored, it will return the `init` value.
1163 ///
1164 /// # Example
1165 /// ```
1166 /// # use synstructure::*;
1167 /// let di: syn::DeriveInput = syn::parse_quote! {
1168 /// enum A {
1169 /// B(i32, i32),
1170 /// C(u32),
1171 /// }
1172 /// };
1173 /// let s = Structure::new(&di);
1174 ///
1175 /// assert_eq!(
1176 /// s.fold(quote!(0), |acc, bi| quote!(#acc + #bi)).to_string(),
1177 ///
1178 /// quote!{
1179 /// A::B(ref __binding_0, ref __binding_1,) => {
1180 /// 0 + __binding_0 + __binding_1
1181 /// }
1182 /// A::C(ref __binding_0,) => {
1183 /// 0 + __binding_0
1184 /// }
1185 /// }.to_string()
1186 /// );
1187 /// ```
1188 pub fn fold<F, I, R>(&self, init: I, mut f: F) -> TokenStream
1189 where
1190 F: FnMut(TokenStream, &BindingInfo<'_>) -> R,
1191 I: ToTokens,
1192 R: ToTokens,
1193 {
1194 let mut t = TokenStream::new();
1195 for variant in &self.variants {
1196 variant.fold(&init, &mut f).to_tokens(&mut t);
1197 }
1198 if self.omitted_variants {
1199 quote!(_ => { #init }).to_tokens(&mut t);
1200 }
1201 t
1202 }
1203
1204 /// Runs the passed-in function once for each variant, passing in a
1205 /// `VariantInfo`. and generating `match` arms which evaluate the returned
1206 /// tokens.
1207 ///
1208 /// This method will ignore variants and not bind fields which are ignored
1209 /// through the `filter` and `filter_variant` methods.
1210 ///
1211 /// # Example
1212 /// ```
1213 /// # use synstructure::*;
1214 /// let di: syn::DeriveInput = syn::parse_quote! {
1215 /// enum A {
1216 /// B(i32, i32),
1217 /// C(u32),
1218 /// }
1219 /// };
1220 /// let s = Structure::new(&di);
1221 ///
1222 /// assert_eq!(
1223 /// s.each_variant(|v| {
1224 /// let name = &v.ast().ident;
1225 /// quote!(println!(stringify!(#name)))
1226 /// }).to_string(),
1227 ///
1228 /// quote!{
1229 /// A::B(ref __binding_0, ref __binding_1,) => {
1230 /// println!(stringify!(B))
1231 /// }
1232 /// A::C(ref __binding_0,) => {
1233 /// println!(stringify!(C))
1234 /// }
1235 /// }.to_string()
1236 /// );
1237 /// ```
1238 pub fn each_variant<F, R>(&self, mut f: F) -> TokenStream
1239 where
1240 F: FnMut(&VariantInfo<'_>) -> R,
1241 R: ToTokens,
1242 {
1243 let mut t = TokenStream::new();
1244 for variant in &self.variants {
1245 let pat = variant.pat();
1246 let body = f(variant);
1247 quote!(#pat => { #body }).to_tokens(&mut t);
1248 }
1249 if self.omitted_variants {
1250 quote!(_ => {}).to_tokens(&mut t);
1251 }
1252 t
1253 }
1254
1255 /// Filter the bindings created by this `Structure` object. This has 2 effects:
1256 ///
1257 /// * The bindings will no longer appear in match arms generated by methods
1258 /// on this `Structure` or its subobjects.
1259 ///
1260 /// * Impl blocks created with the `bound_impl` or `unsafe_bound_impl`
1261 /// method only consider type parameters referenced in the types of
1262 /// non-filtered fields.
1263 ///
1264 /// # Example
1265 /// ```
1266 /// # use synstructure::*;
1267 /// let di: syn::DeriveInput = syn::parse_quote! {
1268 /// enum A {
1269 /// B{ a: i32, b: i32 },
1270 /// C{ a: u32 },
1271 /// }
1272 /// };
1273 /// let mut s = Structure::new(&di);
1274 ///
1275 /// s.filter(|bi| {
1276 /// bi.ast().ident == Some(quote::format_ident!("a"))
1277 /// });
1278 ///
1279 /// assert_eq!(
1280 /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
1281 ///
1282 /// quote!{
1283 /// A::B{ a: ref __binding_0, .. } => {
1284 /// { println!("{:?}", __binding_0) }
1285 /// }
1286 /// A::C{ a: ref __binding_0, } => {
1287 /// { println!("{:?}", __binding_0) }
1288 /// }
1289 /// }.to_string()
1290 /// );
1291 /// ```
1292 pub fn filter<F>(&mut self, mut f: F) -> &mut Self
1293 where
1294 F: FnMut(&BindingInfo<'_>) -> bool,
1295 {
1296 for variant in &mut self.variants {
1297 variant.filter(&mut f);
1298 }
1299 self
1300 }
1301
1302 /// Iterates all the bindings of this `Structure` object and uses a closure to determine if a
1303 /// binding should be removed. If the closure returns `true` the binding is removed from the
1304 /// structure. If the closure returns `false`, the binding remains in the structure.
1305 ///
1306 /// All the removed bindings are moved to a new `Structure` object which is otherwise identical
1307 /// to the current one. To understand the effects of removing a binding from a structure check
1308 /// the [`Structure::filter`] documentation.
1309 ///
1310 /// # Example
1311 /// ```
1312 /// # use synstructure::*;
1313 /// let di: syn::DeriveInput = syn::parse_quote! {
1314 /// enum A {
1315 /// B{ a: i32, b: i32 },
1316 /// C{ a: u32 },
1317 /// }
1318 /// };
1319 /// let mut with_b = Structure::new(&di);
1320 ///
1321 /// let with_a = with_b.drain_filter(|bi| {
1322 /// bi.ast().ident == Some(quote::format_ident!("a"))
1323 /// });
1324 ///
1325 /// assert_eq!(
1326 /// with_a.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
1327 ///
1328 /// quote!{
1329 /// A::B{ a: ref __binding_0, .. } => {
1330 /// { println!("{:?}", __binding_0) }
1331 /// }
1332 /// A::C{ a: ref __binding_0, } => {
1333 /// { println!("{:?}", __binding_0) }
1334 /// }
1335 /// }.to_string()
1336 /// );
1337 ///
1338 /// assert_eq!(
1339 /// with_b.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
1340 ///
1341 /// quote!{
1342 /// A::B{ b: ref __binding_1, .. } => {
1343 /// { println!("{:?}", __binding_1) }
1344 /// }
1345 /// A::C{ .. } => {
1346 ///
1347 /// }
1348 /// }.to_string()
1349 /// );
1350 /// ```
1351 #[allow(clippy::return_self_not_must_use)]
1352 pub fn drain_filter<F>(&mut self, mut f: F) -> Self
1353 where
1354 F: FnMut(&BindingInfo<'_>) -> bool,
1355 {
1356 Self {
1357 variants: self
1358 .variants
1359 .iter_mut()
1360 .map(|variant| variant.drain_filter(&mut f))
1361 .collect(),
1362 omitted_variants: self.omitted_variants,
1363 underscore_const: self.underscore_const,
1364 ast: self.ast,
1365 extra_impl: self.extra_impl.clone(),
1366 extra_predicates: self.extra_predicates.clone(),
1367 add_bounds: self.add_bounds,
1368 }
1369 }
1370
1371 /// Specify additional where predicate bounds which should be generated by
1372 /// impl-generating functions such as `gen_impl`, `bound_impl`, and
1373 /// `unsafe_bound_impl`.
1374 ///
1375 /// # Example
1376 /// ```
1377 /// # use synstructure::*;
1378 /// let di: syn::DeriveInput = syn::parse_quote! {
1379 /// enum A<T, U> {
1380 /// B(T),
1381 /// C(Option<U>),
1382 /// }
1383 /// };
1384 /// let mut s = Structure::new(&di);
1385 ///
1386 /// // Add an additional where predicate.
1387 /// s.add_where_predicate(syn::parse_quote!(T: std::fmt::Display));
1388 ///
1389 /// assert_eq!(
1390 /// s.bound_impl(quote!(krate::Trait), quote!{
1391 /// fn a() {}
1392 /// }).to_string(),
1393 /// quote!{
1394 /// #[allow(non_upper_case_globals)]
1395 /// #[doc(hidden)]
1396 /// const _DERIVE_krate_Trait_FOR_A: () = {
1397 /// extern crate krate;
1398 /// impl<T, U> krate::Trait for A<T, U>
1399 /// where T: std::fmt::Display,
1400 /// T: krate::Trait,
1401 /// Option<U>: krate::Trait,
1402 /// U: krate::Trait
1403 /// {
1404 /// fn a() {}
1405 /// }
1406 /// };
1407 /// }.to_string()
1408 /// );
1409 /// ```
1410 pub fn add_where_predicate(&mut self, pred: WherePredicate) -> &mut Self {
1411 self.extra_predicates.push(pred);
1412 self
1413 }
1414
1415 /// Specify which bounds should be generated by impl-generating functions
1416 /// such as `gen_impl`, `bound_impl`, and `unsafe_bound_impl`.
1417 ///
1418 /// The default behaviour is to generate both field and generic bounds from
1419 /// type parameters.
1420 ///
1421 /// # Example
1422 /// ```
1423 /// # use synstructure::*;
1424 /// let di: syn::DeriveInput = syn::parse_quote! {
1425 /// enum A<T, U> {
1426 /// B(T),
1427 /// C(Option<U>),
1428 /// }
1429 /// };
1430 /// let mut s = Structure::new(&di);
1431 ///
1432 /// // Limit bounds to only generics.
1433 /// s.add_bounds(AddBounds::Generics);
1434 ///
1435 /// assert_eq!(
1436 /// s.bound_impl(quote!(krate::Trait), quote!{
1437 /// fn a() {}
1438 /// }).to_string(),
1439 /// quote!{
1440 /// #[allow(non_upper_case_globals)]
1441 /// #[doc(hidden)]
1442 /// const _DERIVE_krate_Trait_FOR_A: () = {
1443 /// extern crate krate;
1444 /// impl<T, U> krate::Trait for A<T, U>
1445 /// where T: krate::Trait,
1446 /// U: krate::Trait
1447 /// {
1448 /// fn a() {}
1449 /// }
1450 /// };
1451 /// }.to_string()
1452 /// );
1453 /// ```
1454 pub fn add_bounds(&mut self, mode: AddBounds) -> &mut Self {
1455 self.add_bounds = mode;
1456 self
1457 }
1458
1459 /// Filter the variants matched by this `Structure` object. This has 2 effects:
1460 ///
1461 /// * Match arms destructuring these variants will no longer be generated by
1462 /// methods on this `Structure`
1463 ///
1464 /// * Impl blocks created with the `bound_impl` or `unsafe_bound_impl`
1465 /// method only consider type parameters referenced in the types of
1466 /// fields in non-fitered variants.
1467 ///
1468 /// # Example
1469 /// ```
1470 /// # use synstructure::*;
1471 /// let di: syn::DeriveInput = syn::parse_quote! {
1472 /// enum A {
1473 /// B(i32, i32),
1474 /// C(u32),
1475 /// }
1476 /// };
1477 ///
1478 /// let mut s = Structure::new(&di);
1479 ///
1480 /// s.filter_variants(|v| v.ast().ident != "B");
1481 ///
1482 /// assert_eq!(
1483 /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
1484 ///
1485 /// quote!{
1486 /// A::C(ref __binding_0,) => {
1487 /// { println!("{:?}", __binding_0) }
1488 /// }
1489 /// _ => {}
1490 /// }.to_string()
1491 /// );
1492 /// ```
1493 pub fn filter_variants<F>(&mut self, f: F) -> &mut Self
1494 where
1495 F: FnMut(&VariantInfo<'_>) -> bool,
1496 {
1497 let before_len = self.variants.len();
1498 self.variants.retain(f);
1499 if self.variants.len() != before_len {
1500 self.omitted_variants = true;
1501 }
1502 self
1503 }
1504 /// Iterates all the variants of this `Structure` object and uses a closure to determine if a
1505 /// variant should be removed. If the closure returns `true` the variant is removed from the
1506 /// structure. If the closure returns `false`, the variant remains in the structure.
1507 ///
1508 /// All the removed variants are moved to a new `Structure` object which is otherwise identical
1509 /// to the current one. To understand the effects of removing a variant from a structure check
1510 /// the [`Structure::filter_variants`] documentation.
1511 ///
1512 /// # Example
1513 /// ```
1514 /// # use synstructure::*;
1515 /// let di: syn::DeriveInput = syn::parse_quote! {
1516 /// enum A {
1517 /// B(i32, i32),
1518 /// C(u32),
1519 /// }
1520 /// };
1521 ///
1522 /// let mut with_c = Structure::new(&di);
1523 ///
1524 /// let with_b = with_c.drain_filter_variants(|v| v.ast().ident == "B");
1525 ///
1526 /// assert_eq!(
1527 /// with_c.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
1528 ///
1529 /// quote!{
1530 /// A::C(ref __binding_0,) => {
1531 /// { println!("{:?}", __binding_0) }
1532 /// }
1533 /// }.to_string()
1534 /// );
1535 ///
1536 /// assert_eq!(
1537 /// with_b.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
1538 ///
1539 /// quote!{
1540 /// A::B(ref __binding_0, ref __binding_1,) => {
1541 /// { println!("{:?}", __binding_0) }
1542 /// { println!("{:?}", __binding_1) }
1543 /// }
1544 /// }.to_string()
1545 /// );
1546 #[allow(clippy::return_self_not_must_use)]
1547 pub fn drain_filter_variants<F>(&mut self, mut f: F) -> Self
1548 where
1549 F: FnMut(&VariantInfo<'_>) -> bool,
1550 {
1551 let mut other = Self {
1552 variants: vec![],
1553 omitted_variants: self.omitted_variants,
1554 underscore_const: self.underscore_const,
1555 ast: self.ast,
1556 extra_impl: self.extra_impl.clone(),
1557 extra_predicates: self.extra_predicates.clone(),
1558 add_bounds: self.add_bounds,
1559 };
1560
1561 let (other_variants, self_variants) = self.variants.drain(..).partition(&mut f);
1562 other.variants = other_variants;
1563 self.variants = self_variants;
1564
1565 other
1566 }
1567
1568 /// Remove the variant at the given index.
1569 ///
1570 /// # Panics
1571 ///
1572 /// Panics if the index is out of range.
1573 pub fn remove_variant(&mut self, idx: usize) -> &mut Self {
1574 self.variants.remove(idx);
1575 self.omitted_variants = true;
1576 self
1577 }
1578
1579 /// Updates the `BindStyle` for each of the passed-in fields by calling the
1580 /// passed-in function for each `BindingInfo`.
1581 ///
1582 /// # Example
1583 /// ```
1584 /// # use synstructure::*;
1585 /// let di: syn::DeriveInput = syn::parse_quote! {
1586 /// enum A {
1587 /// B(i32, i32),
1588 /// C(u32),
1589 /// }
1590 /// };
1591 /// let mut s = Structure::new(&di);
1592 ///
1593 /// s.bind_with(|bi| BindStyle::RefMut);
1594 ///
1595 /// assert_eq!(
1596 /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
1597 ///
1598 /// quote!{
1599 /// A::B(ref mut __binding_0, ref mut __binding_1,) => {
1600 /// { println!("{:?}", __binding_0) }
1601 /// { println!("{:?}", __binding_1) }
1602 /// }
1603 /// A::C(ref mut __binding_0,) => {
1604 /// { println!("{:?}", __binding_0) }
1605 /// }
1606 /// }.to_string()
1607 /// );
1608 /// ```
1609 pub fn bind_with<F>(&mut self, mut f: F) -> &mut Self
1610 where
1611 F: FnMut(&BindingInfo<'_>) -> BindStyle,
1612 {
1613 for variant in &mut self.variants {
1614 variant.bind_with(&mut f);
1615 }
1616 self
1617 }
1618
1619 /// Updates the binding name for each fo the passed-in fields by calling the
1620 /// passed-in function for each `BindingInfo`.
1621 ///
1622 /// The function will be called with the `BindingInfo` and its index in the
1623 /// enclosing variant.
1624 ///
1625 /// The default name is `__binding_{}` where `{}` is replaced with an
1626 /// increasing number.
1627 ///
1628 /// # Example
1629 /// ```
1630 /// # use synstructure::*;
1631 /// let di: syn::DeriveInput = syn::parse_quote! {
1632 /// enum A {
1633 /// B{ a: i32, b: i32 },
1634 /// C{ a: u32 },
1635 /// }
1636 /// };
1637 /// let mut s = Structure::new(&di);
1638 ///
1639 /// s.binding_name(|bi, i| bi.ident.clone().unwrap());
1640 ///
1641 /// assert_eq!(
1642 /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(),
1643 ///
1644 /// quote!{
1645 /// A::B{ a: ref a, b: ref b, } => {
1646 /// { println!("{:?}", a) }
1647 /// { println!("{:?}", b) }
1648 /// }
1649 /// A::C{ a: ref a, } => {
1650 /// { println!("{:?}", a) }
1651 /// }
1652 /// }.to_string()
1653 /// );
1654 /// ```
1655 pub fn binding_name<F>(&mut self, mut f: F) -> &mut Self
1656 where
1657 F: FnMut(&Field, usize) -> Ident,
1658 {
1659 for variant in &mut self.variants {
1660 variant.binding_name(&mut f);
1661 }
1662 self
1663 }
1664
1665 /// Returns a list of the type parameters which are refrenced in the types
1666 /// of non-filtered fields / variants.
1667 ///
1668 /// # Caveat
1669 ///
1670 /// If the struct contains any macros in type position, all parameters will
1671 /// be considered bound. This is because we cannot determine which type
1672 /// parameters are bound by type macros.
1673 ///
1674 /// # Example
1675 /// ```
1676 /// # use synstructure::*;
1677 /// let di: syn::DeriveInput = syn::parse_quote! {
1678 /// enum A<T, U> {
1679 /// B(T, i32),
1680 /// C(Option<U>),
1681 /// }
1682 /// };
1683 /// let mut s = Structure::new(&di);
1684 ///
1685 /// s.filter_variants(|v| v.ast().ident != "C");
1686 ///
1687 /// assert_eq!(
1688 /// s.referenced_ty_params(),
1689 /// &[&quote::format_ident!("T")]
1690 /// );
1691 /// ```
1692 pub fn referenced_ty_params(&self) -> Vec<&'a Ident> {
1693 let mut flags = Vec::new();
1694 for variant in &self.variants {
1695 for binding in &variant.bindings {
1696 generics_fuse(&mut flags, &binding.seen_generics);
1697 }
1698 }
1699 fetch_generics(&flags, &self.ast.generics)
1700 }
1701
1702 /// Adds an `impl<>` generic parameter.
1703 /// This can be used when the trait to be derived needs some extra generic parameters.
1704 ///
1705 /// # Example
1706 /// ```
1707 /// # use synstructure::*;
1708 /// let di: syn::DeriveInput = syn::parse_quote! {
1709 /// enum A<T, U> {
1710 /// B(T),
1711 /// C(Option<U>),
1712 /// }
1713 /// };
1714 /// let mut s = Structure::new(&di);
1715 /// let generic: syn::GenericParam = syn::parse_quote!(X: krate::AnotherTrait);
1716 ///
1717 /// assert_eq!(
1718 /// s.add_impl_generic(generic)
1719 /// .bound_impl(quote!(krate::Trait<X>),
1720 /// quote!{
1721 /// fn a() {}
1722 /// }
1723 /// ).to_string(),
1724 /// quote!{
1725 /// #[allow(non_upper_case_globals)]
1726 /// #[doc(hidden)]
1727 /// const _DERIVE_krate_Trait_X_FOR_A: () = {
1728 /// extern crate krate;
1729 /// impl<T, U, X: krate::AnotherTrait> krate::Trait<X> for A<T, U>
1730 /// where T : krate :: Trait < X >,
1731 /// Option<U>: krate::Trait<X>,
1732 /// U: krate::Trait<X>
1733 /// {
1734 /// fn a() {}
1735 /// }
1736 /// };
1737 /// }.to_string()
1738 /// );
1739 /// ```
1740 pub fn add_impl_generic(&mut self, param: GenericParam) -> &mut Self {
1741 self.extra_impl.push(param);
1742 self
1743 }
1744
1745 /// Add trait bounds for a trait with the given path for each type parmaeter
1746 /// referenced in the types of non-filtered fields.
1747 ///
1748 /// # Caveat
1749 ///
1750 /// If the method contains any macros in type position, all parameters will
1751 /// be considered bound. This is because we cannot determine which type
1752 /// parameters are bound by type macros.
1753 pub fn add_trait_bounds(
1754 &self,
1755 bound: &TraitBound,
1756 where_clause: &mut Option<WhereClause>,
1757 mode: AddBounds,
1758 ) {
1759 // If we have any explicit where predicates, make sure to add them first.
1760 if !self.extra_predicates.is_empty() {
1761 let clause = get_or_insert_with(&mut *where_clause, || WhereClause {
1762 where_token: Default::default(),
1763 predicates: punctuated::Punctuated::new(),
1764 });
1765 clause
1766 .predicates
1767 .extend(self.extra_predicates.iter().cloned());
1768 }
1769
1770 let mut seen = HashSet::new();
1771 let mut pred = |ty: Type| {
1772 if !seen.contains(&ty) {
1773 seen.insert(ty.clone());
1774
1775 // Add a predicate.
1776 let clause = get_or_insert_with(&mut *where_clause, || WhereClause {
1777 where_token: Default::default(),
1778 predicates: punctuated::Punctuated::new(),
1779 });
1780 clause.predicates.push(WherePredicate::Type(PredicateType {
1781 lifetimes: None,
1782 bounded_ty: ty,
1783 colon_token: Default::default(),
1784 bounds: Some(punctuated::Pair::End(TypeParamBound::Trait(bound.clone())))
1785 .into_iter()
1786 .collect(),
1787 }));
1788 }
1789 };
1790
1791 for variant in &self.variants {
1792 for binding in &variant.bindings {
1793 match mode {
1794 AddBounds::Both | AddBounds::Fields => {
1795 for &seen in &binding.seen_generics {
1796 if seen {
1797 pred(binding.ast().ty.clone());
1798 break;
1799 }
1800 }
1801 }
1802 _ => {}
1803 }
1804
1805 match mode {
1806 AddBounds::Both | AddBounds::Generics => {
1807 for param in binding.referenced_ty_params() {
1808 pred(Type::Path(TypePath {
1809 qself: None,
1810 path: (*param).clone().into(),
1811 }));
1812 }
1813 }
1814 _ => {}
1815 }
1816 }
1817 }
1818 }
1819
1820 /// Configure whether to use `const _` instead of a generated const name in
1821 /// code generated by `gen_impl` and `bound_impl`.
1822 ///
1823 /// This syntax is only supported by rust 1.37, and later versions.
1824 ///
1825 /// Defaults to `false` for backwards compatibility reasons.
1826 ///
1827 /// # Example
1828 ///
1829 /// ```
1830 /// # use synstructure::*;
1831 /// let di: syn::DeriveInput = syn::parse_quote! {
1832 /// struct MyStruct;
1833 /// };
1834 /// let mut s = Structure::new(&di);
1835 ///
1836 /// assert_eq!(
1837 /// s.underscore_const(true)
1838 /// .gen_impl(quote! { gen impl Trait for @Self { } })
1839 /// .to_string(),
1840 /// quote! {
1841 /// const _: () = {
1842 /// impl Trait for MyStruct { }
1843 /// };
1844 /// }
1845 /// .to_string()
1846 /// );
1847 ///
1848 /// assert_eq!(
1849 /// s.underscore_const(false)
1850 /// .gen_impl(quote! { gen impl Trait for @Self { } })
1851 /// .to_string(),
1852 /// quote! {
1853 /// #[allow(non_upper_case_globals)]
1854 /// const _DERIVE_Trait_FOR_MyStruct: () = {
1855 /// impl Trait for MyStruct { }
1856 /// };
1857 /// }
1858 /// .to_string()
1859 /// );
1860 /// ```
1861 pub fn underscore_const(&mut self, enabled: bool) -> &mut Self {
1862 self.underscore_const = enabled;
1863 self
1864 }
1865
1866 /// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
1867 ///
1868 /// Creates an `impl` block with the required generic type fields filled in
1869 /// to implement the trait `path`.
1870 ///
1871 /// This method also adds where clauses to the impl requiring that all
1872 /// referenced type parmaeters implement the trait `path`.
1873 ///
1874 /// # Hygiene and Paths
1875 ///
1876 /// This method wraps the impl block inside of a `const` (see the example
1877 /// below). In this scope, the first segment of the passed-in path is
1878 /// `extern crate`-ed in. If you don't want to generate that `extern crate`
1879 /// item, use a global path.
1880 ///
1881 /// This means that if you are implementing `my_crate::Trait`, you simply
1882 /// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
1883 /// entirety of the definition, you can refer to your crate as `my_crate`.
1884 ///
1885 /// # Caveat
1886 ///
1887 /// If the method contains any macros in type position, all parameters will
1888 /// be considered bound. This is because we cannot determine which type
1889 /// parameters are bound by type macros.
1890 ///
1891 /// # Panics
1892 ///
1893 /// Panics if the path string parameter is not a valid `TraitBound`.
1894 ///
1895 /// # Example
1896 /// ```
1897 /// # use synstructure::*;
1898 /// let di: syn::DeriveInput = syn::parse_quote! {
1899 /// enum A<T, U> {
1900 /// B(T),
1901 /// C(Option<U>),
1902 /// }
1903 /// };
1904 /// let mut s = Structure::new(&di);
1905 ///
1906 /// s.filter_variants(|v| v.ast().ident != "B");
1907 ///
1908 /// assert_eq!(
1909 /// s.bound_impl(quote!(krate::Trait), quote!{
1910 /// fn a() {}
1911 /// }).to_string(),
1912 /// quote!{
1913 /// #[allow(non_upper_case_globals)]
1914 /// #[doc(hidden)]
1915 /// const _DERIVE_krate_Trait_FOR_A: () = {
1916 /// extern crate krate;
1917 /// impl<T, U> krate::Trait for A<T, U>
1918 /// where Option<U>: krate::Trait,
1919 /// U: krate::Trait
1920 /// {
1921 /// fn a() {}
1922 /// }
1923 /// };
1924 /// }.to_string()
1925 /// );
1926 /// ```
1927 pub fn bound_impl<P: ToTokens, B: ToTokens>(&self, path: P, body: B) -> TokenStream {
1928 self.impl_internal(
1929 path.into_token_stream(),
1930 body.into_token_stream(),
1931 quote!(),
1932 None,
1933 )
1934 }
1935
1936 /// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
1937 ///
1938 /// Creates an `impl` block with the required generic type fields filled in
1939 /// to implement the unsafe trait `path`.
1940 ///
1941 /// This method also adds where clauses to the impl requiring that all
1942 /// referenced type parmaeters implement the trait `path`.
1943 ///
1944 /// # Hygiene and Paths
1945 ///
1946 /// This method wraps the impl block inside of a `const` (see the example
1947 /// below). In this scope, the first segment of the passed-in path is
1948 /// `extern crate`-ed in. If you don't want to generate that `extern crate`
1949 /// item, use a global path.
1950 ///
1951 /// This means that if you are implementing `my_crate::Trait`, you simply
1952 /// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
1953 /// entirety of the definition, you can refer to your crate as `my_crate`.
1954 ///
1955 /// # Caveat
1956 ///
1957 /// If the method contains any macros in type position, all parameters will
1958 /// be considered bound. This is because we cannot determine which type
1959 /// parameters are bound by type macros.
1960 ///
1961 /// # Panics
1962 ///
1963 /// Panics if the path string parameter is not a valid `TraitBound`.
1964 ///
1965 /// # Example
1966 /// ```
1967 /// # use synstructure::*;
1968 /// let di: syn::DeriveInput = syn::parse_quote! {
1969 /// enum A<T, U> {
1970 /// B(T),
1971 /// C(Option<U>),
1972 /// }
1973 /// };
1974 /// let mut s = Structure::new(&di);
1975 ///
1976 /// s.filter_variants(|v| v.ast().ident != "B");
1977 ///
1978 /// assert_eq!(
1979 /// s.unsafe_bound_impl(quote!(krate::Trait), quote!{
1980 /// fn a() {}
1981 /// }).to_string(),
1982 /// quote!{
1983 /// #[allow(non_upper_case_globals)]
1984 /// #[doc(hidden)]
1985 /// const _DERIVE_krate_Trait_FOR_A: () = {
1986 /// extern crate krate;
1987 /// unsafe impl<T, U> krate::Trait for A<T, U>
1988 /// where Option<U>: krate::Trait,
1989 /// U: krate::Trait
1990 /// {
1991 /// fn a() {}
1992 /// }
1993 /// };
1994 /// }.to_string()
1995 /// );
1996 /// ```
1997 pub fn unsafe_bound_impl<P: ToTokens, B: ToTokens>(&self, path: P, body: B) -> TokenStream {
1998 self.impl_internal(
1999 path.into_token_stream(),
2000 body.into_token_stream(),
2001 quote!(unsafe),
2002 None,
2003 )
2004 }
2005
2006 /// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
2007 ///
2008 /// Creates an `impl` block with the required generic type fields filled in
2009 /// to implement the trait `path`.
2010 ///
2011 /// This method will not add any where clauses to the impl.
2012 ///
2013 /// # Hygiene and Paths
2014 ///
2015 /// This method wraps the impl block inside of a `const` (see the example
2016 /// below). In this scope, the first segment of the passed-in path is
2017 /// `extern crate`-ed in. If you don't want to generate that `extern crate`
2018 /// item, use a global path.
2019 ///
2020 /// This means that if you are implementing `my_crate::Trait`, you simply
2021 /// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
2022 /// entirety of the definition, you can refer to your crate as `my_crate`.
2023 ///
2024 /// # Panics
2025 ///
2026 /// Panics if the path string parameter is not a valid `TraitBound`.
2027 ///
2028 /// # Example
2029 /// ```
2030 /// # use synstructure::*;
2031 /// let di: syn::DeriveInput = syn::parse_quote! {
2032 /// enum A<T, U> {
2033 /// B(T),
2034 /// C(Option<U>),
2035 /// }
2036 /// };
2037 /// let mut s = Structure::new(&di);
2038 ///
2039 /// s.filter_variants(|v| v.ast().ident != "B");
2040 ///
2041 /// assert_eq!(
2042 /// s.unbound_impl(quote!(krate::Trait), quote!{
2043 /// fn a() {}
2044 /// }).to_string(),
2045 /// quote!{
2046 /// #[allow(non_upper_case_globals)]
2047 /// #[doc(hidden)]
2048 /// const _DERIVE_krate_Trait_FOR_A: () = {
2049 /// extern crate krate;
2050 /// impl<T, U> krate::Trait for A<T, U> {
2051 /// fn a() {}
2052 /// }
2053 /// };
2054 /// }.to_string()
2055 /// );
2056 /// ```
2057 pub fn unbound_impl<P: ToTokens, B: ToTokens>(&self, path: P, body: B) -> TokenStream {
2058 self.impl_internal(
2059 path.into_token_stream(),
2060 body.into_token_stream(),
2061 quote!(),
2062 Some(AddBounds::None),
2063 )
2064 }
2065
2066 /// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
2067 ///
2068 /// Creates an `impl` block with the required generic type fields filled in
2069 /// to implement the unsafe trait `path`.
2070 ///
2071 /// This method will not add any where clauses to the impl.
2072 ///
2073 /// # Hygiene and Paths
2074 ///
2075 /// This method wraps the impl block inside of a `const` (see the example
2076 /// below). In this scope, the first segment of the passed-in path is
2077 /// `extern crate`-ed in. If you don't want to generate that `extern crate`
2078 /// item, use a global path.
2079 ///
2080 /// This means that if you are implementing `my_crate::Trait`, you simply
2081 /// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
2082 /// entirety of the definition, you can refer to your crate as `my_crate`.
2083 ///
2084 /// # Panics
2085 ///
2086 /// Panics if the path string parameter is not a valid `TraitBound`.
2087 ///
2088 /// # Example
2089 /// ```
2090 /// # use synstructure::*;
2091 /// let di: syn::DeriveInput = syn::parse_quote! {
2092 /// enum A<T, U> {
2093 /// B(T),
2094 /// C(Option<U>),
2095 /// }
2096 /// };
2097 /// let mut s = Structure::new(&di);
2098 ///
2099 /// s.filter_variants(|v| v.ast().ident != "B");
2100 ///
2101 /// assert_eq!(
2102 /// s.unsafe_unbound_impl(quote!(krate::Trait), quote!{
2103 /// fn a() {}
2104 /// }).to_string(),
2105 /// quote!{
2106 /// #[allow(non_upper_case_globals)]
2107 /// #[doc(hidden)]
2108 /// const _DERIVE_krate_Trait_FOR_A: () = {
2109 /// extern crate krate;
2110 /// unsafe impl<T, U> krate::Trait for A<T, U> {
2111 /// fn a() {}
2112 /// }
2113 /// };
2114 /// }.to_string()
2115 /// );
2116 /// ```
2117 #[deprecated]
2118 pub fn unsafe_unbound_impl<P: ToTokens, B: ToTokens>(&self, path: P, body: B) -> TokenStream {
2119 self.impl_internal(
2120 path.into_token_stream(),
2121 body.into_token_stream(),
2122 quote!(unsafe),
2123 Some(AddBounds::None),
2124 )
2125 }
2126
2127 fn impl_internal(
2128 &self,
2129 path: TokenStream,
2130 body: TokenStream,
2131 safety: TokenStream,
2132 mode: Option<AddBounds>,
2133 ) -> TokenStream {
2134 let mode = mode.unwrap_or(self.add_bounds);
2135 let name = &self.ast.ident;
2136 let mut gen_clone = self.ast.generics.clone();
2137 gen_clone.params.extend(self.extra_impl.clone().into_iter());
2138 let (impl_generics, _, _) = gen_clone.split_for_impl();
2139 let (_, ty_generics, where_clause) = self.ast.generics.split_for_impl();
2140
2141 let bound = syn::parse2::<TraitBound>(path)
2142 .expect("`path` argument must be a valid rust trait bound");
2143
2144 let mut where_clause = where_clause.cloned();
2145 self.add_trait_bounds(&bound, &mut where_clause, mode);
2146
2147 // This function is smart. If a global path is passed, no extern crate
2148 // statement will be generated, however, a relative path will cause the
2149 // crate which it is relative to to be imported within the current
2150 // scope.
2151 let mut extern_crate = quote!();
2152 if bound.path.leading_colon.is_none() {
2153 if let Some(seg) = bound.path.segments.first() {
2154 let seg = &seg.ident;
2155 extern_crate = quote! { extern crate #seg; };
2156 }
2157 }
2158
2159 let generated = quote! {
2160 #extern_crate
2161 #safety impl #impl_generics #bound for #name #ty_generics #where_clause {
2162 #body
2163 }
2164 };
2165
2166 if self.underscore_const {
2167 quote! {
2168 const _: () = { #generated };
2169 }
2170 } else {
2171 let dummy_const: Ident = sanitize_ident(&format!(
2172 "_DERIVE_{}_FOR_{}",
2173 (&bound).into_token_stream(),
2174 name.into_token_stream(),
2175 ));
2176 quote! {
2177 #[allow(non_upper_case_globals)]
2178 #[doc(hidden)]
2179 const #dummy_const: () = {
2180 #generated
2181 };
2182 }
2183 }
2184 }
2185
2186 /// Generate an impl block for the given struct. This impl block will
2187 /// automatically use hygiene tricks to avoid polluting the caller's
2188 /// namespace, and will automatically add trait bounds for generic type
2189 /// parameters.
2190 ///
2191 /// # Syntax
2192 ///
2193 /// This function accepts its arguments as a `TokenStream`. The recommended way
2194 /// to call this function is passing the result of invoking the `quote!`
2195 /// macro to it.
2196 ///
2197 /// ```ignore
2198 /// s.gen_impl(quote! {
2199 /// // You can write any items which you want to import into scope here.
2200 /// // For example, you may want to include an `extern crate` for the
2201 /// // crate which implements your trait. These items will only be
2202 /// // visible to the code you generate, and won't be exposed to the
2203 /// // consuming crate
2204 /// extern crate krate;
2205 ///
2206 /// // You can also add `use` statements here to bring types or traits
2207 /// // into scope.
2208 /// //
2209 /// // WARNING: Try not to use common names here, because the stable
2210 /// // version of syn does not support hygiene and you could accidentally
2211 /// // shadow types from the caller crate.
2212 /// use krate::Trait as MyTrait;
2213 ///
2214 /// // The actual impl block is a `gen impl` or `gen unsafe impl` block.
2215 /// // You can use `@Self` to refer to the structure's type.
2216 /// gen impl MyTrait for @Self {
2217 /// fn f(&self) { ... }
2218 /// }
2219 /// })
2220 /// ```
2221 ///
2222 /// The most common usage of this trait involves loading the crate the
2223 /// target trait comes from with `extern crate`, and then invoking a `gen
2224 /// impl` block.
2225 ///
2226 /// # Hygiene
2227 ///
2228 /// This method tries to handle hygiene intelligenly for both stable and
2229 /// unstable proc-macro implementations, however there are visible
2230 /// differences.
2231 ///
2232 /// The output of every `gen_impl` function is wrapped in a dummy `const`
2233 /// value, to ensure that it is given its own scope, and any values brought
2234 /// into scope are not leaked to the calling crate.
2235 ///
2236 /// By default, the above invocation may generate an output like the
2237 /// following:
2238 ///
2239 /// ```ignore
2240 /// const _DERIVE_krate_Trait_FOR_Struct: () = {
2241 /// extern crate krate;
2242 /// use krate::Trait as MyTrait;
2243 /// impl<T> MyTrait for Struct<T> where T: MyTrait {
2244 /// fn f(&self) { ... }
2245 /// }
2246 /// };
2247 /// ```
2248 ///
2249 /// The `Structure` may also be configured with the
2250 /// [`Structure::underscore_const`] method to generate `const _` instead.
2251 ///
2252 /// ```ignore
2253 /// const _: () = {
2254 /// extern crate krate;
2255 /// use krate::Trait as MyTrait;
2256 /// impl<T> MyTrait for Struct<T> where T: MyTrait {
2257 /// fn f(&self) { ... }
2258 /// }
2259 /// };
2260 /// ```
2261 ///
2262 /// ### Using the `std` crate
2263 ///
2264 /// If you are using `quote!()` to implement your trait, with the
2265 /// `proc-macro2/nightly` feature, `std` isn't considered to be in scope for
2266 /// your macro. This means that if you use types from `std` in your
2267 /// procedural macro, you'll want to explicitly load it with an `extern
2268 /// crate std;`.
2269 ///
2270 /// ### Absolute paths
2271 ///
2272 /// You should generally avoid using absolute paths in your generated code,
2273 /// as they will resolve very differently when using the stable and nightly
2274 /// versions of `proc-macro2`. Instead, load the crates you need to use
2275 /// explictly with `extern crate` and
2276 ///
2277 /// # Trait Bounds
2278 ///
2279 /// This method will automatically add trait bounds for any type parameters
2280 /// which are referenced within the types of non-ignored fields.
2281 ///
2282 /// Additional type parameters may be added with the generics syntax after
2283 /// the `impl` keyword.
2284 ///
2285 /// ### Type Macro Caveat
2286 ///
2287 /// If the method contains any macros in type position, all parameters will
2288 /// be considered bound. This is because we cannot determine which type
2289 /// parameters are bound by type macros.
2290 ///
2291 /// # Errors
2292 ///
2293 /// This function will generate a `compile_error!` if additional type
2294 /// parameters added by `impl<..>` conflict with generic type parameters on
2295 /// the original struct.
2296 ///
2297 /// # Panics
2298 ///
2299 /// This function will panic if the input `TokenStream` is not well-formed.
2300 ///
2301 /// # Example Usage
2302 ///
2303 /// ```
2304 /// # use synstructure::*;
2305 /// let di: syn::DeriveInput = syn::parse_quote! {
2306 /// enum A<T, U> {
2307 /// B(T),
2308 /// C(Option<U>),
2309 /// }
2310 /// };
2311 /// let mut s = Structure::new(&di);
2312 ///
2313 /// s.filter_variants(|v| v.ast().ident != "B");
2314 ///
2315 /// assert_eq!(
2316 /// s.gen_impl(quote! {
2317 /// extern crate krate;
2318 /// gen impl krate::Trait for @Self {
2319 /// fn a() {}
2320 /// }
2321 /// }).to_string(),
2322 /// quote!{
2323 /// #[allow(non_upper_case_globals)]
2324 /// const _DERIVE_krate_Trait_FOR_A: () = {
2325 /// extern crate krate;
2326 /// impl<T, U> krate::Trait for A<T, U>
2327 /// where
2328 /// Option<U>: krate::Trait,
2329 /// U: krate::Trait
2330 /// {
2331 /// fn a() {}
2332 /// }
2333 /// };
2334 /// }.to_string()
2335 /// );
2336 ///
2337 /// // NOTE: You can also add extra generics after the impl
2338 /// assert_eq!(
2339 /// s.gen_impl(quote! {
2340 /// extern crate krate;
2341 /// gen impl<X: krate::OtherTrait> krate::Trait<X> for @Self
2342 /// where
2343 /// X: Send + Sync,
2344 /// {
2345 /// fn a() {}
2346 /// }
2347 /// }).to_string(),
2348 /// quote!{
2349 /// #[allow(non_upper_case_globals)]
2350 /// const _DERIVE_krate_Trait_X_FOR_A: () = {
2351 /// extern crate krate;
2352 /// impl<X: krate::OtherTrait, T, U> krate::Trait<X> for A<T, U>
2353 /// where
2354 /// X: Send + Sync,
2355 /// Option<U>: krate::Trait<X>,
2356 /// U: krate::Trait<X>
2357 /// {
2358 /// fn a() {}
2359 /// }
2360 /// };
2361 /// }.to_string()
2362 /// );
2363 ///
2364 /// // NOTE: you can generate multiple traits with a single call
2365 /// assert_eq!(
2366 /// s.gen_impl(quote! {
2367 /// extern crate krate;
2368 ///
2369 /// gen impl krate::Trait for @Self {
2370 /// fn a() {}
2371 /// }
2372 ///
2373 /// gen impl krate::OtherTrait for @Self {
2374 /// fn b() {}
2375 /// }
2376 /// }).to_string(),
2377 /// quote!{
2378 /// #[allow(non_upper_case_globals)]
2379 /// const _DERIVE_krate_Trait_FOR_A: () = {
2380 /// extern crate krate;
2381 /// impl<T, U> krate::Trait for A<T, U>
2382 /// where
2383 /// Option<U>: krate::Trait,
2384 /// U: krate::Trait
2385 /// {
2386 /// fn a() {}
2387 /// }
2388 ///
2389 /// impl<T, U> krate::OtherTrait for A<T, U>
2390 /// where
2391 /// Option<U>: krate::OtherTrait,
2392 /// U: krate::OtherTrait
2393 /// {
2394 /// fn b() {}
2395 /// }
2396 /// };
2397 /// }.to_string()
2398 /// );
2399 /// ```
2400 ///
2401 /// Use `add_bounds` to change which bounds are generated.
2402 pub fn gen_impl(&self, cfg: TokenStream) -> TokenStream {
2403 Parser::parse2(
2404 |input: ParseStream<'_>| -> Result<TokenStream> { self.gen_impl_parse(input, true) },
2405 cfg,
2406 )
2407 .expect("Failed to parse gen_impl")
2408 }
2409
2410 fn gen_impl_parse(&self, input: ParseStream<'_>, wrap: bool) -> Result<TokenStream> {
2411 fn parse_prefix(input: ParseStream<'_>) -> Result<Option<Token![unsafe]>> {
2412 if input.parse::<Ident>()? != "gen" {
2413 return Err(input.error("Expected keyword `gen`"));
2414 }
2415 let safety = input.parse::<Option<Token![unsafe]>>()?;
2416 let _ = input.parse::<Token![impl]>()?;
2417 Ok(safety)
2418 }
2419
2420 let mut before = vec![];
2421 loop {
2422 if parse_prefix(&input.fork()).is_ok() {
2423 break;
2424 }
2425 before.push(input.parse::<TokenTree>()?);
2426 }
2427
2428 // Parse the prefix "for real"
2429 let safety = parse_prefix(input)?;
2430
2431 // optional `<>`
2432 let mut generics = input.parse::<Generics>()?;
2433
2434 // @bound
2435 let bound = input.parse::<TraitBound>()?;
2436
2437 // `for @Self`
2438 let _ = input.parse::<Token![for]>()?;
2439 let _ = input.parse::<Token![@]>()?;
2440 let _ = input.parse::<Token![Self]>()?;
2441
2442 // optional `where ...`
2443 generics.where_clause = input.parse()?;
2444
2445 // Body of the impl
2446 let body;
2447 braced!(body in input);
2448 let body = body.parse::<TokenStream>()?;
2449
2450 // Try to parse the next entry in sequence. If this fails, we'll fall
2451 // back to just parsing the entire rest of the TokenStream.
2452 let maybe_next_impl = self.gen_impl_parse(&input.fork(), false);
2453
2454 // Eat tokens to the end. Whether or not our speculative nested parse
2455 // succeeded, we're going to want to consume the rest of our input.
2456 let mut after = input.parse::<TokenStream>()?;
2457 if let Ok(stream) = maybe_next_impl {
2458 after = stream;
2459 }
2460 assert!(input.is_empty(), "Should've consumed the rest of our input");
2461
2462 /* Codegen Logic */
2463 let name = &self.ast.ident;
2464
2465 // Add the generics from the original struct in, and then add any
2466 // additional trait bounds which we need on the type.
2467 if let Err(err) = merge_generics(&mut generics, &self.ast.generics) {
2468 // Report the merge error as a `compile_error!`, as it may be
2469 // triggerable by an end-user.
2470 return Ok(err.to_compile_error());
2471 }
2472
2473 self.add_trait_bounds(&bound, &mut generics.where_clause, self.add_bounds);
2474 let (impl_generics, _, where_clause) = generics.split_for_impl();
2475 let (_, ty_generics, _) = self.ast.generics.split_for_impl();
2476
2477 let generated = quote! {
2478 #(#before)*
2479 #safety impl #impl_generics #bound for #name #ty_generics #where_clause {
2480 #body
2481 }
2482 #after
2483 };
2484
2485 if wrap {
2486 if self.underscore_const {
2487 Ok(quote! {
2488 const _: () = { #generated };
2489 })
2490 } else {
2491 let dummy_const: Ident = sanitize_ident(&format!(
2492 "_DERIVE_{}_FOR_{}",
2493 (&bound).into_token_stream(),
2494 name.into_token_stream(),
2495 ));
2496 Ok(quote! {
2497 #[allow(non_upper_case_globals)]
2498 const #dummy_const: () = {
2499 #generated
2500 };
2501 })
2502 }
2503 } else {
2504 Ok(generated)
2505 }
2506 }
2507}
2508
2509/// Dumps an unpretty version of a tokenstream. Takes any type which implements
2510/// `Display`.
2511///
2512/// This is mostly useful for visualizing the output of a procedural macro, as
2513/// it makes it marginally more readable. It is used in the implementation of
2514/// `test_derive!` to unprettily print the output.
2515///
2516/// # Stability
2517///
2518/// The stability of the output of this function is not guaranteed. Do not
2519/// assert that the output of this function does not change between minor
2520/// versions.
2521///
2522/// # Example
2523///
2524/// ```
2525/// # use quote::quote;
2526/// assert_eq!(
2527/// synstructure::unpretty_print(quote! {
2528/// #[allow(non_upper_case_globals)]
2529/// const _DERIVE_krate_Trait_FOR_A: () = {
2530/// extern crate krate;
2531/// impl<T, U> krate::Trait for A<T, U>
2532/// where
2533/// Option<U>: krate::Trait,
2534/// U: krate::Trait
2535/// {
2536/// fn a() {}
2537/// }
2538/// };
2539/// }),
2540/// "# [
2541/// allow (
2542/// non_upper_case_globals)
2543/// ]
2544/// const _DERIVE_krate_Trait_FOR_A : (
2545/// )
2546/// = {
2547/// extern crate krate ;
2548/// impl < T , U > krate :: Trait for A < T , U > where Option < U > : krate :: Trait , U : krate :: Trait {
2549/// fn a (
2550/// )
2551/// {
2552/// }
2553/// }
2554/// }
2555/// ;
2556/// "
2557/// )
2558/// ```
2559pub fn unpretty_print<T: std::fmt::Display>(ts: T) -> String {
2560 let mut res: String = String::new();
2561
2562 let raw_s: String = ts.to_string();
2563 let mut s: &str = &raw_s[..];
2564 let mut indent: i32 = 0;
2565 while let Some(i: usize) = s.find(&['(', '{', '[', ')', '}', ']', ';'][..]) {
2566 match &s[i..=i] {
2567 "(" | "{" | "[" => indent += 1,
2568 ")" | "}" | "]" => indent -= 1,
2569 _ => {}
2570 }
2571 res.push_str(&s[..=i]);
2572 res.push(ch:'\n');
2573 for _ in 0..indent {
2574 res.push_str(string:" ");
2575 }
2576 s = trim_start_matches(&s[i + 1..], c:' ');
2577 }
2578 res.push_str(string:s);
2579 res
2580}
2581
2582/// `trim_left_matches` has been deprecated in favor of `trim_start_matches`.
2583/// This helper silences the warning, as we need to continue using
2584/// `trim_left_matches` for rust 1.15 support.
2585#[allow(deprecated)]
2586fn trim_start_matches(s: &str, c: char) -> &str {
2587 s.trim_left_matches(c)
2588}
2589
2590/// Helper trait describing values which may be returned by macro implementation
2591/// methods used by this crate's macros.
2592pub trait MacroResult {
2593 /// Convert this result into a `Result` for further processing / validation.
2594 fn into_result(self) -> Result<TokenStream>;
2595
2596 /// Convert this result into a `proc_macro::TokenStream`, ready to return
2597 /// from a native `proc_macro` implementation.
2598 ///
2599 /// If `into_result()` would return an `Err`, this method should instead
2600 /// generate a `compile_error!` invocation to nicely report the error.
2601 ///
2602 /// *This method is available if `synstructure` is built with the
2603 /// `"proc-macro"` feature.*
2604 #[cfg(all(
2605 not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
2606 feature = "proc-macro"
2607 ))]
2608 fn into_stream(self) -> proc_macro::TokenStream
2609 where
2610 Self: Sized,
2611 {
2612 match self.into_result() {
2613 Ok(ts) => ts.into(),
2614 Err(err) => err.to_compile_error().into(),
2615 }
2616 }
2617}
2618
2619#[cfg(all(
2620 not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
2621 feature = "proc-macro"
2622))]
2623impl MacroResult for proc_macro::TokenStream {
2624 fn into_result(self) -> Result<TokenStream> {
2625 Ok(self.into())
2626 }
2627
2628 fn into_stream(self) -> proc_macro::TokenStream {
2629 self
2630 }
2631}
2632
2633impl MacroResult for TokenStream {
2634 fn into_result(self) -> Result<TokenStream> {
2635 Ok(self)
2636 }
2637}
2638
2639impl<T: MacroResult> MacroResult for Result<T> {
2640 fn into_result(self) -> Result<TokenStream> {
2641 match self {
2642 Ok(v: T) => v.into_result(),
2643 Err(err: Error) => Err(err),
2644 }
2645 }
2646}
2647
2648#[cfg(test)]
2649mod tests {
2650 use super::*;
2651
2652 // Regression test for #48
2653 #[test]
2654 fn test_each_enum() {
2655 let di: syn::DeriveInput = syn::parse_quote! {
2656 enum A {
2657 Foo(usize, bool),
2658 Bar(bool, usize),
2659 Baz(usize, bool, usize),
2660 Quux(bool, usize, bool)
2661 }
2662 };
2663 let mut s = Structure::new(&di);
2664
2665 s.filter(|bi| bi.ast().ty.to_token_stream().to_string() == "bool");
2666
2667 assert_eq!(
2668 s.each(|bi| quote!(do_something(#bi))).to_string(),
2669 quote! {
2670 A::Foo(_, ref __binding_1,) => { { do_something(__binding_1) } }
2671 A::Bar(ref __binding_0, ..) => { { do_something(__binding_0) } }
2672 A::Baz(_, ref __binding_1, ..) => { { do_something(__binding_1) } }
2673 A::Quux(ref __binding_0, _, ref __binding_2,) => {
2674 {
2675 do_something(__binding_0)
2676 }
2677 {
2678 do_something(__binding_2)
2679 }
2680 }
2681 }
2682 .to_string()
2683 );
2684 }
2685}
2686