derivative/
utils.rs

1use proc_macro2;
2
3use ast;
4use attr;
5use bound;
6use syn;
7
8/// Make generic with all the generics in the input, plus a bound `T: <trait_path>` for each
9/// generic field type that will be shown.
10pub fn build_impl_generics<F, G, H>(
11    item: &ast::Input,
12    trait_path: &syn::Path,
13    needs_debug_bound: F,
14    field_bound: G,
15    input_bound: H,
16) -> syn::Generics
17where
18    F: Fn(&attr::Field) -> bool,
19    G: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>,
20    H: Fn(&attr::Input) -> Option<&[syn::WherePredicate]>,
21{
22    let generics = bound::without_defaults(item.generics);
23    let generics = bound::with_where_predicates_from_fields(item, &generics, field_bound);
24
25    match input_bound(&item.attrs) {
26        Some(predicates) => bound::with_where_predicates(&generics, predicates),
27        None => bound::with_bound(item, &generics, needs_debug_bound, trait_path),
28    }
29}
30
31/// Construct a name for the inner type parameter that can't collide with any
32/// type parameters of the item. This is achieved by starting with a base and
33/// then concatenating the names of all other type parameters.
34pub fn hygienic_type_parameter(item: &ast::Input, base: &str) -> syn::Ident {
35    let mut typaram = String::with_capacity(150);
36    typaram.push_str(base);
37    let typaram = item.generics.type_params().fold(typaram, |mut acc, ty| {
38        acc.push_str(&format!("{}", &ty.ident));
39        acc
40    });
41
42    syn::Ident::new(&typaram, proc_macro2::Span::call_site())
43}