]> git.lizzy.rs Git - rust.git/blob - crates/hir-ty/src/utils.rs
fix: Fix panics on GATs involving const generics
[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 parent_params = &parent_generics.as_ref().unwrap().params;
180         let has_consts =
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
186             // (#11769, #12193)
187             // Note: also crashes when the parent has const generics (also even if the GAT
188             // doesn't use them), see `tests::regression::gat_crash_3` for an example.
189             //
190             // Chalk expects the inner associated type's parameters to come
191             // *before*, not after the trait's generics as we've always done it.
192             // Adapting to this requires a larger refactoring
193             cov_mark::hit!(ignore_gats);
194             Generics { def, params: Interned::new(Default::default()), parent_generics }
195         } else {
196             Generics { def, params, parent_generics }
197         };
198     }
199     Generics { def, params: db.generic_params(def), parent_generics }
200 }
201
202 #[derive(Debug)]
203 pub(crate) struct Generics {
204     def: GenericDefId,
205     pub(crate) params: Interned<GenericParams>,
206     parent_generics: Option<Box<Generics>>,
207 }
208
209 impl Generics {
210     pub(crate) fn iter_id<'a>(
211         &'a self,
212     ) -> impl Iterator<Item = Either<TypeParamId, ConstParamId>> + 'a {
213         self.iter().map(|(id, data)| match data {
214             TypeOrConstParamData::TypeParamData(_) => Either::Left(TypeParamId::from_unchecked(id)),
215             TypeOrConstParamData::ConstParamData(_) => {
216                 Either::Right(ConstParamId::from_unchecked(id))
217             }
218         })
219     }
220
221     /// Iterator over types and const params of parent, then self.
222     pub(crate) fn iter<'a>(
223         &'a self,
224     ) -> impl DoubleEndedIterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
225         let to_toc_id = |it: &'a Generics| {
226             move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p)
227         };
228         self.parent_generics()
229             .into_iter()
230             .flat_map(move |it| it.params.iter().map(to_toc_id(it)))
231             .chain(self.params.iter().map(to_toc_id(self)))
232     }
233
234     /// Iterator over types and const params of parent.
235     pub(crate) fn iter_parent<'a>(
236         &'a self,
237     ) -> impl Iterator<Item = (TypeOrConstParamId, &'a TypeOrConstParamData)> + 'a {
238         self.parent_generics().into_iter().flat_map(|it| {
239             let to_toc_id =
240                 move |(local_id, p)| (TypeOrConstParamId { parent: it.def, local_id }, p);
241             it.params.iter().map(to_toc_id)
242         })
243     }
244
245     pub(crate) fn len(&self) -> usize {
246         let parent = self.parent_generics().map_or(0, Generics::len);
247         let child = self.params.type_or_consts.len();
248         parent + child
249     }
250
251     /// (parent total, self param, type param list, const param list, impl trait)
252     pub(crate) fn provenance_split(&self) -> (usize, usize, usize, usize, usize) {
253         let ty_iter = || self.params.iter().filter_map(|x| x.1.type_param());
254
255         let self_params =
256             ty_iter().filter(|p| p.provenance == TypeParamProvenance::TraitSelf).count();
257         let type_params =
258             ty_iter().filter(|p| p.provenance == TypeParamProvenance::TypeParamList).count();
259         let impl_trait_params =
260             ty_iter().filter(|p| p.provenance == TypeParamProvenance::ArgumentImplTrait).count();
261         let const_params = self.params.iter().filter_map(|x| x.1.const_param()).count();
262
263         let parent_len = self.parent_generics().map_or(0, Generics::len);
264         (parent_len, self_params, type_params, const_params, impl_trait_params)
265     }
266
267     pub(crate) fn param_idx(&self, param: TypeOrConstParamId) -> Option<usize> {
268         Some(self.find_param(param)?.0)
269     }
270
271     fn find_param(&self, param: TypeOrConstParamId) -> Option<(usize, &TypeOrConstParamData)> {
272         if param.parent == self.def {
273             let (idx, (_local_id, data)) =
274                 self.params.iter().enumerate().find(|(_, (idx, _))| *idx == param.local_id)?;
275             let parent_len = self.parent_generics().map_or(0, Generics::len);
276             Some((parent_len + idx, data))
277         } else {
278             self.parent_generics().and_then(|g| g.find_param(param))
279         }
280     }
281
282     fn parent_generics(&self) -> Option<&Generics> {
283         self.parent_generics.as_ref().map(|it| &**it)
284     }
285
286     /// Returns a Substitution that replaces each parameter by a bound variable.
287     pub(crate) fn bound_vars_subst(
288         &self,
289         db: &dyn HirDatabase,
290         debruijn: DebruijnIndex,
291     ) -> Substitution {
292         Substitution::from_iter(
293             Interner,
294             self.iter_id().enumerate().map(|(idx, id)| match id {
295                 Either::Left(_) => GenericArgData::Ty(
296                     TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(Interner),
297                 )
298                 .intern(Interner),
299                 Either::Right(id) => GenericArgData::Const(
300                     ConstData {
301                         value: ConstValue::BoundVar(BoundVar::new(debruijn, idx)),
302                         ty: db.const_param_ty(id),
303                     }
304                     .intern(Interner),
305                 )
306                 .intern(Interner),
307             }),
308         )
309     }
310
311     /// Returns a Substitution that replaces each parameter by itself (i.e. `Ty::Param`).
312     pub(crate) fn placeholder_subst(&self, db: &dyn HirDatabase) -> Substitution {
313         Substitution::from_iter(
314             Interner,
315             self.iter_id().map(|id| match id {
316                 Either::Left(id) => GenericArgData::Ty(
317                     TyKind::Placeholder(crate::to_placeholder_idx(db, id.into())).intern(Interner),
318                 )
319                 .intern(Interner),
320                 Either::Right(id) => GenericArgData::Const(
321                     ConstData {
322                         value: ConstValue::Placeholder(crate::to_placeholder_idx(db, id.into())),
323                         ty: db.const_param_ty(id),
324                     }
325                     .intern(Interner),
326                 )
327                 .intern(Interner),
328             }),
329         )
330     }
331 }
332
333 fn parent_generic_def(db: &dyn DefDatabase, def: GenericDefId) -> Option<GenericDefId> {
334     let container = match def {
335         GenericDefId::FunctionId(it) => it.lookup(db).container,
336         GenericDefId::TypeAliasId(it) => it.lookup(db).container,
337         GenericDefId::ConstId(it) => it.lookup(db).container,
338         GenericDefId::EnumVariantId(it) => return Some(it.parent.into()),
339         GenericDefId::AdtId(_) | GenericDefId::TraitId(_) | GenericDefId::ImplId(_) => return None,
340     };
341
342     match container {
343         ItemContainerId::ImplId(it) => Some(it.into()),
344         ItemContainerId::TraitId(it) => Some(it.into()),
345         ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
346     }
347 }
348
349 pub fn is_fn_unsafe_to_call(db: &dyn HirDatabase, func: FunctionId) -> bool {
350     let data = db.function_data(func);
351     if data.has_unsafe_kw() {
352         return true;
353     }
354
355     match func.lookup(db.upcast()).container {
356         hir_def::ItemContainerId::ExternBlockId(block) => {
357             // Function in an `extern` block are always unsafe to call, except when it has
358             // `"rust-intrinsic"` ABI there are a few exceptions.
359             let id = block.lookup(db.upcast()).id;
360             !matches!(
361                 id.item_tree(db.upcast())[id.value].abi.as_deref(),
362                 Some("rust-intrinsic") if !is_intrinsic_fn_unsafe(&data.name)
363             )
364         }
365         _ => false,
366     }
367 }
368
369 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
370 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
371     // Should be kept in sync with https://github.com/rust-lang/rust/blob/532d2b14c05f9bc20b2d27cbb5f4550d28343a36/compiler/rustc_typeck/src/check/intrinsic.rs#L72-L106
372     ![
373         known::abort,
374         known::add_with_overflow,
375         known::bitreverse,
376         known::black_box,
377         known::bswap,
378         known::caller_location,
379         known::ctlz,
380         known::ctpop,
381         known::cttz,
382         known::discriminant_value,
383         known::forget,
384         known::likely,
385         known::maxnumf32,
386         known::maxnumf64,
387         known::min_align_of,
388         known::minnumf32,
389         known::minnumf64,
390         known::mul_with_overflow,
391         known::needs_drop,
392         known::ptr_guaranteed_eq,
393         known::ptr_guaranteed_ne,
394         known::rotate_left,
395         known::rotate_right,
396         known::rustc_peek,
397         known::saturating_add,
398         known::saturating_sub,
399         known::size_of,
400         known::sub_with_overflow,
401         known::type_id,
402         known::type_name,
403         known::unlikely,
404         known::variant_count,
405         known::wrapping_add,
406         known::wrapping_mul,
407         known::wrapping_sub,
408     ]
409     .contains(name)
410 }