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`).
7 use chalk_ir::{fold::Shift, BoundVar, DebruijnIndex};
11 GenericParams, TypeParamData, TypeParamProvenance, WherePredicate, WherePredicateTypeTarget,
15 resolver::{HasResolver, TypeNs},
16 type_ref::{TraitBoundModifier, TypeRef},
17 GenericDefId, ItemContainerId, Lookup, TraitId, TypeAliasId, TypeParamId,
19 use hir_expand::name::{name, Name};
20 use rustc_hash::FxHashSet;
21 use smallvec::{smallvec, SmallVec};
25 db::HirDatabase, ChalkTraitId, Interner, Substitution, TraitRef, TraitRefExt, TyKind,
29 pub(crate) fn fn_traits(db: &dyn DefDatabase, krate: CrateId) -> impl Iterator<Item = TraitId> {
31 db.lang_item(krate, SmolStr::new_inline("fn")),
32 db.lang_item(krate, SmolStr::new_inline("fn_mut")),
33 db.lang_item(krate, SmolStr::new_inline("fn_once")),
37 .flat_map(|it| it.as_trait())
40 fn direct_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> SmallVec<[TraitId; 4]> {
41 let resolver = trait_.resolver(db);
42 // returning the iterator directly doesn't easily work because of
43 // lifetime problems, but since there usually shouldn't be more than a
44 // few direct traits this should be fine (we could even use some kind of
45 // SmallVec if performance is a concern)
46 let generic_params = db.generic_params(trait_.into());
47 let trait_self = generic_params.find_trait_self_param();
51 .filter_map(|pred| match pred {
52 WherePredicate::ForLifetime { target, bound, .. }
53 | WherePredicate::TypeBound { target, bound } => match target {
54 WherePredicateTypeTarget::TypeRef(type_ref) => match &**type_ref {
55 TypeRef::Path(p) if p == &Path::from(name![Self]) => bound.as_path(),
58 WherePredicateTypeTarget::TypeParam(local_id) if Some(*local_id) == trait_self => {
63 WherePredicate::Lifetime { .. } => None,
65 .filter_map(|(path, bound_modifier)| match bound_modifier {
66 TraitBoundModifier::None => Some(path),
67 TraitBoundModifier::Maybe => None,
69 .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path.mod_path()) {
70 Some(TypeNs::TraitId(t)) => Some(t),
76 fn direct_super_trait_refs(db: &dyn HirDatabase, trait_ref: &TraitRef) -> Vec<TraitRef> {
77 // returning the iterator directly doesn't easily work because of
78 // lifetime problems, but since there usually shouldn't be more than a
79 // few direct traits this should be fine (we could even use some kind of
80 // SmallVec if performance is a concern)
81 let generic_params = db.generic_params(trait_ref.hir_trait_id().into());
82 let trait_self = match generic_params.find_trait_self_param() {
83 Some(p) => TypeParamId { parent: trait_ref.hir_trait_id().into(), local_id: p },
84 None => return Vec::new(),
86 db.generic_predicates_for_param(trait_self, None)
89 pred.as_ref().filter_map(|pred| match pred.skip_binders() {
90 // FIXME: how to correctly handle higher-ranked bounds here?
91 WhereClause::Implemented(tr) => Some(
93 .shifted_out_to(&Interner, DebruijnIndex::ONE)
94 .expect("FIXME unexpected higher-ranked trait bound"),
99 .map(|pred| pred.substitute(&Interner, &trait_ref.substitution))
103 /// Returns an iterator over the whole super trait hierarchy (including the
105 pub fn all_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> SmallVec<[TraitId; 4]> {
106 // we need to take care a bit here to avoid infinite loops in case of cycles
107 // (i.e. if we have `trait A: B; trait B: A;`)
109 let mut result = smallvec![trait_];
111 while let Some(&t) = result.get(i) {
112 // yeah this is quadratic, but trait hierarchies should be flat
113 // enough that this doesn't matter
114 for tt in direct_super_traits(db, t) {
115 if !result.contains(&tt) {
124 /// Given a trait ref (`Self: Trait`), builds all the implied trait refs for
125 /// super traits. The original trait ref will be included. So the difference to
126 /// `all_super_traits` is that we keep track of type parameters; for example if
127 /// we have `Self: Trait<u32, i32>` and `Trait<T, U>: OtherTrait<U>` we'll get
128 /// `Self: OtherTrait<i32>`.
129 pub(super) fn all_super_trait_refs(db: &dyn HirDatabase, trait_ref: TraitRef) -> SuperTraits {
130 SuperTraits { db, seen: iter::once(trait_ref.trait_id).collect(), stack: vec![trait_ref] }
133 pub(super) struct SuperTraits<'a> {
134 db: &'a dyn HirDatabase,
135 stack: Vec<TraitRef>,
136 seen: FxHashSet<ChalkTraitId>,
139 impl<'a> SuperTraits<'a> {
140 fn elaborate(&mut self, trait_ref: &TraitRef) {
141 let mut trait_refs = direct_super_trait_refs(self.db, trait_ref);
142 trait_refs.retain(|tr| !self.seen.contains(&tr.trait_id));
143 self.stack.extend(trait_refs);
147 impl<'a> Iterator for SuperTraits<'a> {
148 type Item = TraitRef;
150 fn next(&mut self) -> Option<Self::Item> {
151 if let Some(next) = self.stack.pop() {
152 self.elaborate(&next);
160 pub(super) fn associated_type_by_name_including_super_traits(
161 db: &dyn HirDatabase,
164 ) -> Option<(TraitRef, TypeAliasId)> {
165 all_super_trait_refs(db, trait_ref).find_map(|t| {
166 let assoc_type = db.trait_data(t.hir_trait_id()).associated_type_by_name(name)?;
167 Some((t, assoc_type))
171 pub(crate) fn generics(db: &dyn DefDatabase, def: GenericDefId) -> Generics {
172 let parent_generics = parent_generic_def(db, def).map(|def| Box::new(generics(db, def)));
173 Generics { def, params: db.generic_params(def), parent_generics }
177 pub(crate) struct Generics {
179 pub(crate) params: Interned<GenericParams>,
180 parent_generics: Option<Box<Generics>>,
184 pub(crate) fn iter<'a>(
186 ) -> impl Iterator<Item = (TypeParamId, &'a TypeParamData)> + 'a {
194 .map(move |(local_id, p)| (TypeParamId { parent: it.def, local_id }, p))
200 .map(move |(local_id, p)| (TypeParamId { parent: self.def, local_id }, p)),
204 pub(crate) fn iter_parent<'a>(
206 ) -> impl Iterator<Item = (TypeParamId, &'a TypeParamData)> + 'a {
207 self.parent_generics.as_ref().into_iter().flat_map(|it| {
211 .map(move |(local_id, p)| (TypeParamId { parent: it.def, local_id }, p))
215 pub(crate) fn len(&self) -> usize {
219 /// (total, parents, child)
220 pub(crate) fn len_split(&self) -> (usize, usize, usize) {
221 let parent = self.parent_generics.as_ref().map_or(0, |p| p.len());
222 let child = self.params.types.len();
223 (parent + child, parent, child)
226 /// (parent total, self param, type param list, impl trait)
227 pub(crate) fn provenance_split(&self) -> (usize, usize, usize, usize) {
228 let parent = self.parent_generics.as_ref().map_or(0, |p| p.len());
229 let self_params = self
233 .filter(|(_, p)| p.provenance == TypeParamProvenance::TraitSelf)
235 let list_params = self
239 .filter(|(_, p)| p.provenance == TypeParamProvenance::TypeParamList)
241 let impl_trait_params = self
245 .filter(|(_, p)| p.provenance == TypeParamProvenance::ArgumentImplTrait)
247 (parent, self_params, list_params, impl_trait_params)
250 pub(crate) fn param_idx(&self, param: TypeParamId) -> Option<usize> {
251 Some(self.find_param(param)?.0)
254 fn find_param(&self, param: TypeParamId) -> Option<(usize, &TypeParamData)> {
255 if param.parent == self.def {
256 let (idx, (_local_id, data)) = self
261 .find(|(_, (idx, _))| *idx == param.local_id)
263 let (_total, parent_len, _child) = self.len_split();
264 Some((parent_len + idx, data))
266 self.parent_generics.as_ref().and_then(|g| g.find_param(param))
270 /// Returns a Substitution that replaces each parameter by a bound variable.
271 pub(crate) fn bound_vars_subst(&self, debruijn: DebruijnIndex) -> Substitution {
272 Substitution::from_iter(
276 .map(|(idx, _)| TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(&Interner)),
280 /// Returns a Substitution that replaces each parameter by itself (i.e. `Ty::Param`).
281 pub(crate) fn type_params_subst(&self, db: &dyn HirDatabase) -> Substitution {
282 Substitution::from_iter(
284 self.iter().map(|(id, _)| {
285 TyKind::Placeholder(crate::to_placeholder_idx(db, id)).intern(&Interner)
291 fn parent_generic_def(db: &dyn DefDatabase, def: GenericDefId) -> Option<GenericDefId> {
292 let container = match def {
293 GenericDefId::FunctionId(it) => it.lookup(db).container,
294 GenericDefId::TypeAliasId(it) => it.lookup(db).container,
295 GenericDefId::ConstId(it) => it.lookup(db).container,
296 GenericDefId::EnumVariantId(it) => return Some(it.parent.into()),
297 GenericDefId::AdtId(_) | GenericDefId::TraitId(_) | GenericDefId::ImplId(_) => return None,
301 ItemContainerId::ImplId(it) => Some(it.into()),
302 ItemContainerId::TraitId(it) => Some(it.into()),
303 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,