1 //! Helper functions for working with def, which don't need to be a separate
2 //! query, but can't be computed directly from `*Data` (ie, which need a `db`).
8 generics::{GenericParams, TypeParamData, TypeParamProvenance, WherePredicateTypeTarget},
10 resolver::{HasResolver, TypeNs},
12 AssocContainerId, GenericDefId, Lookup, TraitId, TypeAliasId, TypeParamId, VariantId,
14 use hir_expand::name::{name, Name};
16 use crate::{db::HirDatabase, GenericPredicate, TraitRef};
18 fn direct_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> Vec<TraitId> {
19 let resolver = trait_.resolver(db);
20 // returning the iterator directly doesn't easily work because of
21 // lifetime problems, but since there usually shouldn't be more than a
22 // few direct traits this should be fine (we could even use some kind of
23 // SmallVec if performance is a concern)
24 let generic_params = db.generic_params(trait_.into());
25 let trait_self = generic_params.find_trait_self_param();
29 .filter_map(|pred| match pred {
30 hir_def::generics::WherePredicate::TypeBound { target, bound } => match target {
31 WherePredicateTypeTarget::TypeRef(TypeRef::Path(p))
32 if p == &Path::from(name![Self]) =>
36 WherePredicateTypeTarget::TypeParam(local_id) if Some(*local_id) == trait_self => {
41 hir_def::generics::WherePredicate::Lifetime { .. } => None,
43 .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path.mod_path()) {
44 Some(TypeNs::TraitId(t)) => Some(t),
50 fn direct_super_trait_refs(db: &dyn HirDatabase, trait_ref: &TraitRef) -> Vec<TraitRef> {
51 // returning the iterator directly doesn't easily work because of
52 // lifetime problems, but since there usually shouldn't be more than a
53 // few direct traits this should be fine (we could even use some kind of
54 // SmallVec if performance is a concern)
55 let generic_params = db.generic_params(trait_ref.trait_.into());
56 let trait_self = match generic_params.find_trait_self_param() {
57 Some(p) => TypeParamId { parent: trait_ref.trait_.into(), local_id: p },
58 None => return Vec::new(),
60 db.generic_predicates_for_param(trait_self)
63 pred.as_ref().filter_map(|pred| match pred {
64 GenericPredicate::Implemented(tr) => Some(tr.clone()),
68 .map(|pred| pred.subst(&trait_ref.substs))
72 /// Returns an iterator over the whole super trait hierarchy (including the
74 pub(super) fn all_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> Vec<TraitId> {
75 // we need to take care a bit here to avoid infinite loops in case of cycles
76 // (i.e. if we have `trait A: B; trait B: A;`)
77 let mut result = vec![trait_];
79 while i < result.len() {
81 // yeah this is quadratic, but trait hierarchies should be flat
82 // enough that this doesn't matter
83 for tt in direct_super_traits(db, t) {
84 if !result.contains(&tt) {
93 /// Given a trait ref (`Self: Trait`), builds all the implied trait refs for
94 /// super traits. The original trait ref will be included. So the difference to
95 /// `all_super_traits` is that we keep track of type parameters; for example if
96 /// we have `Self: Trait<u32, i32>` and `Trait<T, U>: OtherTrait<U>` we'll get
97 /// `Self: OtherTrait<i32>`.
98 pub(super) fn all_super_trait_refs(db: &dyn HirDatabase, trait_ref: TraitRef) -> Vec<TraitRef> {
99 // we need to take care a bit here to avoid infinite loops in case of cycles
100 // (i.e. if we have `trait A: B; trait B: A;`)
101 let mut result = vec![trait_ref];
103 while i < result.len() {
105 // yeah this is quadratic, but trait hierarchies should be flat
106 // enough that this doesn't matter
107 for tt in direct_super_trait_refs(db, t) {
108 if !result.iter().any(|tr| tr.trait_ == tt.trait_) {
117 pub(super) fn associated_type_by_name_including_super_traits(
118 db: &dyn HirDatabase,
121 ) -> Option<(TraitRef, TypeAliasId)> {
122 all_super_trait_refs(db, trait_ref).into_iter().find_map(|t| {
123 let assoc_type = db.trait_data(t.trait_).associated_type_by_name(name)?;
124 Some((t, assoc_type))
128 pub(super) fn variant_data(db: &dyn DefDatabase, var: VariantId) -> Arc<VariantData> {
130 VariantId::StructId(it) => db.struct_data(it).variant_data.clone(),
131 VariantId::UnionId(it) => db.union_data(it).variant_data.clone(),
132 VariantId::EnumVariantId(it) => {
133 db.enum_data(it.parent).variants[it.local_id].variant_data.clone()
138 /// Helper for mutating `Arc<[T]>` (i.e. `Arc::make_mut` for Arc slices).
139 /// The underlying values are cloned if there are other strong references.
140 pub(crate) fn make_mut_slice<T: Clone>(a: &mut Arc<[T]>) -> &mut [T] {
141 if Arc::get_mut(a).is_none() {
142 *a = a.iter().cloned().collect();
144 Arc::get_mut(a).unwrap()
147 pub(crate) fn generics(db: &dyn DefDatabase, def: GenericDefId) -> Generics {
148 let parent_generics = parent_generic_def(db, def).map(|def| Box::new(generics(db, def)));
149 Generics { def, params: db.generic_params(def), parent_generics }
153 pub(crate) struct Generics {
155 pub(crate) params: Arc<GenericParams>,
156 parent_generics: Option<Box<Generics>>,
160 pub(crate) fn iter<'a>(
162 ) -> impl Iterator<Item = (TypeParamId, &'a TypeParamData)> + 'a {
170 .map(move |(local_id, p)| (TypeParamId { parent: it.def, local_id }, p))
176 .map(move |(local_id, p)| (TypeParamId { parent: self.def, local_id }, p)),
180 pub(crate) fn iter_parent<'a>(
182 ) -> impl Iterator<Item = (TypeParamId, &'a TypeParamData)> + 'a {
183 self.parent_generics.as_ref().into_iter().flat_map(|it| {
187 .map(move |(local_id, p)| (TypeParamId { parent: it.def, local_id }, p))
191 pub(crate) fn len(&self) -> usize {
195 /// (total, parents, child)
196 pub(crate) fn len_split(&self) -> (usize, usize, usize) {
197 let parent = self.parent_generics.as_ref().map_or(0, |p| p.len());
198 let child = self.params.types.len();
199 (parent + child, parent, child)
202 /// (parent total, self param, type param list, impl trait)
203 pub(crate) fn provenance_split(&self) -> (usize, usize, usize, usize) {
204 let parent = self.parent_generics.as_ref().map_or(0, |p| p.len());
205 let self_params = self
209 .filter(|(_, p)| p.provenance == TypeParamProvenance::TraitSelf)
211 let list_params = self
215 .filter(|(_, p)| p.provenance == TypeParamProvenance::TypeParamList)
217 let impl_trait_params = self
221 .filter(|(_, p)| p.provenance == TypeParamProvenance::ArgumentImplTrait)
223 (parent, self_params, list_params, impl_trait_params)
226 pub(crate) fn param_idx(&self, param: TypeParamId) -> Option<usize> {
227 Some(self.find_param(param)?.0)
230 fn find_param(&self, param: TypeParamId) -> Option<(usize, &TypeParamData)> {
231 if param.parent == self.def {
232 let (idx, (_local_id, data)) = self
237 .find(|(_, (idx, _))| *idx == param.local_id)
239 let (_total, parent_len, _child) = self.len_split();
240 Some((parent_len + idx, data))
242 self.parent_generics.as_ref().and_then(|g| g.find_param(param))
247 fn parent_generic_def(db: &dyn DefDatabase, def: GenericDefId) -> Option<GenericDefId> {
248 let container = match def {
249 GenericDefId::FunctionId(it) => it.lookup(db).container,
250 GenericDefId::TypeAliasId(it) => it.lookup(db).container,
251 GenericDefId::ConstId(it) => it.lookup(db).container,
252 GenericDefId::EnumVariantId(it) => return Some(it.parent.into()),
253 GenericDefId::AdtId(_) | GenericDefId::TraitId(_) | GenericDefId::ImplId(_) => return None,
257 AssocContainerId::ImplId(it) => Some(it.into()),
258 AssocContainerId::TraitId(it) => Some(it.into()),
259 AssocContainerId::ContainerId(_) => None,