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, TypeOrConstParamData, TypeParamProvenance, WherePredicate,
12 WherePredicateTypeTarget,
15 resolver::{HasResolver, TypeNs},
16 type_ref::{TraitBoundModifier, TypeRef},
17 ConstParamId, FunctionId, GenericDefId, ItemContainerId, Lookup, TraitId, TypeAliasId,
18 TypeOrConstParamId, TypeParamId,
20 use hir_expand::name::{known, Name};
21 use itertools::Either;
22 use rustc_hash::FxHashSet;
23 use smallvec::{smallvec, SmallVec};
27 db::HirDatabase, ChalkTraitId, ConstData, ConstValue, GenericArgData, Interner, Substitution,
28 TraitRef, TraitRefExt, TyKind, WhereClause,
31 pub(crate) fn fn_traits(db: &dyn DefDatabase, krate: CrateId) -> impl Iterator<Item = TraitId> {
33 db.lang_item(krate, SmolStr::new_inline("fn")),
34 db.lang_item(krate, SmolStr::new_inline("fn_mut")),
35 db.lang_item(krate, SmolStr::new_inline("fn_once")),
39 .flat_map(|it| it.as_trait())
42 fn direct_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> SmallVec<[TraitId; 4]> {
43 let resolver = trait_.resolver(db);
44 // returning the iterator directly doesn't easily work because of
45 // lifetime problems, but since there usually shouldn't be more than a
46 // few direct traits this should be fine (we could even use some kind of
47 // SmallVec if performance is a concern)
48 let generic_params = db.generic_params(trait_.into());
49 let trait_self = generic_params.find_trait_self_param();
53 .filter_map(|pred| match pred {
54 WherePredicate::ForLifetime { target, bound, .. }
55 | WherePredicate::TypeBound { target, bound } => {
56 let is_trait = match target {
57 WherePredicateTypeTarget::TypeRef(type_ref) => match &**type_ref {
58 TypeRef::Path(p) => p.is_self_type(),
61 WherePredicateTypeTarget::TypeOrConstParam(local_id) => {
62 Some(*local_id) == trait_self
66 true => bound.as_path(),
70 WherePredicate::Lifetime { .. } => None,
72 .filter(|(_, bound_modifier)| matches!(bound_modifier, TraitBoundModifier::None))
73 .filter_map(|(path, _)| match resolver.resolve_path_in_type_ns_fully(db, path.mod_path()) {
74 Some(TypeNs::TraitId(t)) => Some(t),
80 fn direct_super_trait_refs(db: &dyn HirDatabase, trait_ref: &TraitRef) -> Vec<TraitRef> {
81 // returning the iterator directly doesn't easily work because of
82 // lifetime problems, but since there usually shouldn't be more than a
83 // few direct traits this should be fine (we could even use some kind of
84 // SmallVec if performance is a concern)
85 let generic_params = db.generic_params(trait_ref.hir_trait_id().into());
86 let trait_self = match generic_params.find_trait_self_param() {
87 Some(p) => TypeOrConstParamId { parent: trait_ref.hir_trait_id().into(), local_id: p },
88 None => return Vec::new(),
90 db.generic_predicates_for_param(trait_self.parent, trait_self, None)
93 pred.as_ref().filter_map(|pred| match pred.skip_binders() {
94 // FIXME: how to correctly handle higher-ranked bounds here?
95 WhereClause::Implemented(tr) => Some(
97 .shifted_out_to(Interner, DebruijnIndex::ONE)
98 .expect("FIXME unexpected higher-ranked trait bound"),
103 .map(|pred| pred.substitute(Interner, &trait_ref.substitution))
107 /// Returns an iterator over the whole super trait hierarchy (including the
109 pub fn all_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> SmallVec<[TraitId; 4]> {
110 // we need to take care a bit here to avoid infinite loops in case of cycles
111 // (i.e. if we have `trait A: B; trait B: A;`)
113 let mut result = smallvec![trait_];
115 while let Some(&t) = result.get(i) {
116 // yeah this is quadratic, but trait hierarchies should be flat
117 // enough that this doesn't matter
118 for tt in direct_super_traits(db, t) {
119 if !result.contains(&tt) {
128 /// Given a trait ref (`Self: Trait`), builds all the implied trait refs for
129 /// super traits. The original trait ref will be included. So the difference to
130 /// `all_super_traits` is that we keep track of type parameters; for example if
131 /// we have `Self: Trait<u32, i32>` and `Trait<T, U>: OtherTrait<U>` we'll get
132 /// `Self: OtherTrait<i32>`.
133 pub(super) fn all_super_trait_refs(db: &dyn HirDatabase, trait_ref: TraitRef) -> SuperTraits<'_> {
134 SuperTraits { db, seen: iter::once(trait_ref.trait_id).collect(), stack: vec![trait_ref] }
137 pub(super) struct SuperTraits<'a> {
138 db: &'a dyn HirDatabase,
139 stack: Vec<TraitRef>,
140 seen: FxHashSet<ChalkTraitId>,
143 impl<'a> SuperTraits<'a> {
144 fn elaborate(&mut self, trait_ref: &TraitRef) {
145 let mut trait_refs = direct_super_trait_refs(self.db, trait_ref);
146 trait_refs.retain(|tr| !self.seen.contains(&tr.trait_id));
147 self.stack.extend(trait_refs);
151 impl<'a> Iterator for SuperTraits<'a> {
152 type Item = TraitRef;
154 fn next(&mut self) -> Option<Self::Item> {
155 if let Some(next) = self.stack.pop() {
156 self.elaborate(&next);
164 pub(super) fn associated_type_by_name_including_super_traits(
165 db: &dyn HirDatabase,
168 ) -> Option<(TraitRef, TypeAliasId)> {
169 all_super_trait_refs(db, trait_ref).find_map(|t| {
170 let assoc_type = db.trait_data(t.hir_trait_id()).associated_type_by_name(name)?;
171 Some((t, assoc_type))
175 pub(crate) fn generics(db: &dyn DefDatabase, def: GenericDefId) -> Generics {
176 let parent_generics = parent_generic_def(db, def).map(|def| Box::new(generics(db, def)));
177 if parent_generics.is_some() && matches!(def, GenericDefId::TypeAliasId(_)) {
178 let params = db.generic_params(def);
179 let parent_params = &parent_generics.as_ref().unwrap().params;
181 params.iter().any(|(_, x)| matches!(x, TypeOrConstParamData::ConstParamData(_)));
182 let parent_has_consts =
183 parent_params.iter().any(|(_, x)| matches!(x, TypeOrConstParamData::ConstParamData(_)));
184 return if has_consts || parent_has_consts {
185 // XXX: treat const generic associated types as not existing to avoid crashes
188 // Note: Also crashes when the parent has const generics (also even if the GAT
189 // doesn't use them), see `tests::regression::gat_crash_3` for an example.
190 // Avoids that by disabling GATs when the parent (i.e. `impl` block) has
191 // const generics (#12193).
193 // Chalk expects the inner associated type's parameters to come
194 // *before*, not after the trait's generics as we've always done it.
195 // Adapting to this requires a larger refactoring
196 cov_mark::hit!(ignore_gats);
197 Generics { def, params: Interned::new(Default::default()), parent_generics }
199 Generics { def, params, parent_generics }
202 Generics { def, params: db.generic_params(def), parent_generics }
206 pub(crate) struct Generics {
208 pub(crate) params: Interned<GenericParams>,
209 parent_generics: Option<Box<Generics>>,
213 pub(crate) fn iter_id<'a>(
215 ) -> impl Iterator<Item = Either<TypeParamId, ConstParamId>> + 'a {
216 self.iter().map(|(id, data)| match data {
217 TypeOrConstParamData::TypeParamData(_) => Either::Left(TypeParamId::from_unchecked(id)),
218 TypeOrConstParamData::ConstParamData(_) => {
219 Either::Right(ConstParamId::from_unchecked(id))
224 /// Iterator over types and const params of parent, then self.
225 pub(crate) fn iter<'a>(
227 ) -> impl DoubleEndedIterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
228 let to_toc_id = |it: &'a Generics| {
229 move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p)
231 self.parent_generics()
233 .flat_map(move |it| it.params.iter().map(to_toc_id(it)))
234 .chain(self.params.iter().map(to_toc_id(self)))
237 /// Iterator over types and const params of parent.
238 pub(crate) fn iter_parent<'a>(
240 ) -> impl Iterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
241 self.parent_generics().into_iter().flat_map(|it| {
243 move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p);
244 it.params.iter().map(to_toc_id)
248 pub(crate) fn len(&self) -> usize {
249 let parent = self.parent_generics().map_or(0, Generics::len);
250 let child = self.params.type_or_consts.len();
254 /// (parent total, self param, type param list, const param list, impl trait)
255 pub(crate) fn provenance_split(&self) -> (usize, usize, usize, usize, usize) {
256 let ty_iter = || self.params.iter().filter_map(|x| x.1.type_param());
259 ty_iter().filter(|p| p.provenance == TypeParamProvenance::TraitSelf).count();
261 ty_iter().filter(|p| p.provenance == TypeParamProvenance::TypeParamList).count();
262 let impl_trait_params =
263 ty_iter().filter(|p| p.provenance == TypeParamProvenance::ArgumentImplTrait).count();
264 let const_params = self.params.iter().filter_map(|x| x.1.const_param()).count();
266 let parent_len = self.parent_generics().map_or(0, Generics::len);
267 (parent_len, self_params, type_params, const_params, impl_trait_params)
270 pub(crate) fn param_idx(&self, param: TypeOrConstParamId) -> Option<usize> {
271 Some(self.find_param(param)?.0)
274 fn find_param(&self, param: TypeOrConstParamId) -> Option<(usize, &TypeOrConstParamData)> {
275 if param.parent == self.def {
276 let (idx, (_local_id, data)) =
277 self.params.iter().enumerate().find(|(_, (idx, _))| *idx == param.local_id)?;
278 let parent_len = self.parent_generics().map_or(0, Generics::len);
279 Some((parent_len + idx, data))
281 self.parent_generics().and_then(|g| g.find_param(param))
285 fn parent_generics(&self) -> Option<&Generics> {
286 self.parent_generics.as_ref().map(|it| &**it)
289 /// Returns a Substitution that replaces each parameter by a bound variable.
290 pub(crate) fn bound_vars_subst(
292 db: &dyn HirDatabase,
293 debruijn: DebruijnIndex,
295 Substitution::from_iter(
297 self.iter_id().enumerate().map(|(idx, id)| match id {
298 Either::Left(_) => GenericArgData::Ty(
299 TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(Interner),
302 Either::Right(id) => GenericArgData::Const(
304 value: ConstValue::BoundVar(BoundVar::new(debruijn, idx)),
305 ty: db.const_param_ty(id),
314 /// Returns a Substitution that replaces each parameter by itself (i.e. `Ty::Param`).
315 pub(crate) fn placeholder_subst(&self, db: &dyn HirDatabase) -> Substitution {
316 Substitution::from_iter(
318 self.iter_id().map(|id| match id {
319 Either::Left(id) => GenericArgData::Ty(
320 TyKind::Placeholder(crate::to_placeholder_idx(db, id.into())).intern(Interner),
323 Either::Right(id) => GenericArgData::Const(
325 value: ConstValue::Placeholder(crate::to_placeholder_idx(db, id.into())),
326 ty: db.const_param_ty(id),
336 fn parent_generic_def(db: &dyn DefDatabase, def: GenericDefId) -> Option<GenericDefId> {
337 let container = match def {
338 GenericDefId::FunctionId(it) => it.lookup(db).container,
339 GenericDefId::TypeAliasId(it) => it.lookup(db).container,
340 GenericDefId::ConstId(it) => it.lookup(db).container,
341 GenericDefId::EnumVariantId(it) => return Some(it.parent.into()),
342 GenericDefId::AdtId(_) | GenericDefId::TraitId(_) | GenericDefId::ImplId(_) => return None,
346 ItemContainerId::ImplId(it) => Some(it.into()),
347 ItemContainerId::TraitId(it) => Some(it.into()),
348 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
352 pub fn is_fn_unsafe_to_call(db: &dyn HirDatabase, func: FunctionId) -> bool {
353 let data = db.function_data(func);
354 if data.has_unsafe_kw() {
358 match func.lookup(db.upcast()).container {
359 hir_def::ItemContainerId::ExternBlockId(block) => {
360 // Function in an `extern` block are always unsafe to call, except when it has
361 // `"rust-intrinsic"` ABI there are a few exceptions.
362 let id = block.lookup(db.upcast()).id;
364 id.item_tree(db.upcast())[id.value].abi.as_deref(),
365 Some("rust-intrinsic") if !is_intrinsic_fn_unsafe(&data.name)
372 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
373 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
374 // Should be kept in sync with https://github.com/rust-lang/rust/blob/532d2b14c05f9bc20b2d27cbb5f4550d28343a36/compiler/rustc_typeck/src/check/intrinsic.rs#L72-L106
377 known::add_with_overflow,
381 known::caller_location,
385 known::discriminant_value,
393 known::mul_with_overflow,
395 known::ptr_guaranteed_eq,
396 known::ptr_guaranteed_ne,
400 known::saturating_add,
401 known::saturating_sub,
403 known::sub_with_overflow,
407 known::variant_count,