thiserror_impl/
generics.rs

1use proc_macro2::TokenStream;
2use quote::ToTokens;
3use std::collections::btree_map::Entry;
4use std::collections::{BTreeMap as Map, BTreeSet as Set};
5use syn::punctuated::Punctuated;
6use syn::{parse_quote, GenericArgument, Generics, Ident, PathArguments, Token, Type, WhereClause};
7
8pub struct ParamsInScope<'a> {
9    names: Set<&'a Ident>,
10}
11
12impl<'a> ParamsInScope<'a> {
13    pub fn new(generics: &'a Generics) -> Self {
14        ParamsInScope {
15            names: generics.type_params().map(|param| &param.ident).collect(),
16        }
17    }
18
19    pub fn intersects(&self, ty: &Type) -> bool {
20        let mut found = false;
21        crawl(self, ty, &mut found);
22        found
23    }
24}
25
26fn crawl(in_scope: &ParamsInScope, ty: &Type, found: &mut bool) {
27    if let Type::Path(ty) = ty {
28        if ty.qself.is_none() {
29            if let Some(ident) = ty.path.get_ident() {
30                if in_scope.names.contains(ident) {
31                    *found = true;
32                }
33            }
34        }
35        for segment in &ty.path.segments {
36            if let PathArguments::AngleBracketed(arguments) = &segment.arguments {
37                for arg in &arguments.args {
38                    if let GenericArgument::Type(ty) = arg {
39                        crawl(in_scope, ty, found);
40                    }
41                }
42            }
43        }
44    }
45}
46
47pub struct InferredBounds {
48    bounds: Map<String, (Set<String>, Punctuated<TokenStream, Token![+]>)>,
49    order: Vec<TokenStream>,
50}
51
52impl InferredBounds {
53    pub fn new() -> Self {
54        InferredBounds {
55            bounds: Map::new(),
56            order: Vec::new(),
57        }
58    }
59
60    pub fn insert(&mut self, ty: impl ToTokens, bound: impl ToTokens) {
61        let ty = ty.to_token_stream();
62        let bound = bound.to_token_stream();
63        let entry = self.bounds.entry(ty.to_string());
64        if let Entry::Vacant(_) = entry {
65            self.order.push(ty);
66        }
67        let (set, tokens) = entry.or_default();
68        if set.insert(bound.to_string()) {
69            tokens.push(bound);
70        }
71    }
72
73    pub fn augment_where_clause(&self, generics: &Generics) -> WhereClause {
74        let mut generics = generics.clone();
75        let where_clause = generics.make_where_clause();
76        for ty in &self.order {
77            let (_set, bounds) = &self.bounds[&ty.to_string()];
78            where_clause.predicates.push(parse_quote!(#ty: #bounds));
79        }
80        generics.where_clause.unwrap()
81    }
82}