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);
180 params.iter().any(|(_, x)| matches!(x, TypeOrConstParamData::ConstParamData(_)));
181 return if has_consts {
182 // XXX: treat const generic associated types as not existing to avoid crashes (#11769)
184 // Chalk expects the inner associated type's parameters to come
185 // *before*, not after the trait's generics as we've always done it.
186 // Adapting to this requires a larger refactoring
187 cov_mark::hit!(ignore_gats);
188 Generics { def, params: Interned::new(Default::default()), parent_generics }
190 Generics { def, params, parent_generics }
193 Generics { def, params: db.generic_params(def), parent_generics }
197 pub(crate) struct Generics {
199 pub(crate) params: Interned<GenericParams>,
200 parent_generics: Option<Box<Generics>>,
204 pub(crate) fn iter_id<'a>(
206 ) -> impl Iterator<Item = Either<TypeParamId, ConstParamId>> + 'a {
207 self.iter().map(|(id, data)| match data {
208 TypeOrConstParamData::TypeParamData(_) => Either::Left(TypeParamId::from_unchecked(id)),
209 TypeOrConstParamData::ConstParamData(_) => {
210 Either::Right(ConstParamId::from_unchecked(id))
215 /// Iterator over types and const params of parent, then self.
216 pub(crate) fn iter<'a>(
218 ) -> impl DoubleEndedIterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
219 let to_toc_id = |it: &'a Generics| {
220 move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p)
222 self.parent_generics()
224 .flat_map(move |it| it.params.iter().map(to_toc_id(it)))
225 .chain(self.params.iter().map(to_toc_id(self)))
228 /// Iterator over types and const params of parent.
229 pub(crate) fn iter_parent<'a>(
231 ) -> impl Iterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
232 self.parent_generics().into_iter().flat_map(|it| {
234 move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p);
235 it.params.iter().map(to_toc_id)
239 pub(crate) fn len(&self) -> usize {
240 let parent = self.parent_generics().map_or(0, Generics::len);
241 let child = self.params.type_or_consts.len();
245 /// (parent total, self param, type param list, const param list, impl trait)
246 pub(crate) fn provenance_split(&self) -> (usize, usize, usize, usize, usize) {
247 let ty_iter = || self.params.iter().filter_map(|x| x.1.type_param());
250 ty_iter().filter(|p| p.provenance == TypeParamProvenance::TraitSelf).count();
252 ty_iter().filter(|p| p.provenance == TypeParamProvenance::TypeParamList).count();
253 let impl_trait_params =
254 ty_iter().filter(|p| p.provenance == TypeParamProvenance::ArgumentImplTrait).count();
255 let const_params = self.params.iter().filter_map(|x| x.1.const_param()).count();
257 let parent_len = self.parent_generics().map_or(0, Generics::len);
258 (parent_len, self_params, type_params, const_params, impl_trait_params)
261 pub(crate) fn param_idx(&self, param: TypeOrConstParamId) -> Option<usize> {
262 Some(self.find_param(param)?.0)
265 fn find_param(&self, param: TypeOrConstParamId) -> Option<(usize, &TypeOrConstParamData)> {
266 if param.parent == self.def {
267 let (idx, (_local_id, data)) = self
271 .find(|(_, (idx, _))| *idx == param.local_id)
273 let parent_len = self.parent_generics().map_or(0, Generics::len);
274 Some((parent_len + idx, data))
276 self.parent_generics().and_then(|g| g.find_param(param))
280 fn parent_generics(&self) -> Option<&Generics> {
281 self.parent_generics.as_ref().map(|it| &**it)
284 /// Returns a Substitution that replaces each parameter by a bound variable.
285 pub(crate) fn bound_vars_subst(
287 db: &dyn HirDatabase,
288 debruijn: DebruijnIndex,
290 Substitution::from_iter(
292 self.iter_id().enumerate().map(|(idx, id)| match id {
293 Either::Left(_) => GenericArgData::Ty(
294 TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(Interner),
297 Either::Right(id) => GenericArgData::Const(
299 value: ConstValue::BoundVar(BoundVar::new(debruijn, idx)),
300 ty: db.const_param_ty(id),
309 /// Returns a Substitution that replaces each parameter by itself (i.e. `Ty::Param`).
310 pub(crate) fn placeholder_subst(&self, db: &dyn HirDatabase) -> Substitution {
311 Substitution::from_iter(
313 self.iter_id().map(|id| match id {
314 Either::Left(id) => GenericArgData::Ty(
315 TyKind::Placeholder(crate::to_placeholder_idx(db, id.into())).intern(Interner),
318 Either::Right(id) => GenericArgData::Const(
320 value: ConstValue::Placeholder(crate::to_placeholder_idx(db, id.into())),
321 ty: db.const_param_ty(id),
331 fn parent_generic_def(db: &dyn DefDatabase, def: GenericDefId) -> Option<GenericDefId> {
332 let container = match def {
333 GenericDefId::FunctionId(it) => it.lookup(db).container,
334 GenericDefId::TypeAliasId(it) => it.lookup(db).container,
335 GenericDefId::ConstId(it) => it.lookup(db).container,
336 GenericDefId::EnumVariantId(it) => return Some(it.parent.into()),
337 GenericDefId::AdtId(_) | GenericDefId::TraitId(_) | GenericDefId::ImplId(_) => return None,
341 ItemContainerId::ImplId(it) => Some(it.into()),
342 ItemContainerId::TraitId(it) => Some(it.into()),
343 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
347 pub fn is_fn_unsafe_to_call(db: &dyn HirDatabase, func: FunctionId) -> bool {
348 let data = db.function_data(func);
349 if data.has_unsafe_kw() {
353 match func.lookup(db.upcast()).container {
354 hir_def::ItemContainerId::ExternBlockId(block) => {
355 // Function in an `extern` block are always unsafe to call, except when it has
356 // `"rust-intrinsic"` ABI there are a few exceptions.
357 let id = block.lookup(db.upcast()).id;
359 id.item_tree(db.upcast())[id.value].abi.as_deref(),
360 Some("rust-intrinsic") if !is_intrinsic_fn_unsafe(&data.name)
367 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
368 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
369 // Should be kept in sync with https://github.com/rust-lang/rust/blob/532d2b14c05f9bc20b2d27cbb5f4550d28343a36/compiler/rustc_typeck/src/check/intrinsic.rs#L72-L106
372 known::add_with_overflow,
376 known::caller_location,
380 known::discriminant_value,
388 known::mul_with_overflow,
390 known::ptr_guaranteed_eq,
391 known::ptr_guaranteed_ne,
395 known::saturating_add,
396 known::saturating_sub,
398 known::sub_with_overflow,
402 known::variant_count,