]> git.lizzy.rs Git - rust.git/blob - crates/hir-ty/src/utils.rs
Auto merge of #12605 - erhuve:fix/determine-doc-link-type-at-start, r=erhuve
[rust.git] / crates / hir-ty / src / utils.rs
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`).
3
4 use std::iter;
5
6 use base_db::CrateId;
7 use chalk_ir::{fold::Shift, BoundVar, DebruijnIndex};
8 use hir_def::{
9     db::DefDatabase,
10     generics::{
11         GenericParams, TypeOrConstParamData, TypeParamProvenance, WherePredicate,
12         WherePredicateTypeTarget,
13     },
14     intern::Interned,
15     resolver::{HasResolver, TypeNs},
16     type_ref::{TraitBoundModifier, TypeRef},
17     ConstParamId, FunctionId, GenericDefId, ItemContainerId, Lookup, TraitId, TypeAliasId,
18     TypeOrConstParamId, TypeParamId,
19 };
20 use hir_expand::name::{known, Name};
21 use itertools::Either;
22 use rustc_hash::FxHashSet;
23 use smallvec::{smallvec, SmallVec};
24 use syntax::SmolStr;
25
26 use crate::{
27     db::HirDatabase, ChalkTraitId, ConstData, ConstValue, GenericArgData, Interner, Substitution,
28     TraitRef, TraitRefExt, TyKind, WhereClause,
29 };
30
31 pub(crate) fn fn_traits(db: &dyn DefDatabase, krate: CrateId) -> impl Iterator<Item = TraitId> {
32     [
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")),
36     ]
37     .into_iter()
38     .flatten()
39     .flat_map(|it| it.as_trait())
40 }
41
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();
50     generic_params
51         .where_predicates
52         .iter()
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(),
59                         _ => false,
60                     },
61                     WherePredicateTypeTarget::TypeOrConstParam(local_id) => {
62                         Some(*local_id) == trait_self
63                     }
64                 };
65                 match is_trait {
66                     true => bound.as_path(),
67                     false => None,
68                 }
69             }
70             WherePredicate::Lifetime { .. } => None,
71         })
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),
75             _ => None,
76         })
77         .collect()
78 }
79
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(),
89     };
90     db.generic_predicates_for_param(trait_self.parent, trait_self, None)
91         .iter()
92         .filter_map(|pred| {
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(
96                     tr.clone()
97                         .shifted_out_to(Interner, DebruijnIndex::ONE)
98                         .expect("FIXME unexpected higher-ranked trait bound"),
99                 ),
100                 _ => None,
101             })
102         })
103         .map(|pred| pred.substitute(Interner, &trait_ref.substitution))
104         .collect()
105 }
106
107 /// Returns an iterator over the whole super trait hierarchy (including the
108 /// trait itself).
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;`)
112
113     let mut result = smallvec![trait_];
114     let mut i = 0;
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) {
120                 result.push(tt);
121             }
122         }
123         i += 1;
124     }
125     result
126 }
127
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] }
135 }
136
137 pub(super) struct SuperTraits<'a> {
138     db: &'a dyn HirDatabase,
139     stack: Vec<TraitRef>,
140     seen: FxHashSet<ChalkTraitId>,
141 }
142
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);
148     }
149 }
150
151 impl<'a> Iterator for SuperTraits<'a> {
152     type Item = TraitRef;
153
154     fn next(&mut self) -> Option<Self::Item> {
155         if let Some(next) = self.stack.pop() {
156             self.elaborate(&next);
157             Some(next)
158         } else {
159             None
160         }
161     }
162 }
163
164 pub(super) fn associated_type_by_name_including_super_traits(
165     db: &dyn HirDatabase,
166     trait_ref: TraitRef,
167     name: &Name,
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))
172     })
173 }
174
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 has_consts =
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)
183             //
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 }
189         } else {
190             Generics { def, params, parent_generics }
191         };
192     }
193     Generics { def, params: db.generic_params(def), parent_generics }
194 }
195
196 #[derive(Debug)]
197 pub(crate) struct Generics {
198     def: GenericDefId,
199     pub(crate) params: Interned<GenericParams>,
200     parent_generics: Option<Box<Generics>>,
201 }
202
203 impl Generics {
204     pub(crate) fn iter_id<'a>(
205         &'a self,
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))
211             }
212         })
213     }
214
215     /// Iterator over types and const params of parent, then self.
216     pub(crate) fn iter<'a>(
217         &'a self,
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)
221         };
222         self.parent_generics()
223             .into_iter()
224             .flat_map(move |it| it.params.iter().map(to_toc_id(it)))
225             .chain(self.params.iter().map(to_toc_id(self)))
226     }
227
228     /// Iterator over types and const params of parent.
229     pub(crate) fn iter_parent<'a>(
230         &'a self,
231     ) -> impl Iterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
232         self.parent_generics().into_iter().flat_map(|it| {
233             let to_toc_id =
234                 move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p);
235             it.params.iter().map(to_toc_id)
236         })
237     }
238
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();
242         parent + child
243     }
244
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());
248
249         let self_params =
250             ty_iter().filter(|p| p.provenance == TypeParamProvenance::TraitSelf).count();
251         let type_params =
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();
256
257         let parent_len = self.parent_generics().map_or(0, Generics::len);
258         (parent_len, self_params, type_params, const_params, impl_trait_params)
259     }
260
261     pub(crate) fn param_idx(&self, param: TypeOrConstParamId) -> Option<usize> {
262         Some(self.find_param(param)?.0)
263     }
264
265     fn find_param(&self, param: TypeOrConstParamId) -> Option<(usize, &TypeOrConstParamData)> {
266         if param.parent == self.def {
267             let (idx, (_local_id, data)) = self
268                 .params
269                 .iter()
270                 .enumerate()
271                 .find(|(_, (idx, _))| *idx == param.local_id)
272                 .unwrap();
273             let parent_len = self.parent_generics().map_or(0, Generics::len);
274             Some((parent_len + idx, data))
275         } else {
276             self.parent_generics().and_then(|g| g.find_param(param))
277         }
278     }
279
280     fn parent_generics(&self) -> Option<&Generics> {
281         self.parent_generics.as_ref().map(|it| &**it)
282     }
283
284     /// Returns a Substitution that replaces each parameter by a bound variable.
285     pub(crate) fn bound_vars_subst(
286         &self,
287         db: &dyn HirDatabase,
288         debruijn: DebruijnIndex,
289     ) -> Substitution {
290         Substitution::from_iter(
291             Interner,
292             self.iter_id().enumerate().map(|(idx, id)| match id {
293                 Either::Left(_) => GenericArgData::Ty(
294                     TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(Interner),
295                 )
296                 .intern(Interner),
297                 Either::Right(id) => GenericArgData::Const(
298                     ConstData {
299                         value: ConstValue::BoundVar(BoundVar::new(debruijn, idx)),
300                         ty: db.const_param_ty(id),
301                     }
302                     .intern(Interner),
303                 )
304                 .intern(Interner),
305             }),
306         )
307     }
308
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(
312             Interner,
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),
316                 )
317                 .intern(Interner),
318                 Either::Right(id) => GenericArgData::Const(
319                     ConstData {
320                         value: ConstValue::Placeholder(crate::to_placeholder_idx(db, id.into())),
321                         ty: db.const_param_ty(id),
322                     }
323                     .intern(Interner),
324                 )
325                 .intern(Interner),
326             }),
327         )
328     }
329 }
330
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,
338     };
339
340     match container {
341         ItemContainerId::ImplId(it) => Some(it.into()),
342         ItemContainerId::TraitId(it) => Some(it.into()),
343         ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
344     }
345 }
346
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() {
350         return true;
351     }
352
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;
358             !matches!(
359                 id.item_tree(db.upcast())[id.value].abi.as_deref(),
360                 Some("rust-intrinsic") if !is_intrinsic_fn_unsafe(&data.name)
361             )
362         }
363         _ => false,
364     }
365 }
366
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
370     ![
371         known::abort,
372         known::add_with_overflow,
373         known::bitreverse,
374         known::black_box,
375         known::bswap,
376         known::caller_location,
377         known::ctlz,
378         known::ctpop,
379         known::cttz,
380         known::discriminant_value,
381         known::forget,
382         known::likely,
383         known::maxnumf32,
384         known::maxnumf64,
385         known::min_align_of,
386         known::minnumf32,
387         known::minnumf64,
388         known::mul_with_overflow,
389         known::needs_drop,
390         known::ptr_guaranteed_eq,
391         known::ptr_guaranteed_ne,
392         known::rotate_left,
393         known::rotate_right,
394         known::rustc_peek,
395         known::saturating_add,
396         known::saturating_sub,
397         known::size_of,
398         known::sub_with_overflow,
399         known::type_id,
400         known::type_name,
401         known::unlikely,
402         known::variant_count,
403         known::wrapping_add,
404         known::wrapping_mul,
405         known::wrapping_sub,
406     ]
407     .contains(name)
408 }