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, TypeParamData, TypeParamProvenance, WherePredicate,
12 WherePredicateTypeTarget,
16 resolver::{HasResolver, TypeNs},
17 type_ref::{TraitBoundModifier, TypeRef},
18 ConstParamId, FunctionId, GenericDefId, ItemContainerId, Lookup, TraitId, TypeAliasId,
19 TypeOrConstParamId, TypeParamId,
21 use hir_expand::name::{known, name, Name};
22 use itertools::Either;
23 use rustc_hash::FxHashSet;
24 use smallvec::{smallvec, SmallVec};
28 db::HirDatabase, ChalkTraitId, ConstData, ConstValue, GenericArgData, Interner, Substitution,
29 TraitRef, TraitRefExt, TyKind, WhereClause,
32 pub(crate) fn fn_traits(db: &dyn DefDatabase, krate: CrateId) -> impl Iterator<Item = TraitId> {
34 db.lang_item(krate, SmolStr::new_inline("fn")),
35 db.lang_item(krate, SmolStr::new_inline("fn_mut")),
36 db.lang_item(krate, SmolStr::new_inline("fn_once")),
40 .flat_map(|it| it.as_trait())
43 fn direct_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> SmallVec<[TraitId; 4]> {
44 let resolver = trait_.resolver(db);
45 // returning the iterator directly doesn't easily work because of
46 // lifetime problems, but since there usually shouldn't be more than a
47 // few direct traits this should be fine (we could even use some kind of
48 // SmallVec if performance is a concern)
49 let generic_params = db.generic_params(trait_.into());
50 let trait_self = generic_params.find_trait_self_param();
54 .filter_map(|pred| match pred {
55 WherePredicate::ForLifetime { target, bound, .. }
56 | WherePredicate::TypeBound { target, bound } => match target {
57 WherePredicateTypeTarget::TypeRef(type_ref) => match &**type_ref {
58 TypeRef::Path(p) if p == &Path::from(name![Self]) => bound.as_path(),
61 WherePredicateTypeTarget::TypeOrConstParam(local_id)
62 if Some(*local_id) == trait_self =>
68 WherePredicate::Lifetime { .. } => None,
70 .filter_map(|(path, bound_modifier)| match bound_modifier {
71 TraitBoundModifier::None => Some(path),
72 TraitBoundModifier::Maybe => None,
74 .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path.mod_path()) {
75 Some(TypeNs::TraitId(t)) => Some(t),
81 fn direct_super_trait_refs(db: &dyn HirDatabase, trait_ref: &TraitRef) -> Vec<TraitRef> {
82 // returning the iterator directly doesn't easily work because of
83 // lifetime problems, but since there usually shouldn't be more than a
84 // few direct traits this should be fine (we could even use some kind of
85 // SmallVec if performance is a concern)
86 let generic_params = db.generic_params(trait_ref.hir_trait_id().into());
87 let trait_self = match generic_params.find_trait_self_param() {
88 Some(p) => TypeOrConstParamId { parent: trait_ref.hir_trait_id().into(), local_id: p },
89 None => return Vec::new(),
91 db.generic_predicates_for_param(trait_self.parent, trait_self, None)
94 pred.as_ref().filter_map(|pred| match pred.skip_binders() {
95 // FIXME: how to correctly handle higher-ranked bounds here?
96 WhereClause::Implemented(tr) => Some(
98 .shifted_out_to(Interner, DebruijnIndex::ONE)
99 .expect("FIXME unexpected higher-ranked trait bound"),
104 .map(|pred| pred.substitute(Interner, &trait_ref.substitution))
108 /// Returns an iterator over the whole super trait hierarchy (including the
110 pub fn all_super_traits(db: &dyn DefDatabase, trait_: TraitId) -> SmallVec<[TraitId; 4]> {
111 // we need to take care a bit here to avoid infinite loops in case of cycles
112 // (i.e. if we have `trait A: B; trait B: A;`)
114 let mut result = smallvec![trait_];
116 while let Some(&t) = result.get(i) {
117 // yeah this is quadratic, but trait hierarchies should be flat
118 // enough that this doesn't matter
119 for tt in direct_super_traits(db, t) {
120 if !result.contains(&tt) {
129 /// Given a trait ref (`Self: Trait`), builds all the implied trait refs for
130 /// super traits. The original trait ref will be included. So the difference to
131 /// `all_super_traits` is that we keep track of type parameters; for example if
132 /// we have `Self: Trait<u32, i32>` and `Trait<T, U>: OtherTrait<U>` we'll get
133 /// `Self: OtherTrait<i32>`.
134 pub(super) fn all_super_trait_refs(db: &dyn HirDatabase, trait_ref: TraitRef) -> SuperTraits {
135 SuperTraits { db, seen: iter::once(trait_ref.trait_id).collect(), stack: vec![trait_ref] }
138 pub(super) struct SuperTraits<'a> {
139 db: &'a dyn HirDatabase,
140 stack: Vec<TraitRef>,
141 seen: FxHashSet<ChalkTraitId>,
144 impl<'a> SuperTraits<'a> {
145 fn elaborate(&mut self, trait_ref: &TraitRef) {
146 let mut trait_refs = direct_super_trait_refs(self.db, trait_ref);
147 trait_refs.retain(|tr| !self.seen.contains(&tr.trait_id));
148 self.stack.extend(trait_refs);
152 impl<'a> Iterator for SuperTraits<'a> {
153 type Item = TraitRef;
155 fn next(&mut self) -> Option<Self::Item> {
156 if let Some(next) = self.stack.pop() {
157 self.elaborate(&next);
165 pub(super) fn associated_type_by_name_including_super_traits(
166 db: &dyn HirDatabase,
169 ) -> Option<(TraitRef, TypeAliasId)> {
170 all_super_trait_refs(db, trait_ref).find_map(|t| {
171 let assoc_type = db.trait_data(t.hir_trait_id()).associated_type_by_name(name)?;
172 Some((t, assoc_type))
176 pub(crate) fn generics(db: &dyn DefDatabase, def: GenericDefId) -> Generics {
177 let parent_generics = parent_generic_def(db, def).map(|def| Box::new(generics(db, def)));
178 if parent_generics.is_some() && matches!(def, GenericDefId::TypeAliasId(_)) {
179 let params = db.generic_params(def);
183 .any(|(_, x)| matches!(x, TypeOrConstParamData::ConstParamData(_)))
185 // XXX: treat const generic associated types as not existing to avoid crashes (#11769)
187 // Chalk expects the inner associated type's parameters to come
188 // *before*, not after the trait's generics as we've always done it.
189 // Adapting to this requires a larger refactoring
190 cov_mark::hit!(ignore_gats);
191 return Generics { def, params: Interned::new(Default::default()), parent_generics };
193 return Generics { def, params, parent_generics };
196 Generics { def, params: db.generic_params(def), parent_generics }
200 pub(crate) struct Generics {
202 pub(crate) params: Interned<GenericParams>,
203 parent_generics: Option<Box<Generics>>,
207 // FIXME: we should drop this and handle const and type generics at the same time
208 pub(crate) fn type_iter<'a>(
210 ) -> impl Iterator<Item = (TypeOrConstParamId, &'a TypeParamData)> + 'a {
217 .map(move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p))
220 self.params.type_iter().map(move |(local_id, p)| {
221 (TypeOrConstParamId { parent: self.def, local_id }, p)
226 pub(crate) fn iter_id<'a>(
228 ) -> impl Iterator<Item = Either<TypeParamId, ConstParamId>> + 'a {
229 self.iter().map(|(id, data)| match data {
230 TypeOrConstParamData::TypeParamData(_) => Either::Left(TypeParamId::from_unchecked(id)),
231 TypeOrConstParamData::ConstParamData(_) => {
232 Either::Right(ConstParamId::from_unchecked(id))
237 /// Iterator over types and const params of parent, then self.
238 pub(crate) fn iter<'a>(
240 ) -> impl DoubleEndedIterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
247 .map(move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p))
250 self.params.iter().map(move |(local_id, p)| {
251 (TypeOrConstParamId { parent: self.def, local_id }, p)
256 /// Iterator over types and const params of parent.
257 pub(crate) fn iter_parent<'a>(
259 ) -> impl Iterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
260 self.parent_generics.as_ref().into_iter().flat_map(|it| {
264 .map(move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p))
268 pub(crate) fn len(&self) -> usize {
272 /// (total, parents, child)
273 pub(crate) fn len_split(&self) -> (usize, usize, usize) {
274 let parent = self.parent_generics.as_ref().map_or(0, |p| p.len());
275 let child = self.params.type_or_consts.len();
276 (parent + child, parent, child)
279 /// (parent total, self param, type param list, const param list, impl trait)
280 pub(crate) fn provenance_split(&self) -> (usize, usize, usize, usize, usize) {
281 let parent = self.parent_generics.as_ref().map_or(0, |p| p.len());
282 let self_params = self
285 .filter_map(|x| x.1.type_param())
286 .filter(|p| p.provenance == TypeParamProvenance::TraitSelf)
288 let type_params = self
292 .filter_map(|x| x.1.type_param())
293 .filter(|p| p.provenance == TypeParamProvenance::TypeParamList)
295 let const_params = self.params.iter().filter_map(|x| x.1.const_param()).count();
296 let impl_trait_params = self
299 .filter_map(|x| x.1.type_param())
300 .filter(|p| p.provenance == TypeParamProvenance::ArgumentImplTrait)
302 (parent, self_params, type_params, const_params, impl_trait_params)
305 pub(crate) fn param_idx(&self, param: TypeOrConstParamId) -> Option<usize> {
306 Some(self.find_param(param)?.0)
309 fn find_param(&self, param: TypeOrConstParamId) -> Option<(usize, &TypeOrConstParamData)> {
310 if param.parent == self.def {
311 let (idx, (_local_id, data)) = self
316 .find(|(_, (idx, _))| *idx == param.local_id)
318 let (_total, parent_len, _child) = self.len_split();
319 Some((parent_len + idx, data))
321 self.parent_generics.as_ref().and_then(|g| g.find_param(param))
325 /// Returns a Substitution that replaces each parameter by a bound variable.
326 pub(crate) fn bound_vars_subst(
328 db: &dyn HirDatabase,
329 debruijn: DebruijnIndex,
331 Substitution::from_iter(
333 self.iter_id().enumerate().map(|(idx, id)| match id {
334 Either::Left(_) => GenericArgData::Ty(
335 TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(Interner),
338 Either::Right(id) => GenericArgData::Const(
340 value: ConstValue::BoundVar(BoundVar::new(debruijn, idx)),
341 ty: db.const_param_ty(id),
350 /// Returns a Substitution that replaces each parameter by itself (i.e. `Ty::Param`).
351 pub(crate) fn placeholder_subst(&self, db: &dyn HirDatabase) -> Substitution {
352 Substitution::from_iter(
354 self.iter_id().map(|id| match id {
355 Either::Left(id) => GenericArgData::Ty(
356 TyKind::Placeholder(crate::to_placeholder_idx(db, id.into())).intern(Interner),
359 Either::Right(id) => GenericArgData::Const(
361 value: ConstValue::Placeholder(crate::to_placeholder_idx(db, id.into())),
362 ty: db.const_param_ty(id),
372 fn parent_generic_def(db: &dyn DefDatabase, def: GenericDefId) -> Option<GenericDefId> {
373 let container = match def {
374 GenericDefId::FunctionId(it) => it.lookup(db).container,
375 GenericDefId::TypeAliasId(it) => it.lookup(db).container,
376 GenericDefId::ConstId(it) => it.lookup(db).container,
377 GenericDefId::EnumVariantId(it) => return Some(it.parent.into()),
378 GenericDefId::AdtId(_) | GenericDefId::TraitId(_) | GenericDefId::ImplId(_) => return None,
382 ItemContainerId::ImplId(it) => Some(it.into()),
383 ItemContainerId::TraitId(it) => Some(it.into()),
384 ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
388 pub fn is_fn_unsafe_to_call(db: &dyn HirDatabase, func: FunctionId) -> bool {
389 let data = db.function_data(func);
390 if data.has_unsafe_kw() {
394 match func.lookup(db.upcast()).container {
395 hir_def::ItemContainerId::ExternBlockId(block) => {
396 // Function in an `extern` block are always unsafe to call, except when it has
397 // `"rust-intrinsic"` ABI there are a few exceptions.
398 let id = block.lookup(db.upcast()).id;
399 match id.item_tree(db.upcast())[id.value].abi.as_deref() {
400 Some("rust-intrinsic") => is_intrinsic_fn_unsafe(&data.name),
408 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
409 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
410 // Should be kept in sync with https://github.com/rust-lang/rust/blob/532d2b14c05f9bc20b2d27cbb5f4550d28343a36/compiler/rustc_typeck/src/check/intrinsic.rs#L72-L106
413 known::add_with_overflow,
417 known::caller_location,
421 known::discriminant_value,
429 known::mul_with_overflow,
431 known::ptr_guaranteed_eq,
432 known::ptr_guaranteed_ne,
436 known::saturating_add,
437 known::saturating_sub,
439 known::sub_with_overflow,
443 known::variant_count,