errore_impl/
generics.rs

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