]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/ty.rs
Auto merge of #90891 - nbdd0121:format, r=Mark-Simulacrum
[rust.git] / clippy_utils / src / ty.rs
1 //! Util methods for [`rustc_middle::ty`]
2
3 #![allow(clippy::module_name_repetitions)]
4
5 use rustc_ast::ast::Mutability;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_hir as hir;
8 use rustc_hir::def::{CtorKind, DefKind, Res};
9 use rustc_hir::def_id::DefId;
10 use rustc_hir::{Expr, TyKind, Unsafety};
11 use rustc_infer::infer::TyCtxtInferExt;
12 use rustc_lint::LateContext;
13 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
14 use rustc_middle::ty::{
15     self, AdtDef, Binder, FnSig, IntTy, Predicate, PredicateKind, Ty, TyCtxt, TypeFoldable, UintTy,
16 };
17 use rustc_span::symbol::Ident;
18 use rustc_span::{sym, Span, Symbol, DUMMY_SP};
19 use rustc_trait_selection::infer::InferCtxtExt;
20 use rustc_trait_selection::traits::query::normalize::AtExt;
21 use std::iter;
22
23 use crate::{expr_path_res, match_def_path, must_use_attr};
24
25 // Checks if the given type implements copy.
26 pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
27     ty.is_copy_modulo_regions(cx.tcx.at(DUMMY_SP), cx.param_env)
28 }
29
30 /// Checks whether a type can be partially moved.
31 pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
32     if has_drop(cx, ty) || is_copy(cx, ty) {
33         return false;
34     }
35     match ty.kind() {
36         ty::Param(_) => false,
37         ty::Adt(def, subs) => def.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
38         _ => true,
39     }
40 }
41
42 /// Walks into `ty` and returns `true` if any inner type is the same as `other_ty`
43 pub fn contains_ty(ty: Ty<'_>, other_ty: Ty<'_>) -> bool {
44     ty.walk().any(|inner| match inner.unpack() {
45         GenericArgKind::Type(inner_ty) => ty::TyS::same_type(other_ty, inner_ty),
46         GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
47     })
48 }
49
50 /// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
51 /// constructor.
52 pub fn contains_adt_constructor(ty: Ty<'_>, adt: &AdtDef) -> bool {
53     ty.walk().any(|inner| match inner.unpack() {
54         GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
55         GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
56     })
57 }
58
59 /// Resolves `<T as Iterator>::Item` for `T`
60 /// Do not invoke without first verifying that the type implements `Iterator`
61 pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
62     cx.tcx
63         .get_diagnostic_item(sym::Iterator)
64         .and_then(|iter_did| get_associated_type(cx, ty, iter_did, "Item"))
65 }
66
67 /// Returns the associated type `name` for `ty` as an implementation of `trait_id`.
68 /// Do not invoke without first verifying that the type implements the trait.
69 pub fn get_associated_type<'tcx>(
70     cx: &LateContext<'tcx>,
71     ty: Ty<'tcx>,
72     trait_id: DefId,
73     name: &str,
74 ) -> Option<Ty<'tcx>> {
75     cx.tcx
76         .associated_items(trait_id)
77         .find_by_name_and_kind(cx.tcx, Ident::from_str(name), ty::AssocKind::Type, trait_id)
78         .map(|assoc| {
79             let proj = cx.tcx.mk_projection(assoc.def_id, cx.tcx.mk_substs_trait(ty, &[]));
80             cx.tcx.normalize_erasing_regions(cx.param_env, proj)
81         })
82 }
83
84 /// Returns true if ty has `iter` or `iter_mut` methods
85 pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
86     // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
87     // exists and has the desired signature. Unfortunately FnCtxt is not exported
88     // so we can't use its `lookup_method` method.
89     let into_iter_collections: &[Symbol] = &[
90         sym::Vec,
91         sym::Option,
92         sym::Result,
93         sym::BTreeMap,
94         sym::BTreeSet,
95         sym::VecDeque,
96         sym::LinkedList,
97         sym::BinaryHeap,
98         sym::HashSet,
99         sym::HashMap,
100         sym::PathBuf,
101         sym::Path,
102         sym::Receiver,
103     ];
104
105     let ty_to_check = match probably_ref_ty.kind() {
106         ty::Ref(_, ty_to_check, _) => ty_to_check,
107         _ => probably_ref_ty,
108     };
109
110     let def_id = match ty_to_check.kind() {
111         ty::Array(..) => return Some(sym::array),
112         ty::Slice(..) => return Some(sym::slice),
113         ty::Adt(adt, _) => adt.did,
114         _ => return None,
115     };
116
117     for &name in into_iter_collections {
118         if cx.tcx.is_diagnostic_item(name, def_id) {
119             return Some(cx.tcx.item_name(def_id));
120         }
121     }
122     None
123 }
124
125 /// Checks whether a type implements a trait.
126 /// The function returns false in case the type contains an inference variable.
127 ///
128 /// See:
129 /// * [`get_trait_def_id`](super::get_trait_def_id) to get a trait [`DefId`].
130 /// * [Common tools for writing lints] for an example how to use this function and other options.
131 ///
132 /// [Common tools for writing lints]: https://github.com/rust-lang/rust-clippy/blob/master/doc/common_tools_writing_lints.md#checking-if-a-type-implements-a-specific-trait
133 pub fn implements_trait<'tcx>(
134     cx: &LateContext<'tcx>,
135     ty: Ty<'tcx>,
136     trait_id: DefId,
137     ty_params: &[GenericArg<'tcx>],
138 ) -> bool {
139     // Clippy shouldn't have infer types
140     assert!(!ty.needs_infer());
141
142     let ty = cx.tcx.erase_regions(ty);
143     if ty.has_escaping_bound_vars() {
144         return false;
145     }
146     let ty_params = cx.tcx.mk_substs(ty_params.iter());
147     cx.tcx.infer_ctxt().enter(|infcx| {
148         infcx
149             .type_implements_trait(trait_id, ty, ty_params, cx.param_env)
150             .must_apply_modulo_regions()
151     })
152 }
153
154 /// Checks whether this type implements `Drop`.
155 pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
156     match ty.ty_adt_def() {
157         Some(def) => def.has_dtor(cx.tcx),
158         None => false,
159     }
160 }
161
162 // Returns whether the type has #[must_use] attribute
163 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
164     match ty.kind() {
165         ty::Adt(adt, _) => must_use_attr(cx.tcx.get_attrs(adt.did)).is_some(),
166         ty::Foreign(ref did) => must_use_attr(cx.tcx.get_attrs(*did)).is_some(),
167         ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => {
168             // for the Array case we don't need to care for the len == 0 case
169             // because we don't want to lint functions returning empty arrays
170             is_must_use_ty(cx, *ty)
171         },
172         ty::Tuple(substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
173         ty::Opaque(ref def_id, _) => {
174             for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) {
175                 if let ty::PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder() {
176                     if must_use_attr(cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() {
177                         return true;
178                     }
179                 }
180             }
181             false
182         },
183         ty::Dynamic(binder, _) => {
184             for predicate in binder.iter() {
185                 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
186                     if must_use_attr(cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
187                         return true;
188                     }
189                 }
190             }
191             false
192         },
193         _ => false,
194     }
195 }
196
197 // FIXME: Per https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/infer/at/struct.At.html#method.normalize
198 // this function can be removed once the `normalize` method does not panic when normalization does
199 // not succeed
200 /// Checks if `Ty` is normalizable. This function is useful
201 /// to avoid crashes on `layout_of`.
202 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
203     is_normalizable_helper(cx, param_env, ty, &mut FxHashMap::default())
204 }
205
206 fn is_normalizable_helper<'tcx>(
207     cx: &LateContext<'tcx>,
208     param_env: ty::ParamEnv<'tcx>,
209     ty: Ty<'tcx>,
210     cache: &mut FxHashMap<Ty<'tcx>, bool>,
211 ) -> bool {
212     if let Some(&cached_result) = cache.get(ty) {
213         return cached_result;
214     }
215     // prevent recursive loops, false-negative is better than endless loop leading to stack overflow
216     cache.insert(ty, false);
217     let result = cx.tcx.infer_ctxt().enter(|infcx| {
218         let cause = rustc_middle::traits::ObligationCause::dummy();
219         if infcx.at(&cause, param_env).normalize(ty).is_ok() {
220             match ty.kind() {
221                 ty::Adt(def, substs) => def.variants.iter().all(|variant| {
222                     variant
223                         .fields
224                         .iter()
225                         .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache))
226                 }),
227                 _ => ty.walk().all(|generic_arg| match generic_arg.unpack() {
228                     GenericArgKind::Type(inner_ty) if inner_ty != ty => {
229                         is_normalizable_helper(cx, param_env, inner_ty, cache)
230                     },
231                     _ => true, // if inner_ty == ty, we've already checked it
232                 }),
233             }
234         } else {
235             false
236         }
237     });
238     cache.insert(ty, result);
239     result
240 }
241
242 /// Returns `true` if the given type is a non aggregate primitive (a `bool` or `char`, any
243 /// integer or floating-point number type). For checking aggregation of primitive types (e.g.
244 /// tuples and slices of primitive type) see `is_recursively_primitive_type`
245 pub fn is_non_aggregate_primitive_type(ty: Ty<'_>) -> bool {
246     matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_))
247 }
248
249 /// Returns `true` if the given type is a primitive (a `bool` or `char`, any integer or
250 /// floating-point number type, a `str`, or an array, slice, or tuple of those types).
251 pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
252     match ty.kind() {
253         ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
254         ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true,
255         ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
256         ty::Tuple(inner_types) => inner_types.types().all(is_recursively_primitive_type),
257         _ => false,
258     }
259 }
260
261 /// Checks if the type is a reference equals to a diagnostic item
262 pub fn is_type_ref_to_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
263     match ty.kind() {
264         ty::Ref(_, ref_ty, _) => match ref_ty.kind() {
265             ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
266             _ => false,
267         },
268         _ => false,
269     }
270 }
271
272 /// Checks if the type is equal to a diagnostic item. To check if a type implements a
273 /// trait marked with a diagnostic item use [`implements_trait`].
274 ///
275 /// For a further exploitation what diagnostic items are see [diagnostic items] in
276 /// rustc-dev-guide.
277 ///
278 /// ---
279 ///
280 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
281 ///
282 /// [Diagnostic Items]: https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-items.html
283 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
284     match ty.kind() {
285         ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
286         _ => false,
287     }
288 }
289
290 /// Checks if the type is equal to a lang item.
291 ///
292 /// Returns `false` if the `LangItem` is not defined.
293 pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool {
294     match ty.kind() {
295         ty::Adt(adt, _) => cx.tcx.lang_items().require(lang_item).map_or(false, |li| li == adt.did),
296         _ => false,
297     }
298 }
299
300 /// Return `true` if the passed `typ` is `isize` or `usize`.
301 pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
302     matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
303 }
304
305 /// Checks if type is struct, enum or union type with the given def path.
306 ///
307 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
308 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
309 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
310     match ty.kind() {
311         ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
312         _ => false,
313     }
314 }
315
316 /// Peels off all references on the type. Returns the underlying type and the number of references
317 /// removed.
318 pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
319     fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) {
320         if let ty::Ref(_, ty, _) = ty.kind() {
321             peel(ty, count + 1)
322         } else {
323             (ty, count)
324         }
325     }
326     peel(ty, 0)
327 }
328
329 /// Peels off all references on the type.Returns the underlying type, the number of references
330 /// removed, and whether the pointer is ultimately mutable or not.
331 pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
332     fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
333         match ty.kind() {
334             ty::Ref(_, ty, Mutability::Mut) => f(ty, count + 1, mutability),
335             ty::Ref(_, ty, Mutability::Not) => f(ty, count + 1, Mutability::Not),
336             _ => (ty, count, mutability),
337         }
338     }
339     f(ty, 0, Mutability::Mut)
340 }
341
342 /// Returns `true` if the given type is an `unsafe` function.
343 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
344     match ty.kind() {
345         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
346         _ => false,
347     }
348 }
349
350 /// Returns the base type for HIR references and pointers.
351 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
352     match ty.kind {
353         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(mut_ty.ty),
354         _ => ty,
355     }
356 }
357
358 /// Returns the base type for references and raw pointers, and count reference
359 /// depth.
360 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
361     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
362         match ty.kind() {
363             ty::Ref(_, ty, _) => inner(ty, depth + 1),
364             _ => (ty, depth),
365         }
366     }
367     inner(ty, 0)
368 }
369
370 /// Returns `true` if types `a` and `b` are same types having same `Const` generic args,
371 /// otherwise returns `false`
372 pub fn same_type_and_consts<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
373     match (&a.kind(), &b.kind()) {
374         (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
375             if did_a != did_b {
376                 return false;
377             }
378
379             substs_a
380                 .iter()
381                 .zip(substs_b.iter())
382                 .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) {
383                     (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
384                     (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
385                         same_type_and_consts(type_a, type_b)
386                     },
387                     _ => true,
388                 })
389         },
390         _ => a == b,
391     }
392 }
393
394 /// Checks if a given type looks safe to be uninitialized.
395 pub fn is_uninit_value_valid_for_ty(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
396     match ty.kind() {
397         ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
398         ty::Tuple(types) => types.types().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
399         ty::Adt(adt, _) => cx.tcx.lang_items().maybe_uninit() == Some(adt.did),
400         _ => false,
401     }
402 }
403
404 /// Gets an iterator over all predicates which apply to the given item.
405 pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(Predicate<'_>, Span)> {
406     let mut next_id = Some(id);
407     iter::from_fn(move || {
408         next_id.take().map(|id| {
409             let preds = tcx.predicates_of(id);
410             next_id = preds.parent;
411             preds.predicates.iter()
412         })
413     })
414     .flatten()
415 }
416
417 /// A signature for a function like type.
418 #[derive(Clone, Copy)]
419 pub enum ExprFnSig<'tcx> {
420     Sig(Binder<'tcx, FnSig<'tcx>>),
421     Closure(Binder<'tcx, FnSig<'tcx>>),
422     Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>),
423 }
424 impl<'tcx> ExprFnSig<'tcx> {
425     /// Gets the argument type at the given offset.
426     pub fn input(self, i: usize) -> Binder<'tcx, Ty<'tcx>> {
427         match self {
428             Self::Sig(sig) => sig.input(i),
429             Self::Closure(sig) => sig.input(0).map_bound(|ty| ty.tuple_element_ty(i).unwrap()),
430             Self::Trait(inputs, _) => inputs.map_bound(|ty| ty.tuple_element_ty(i).unwrap()),
431         }
432     }
433
434     /// Gets the result type, if one could be found. Note that the result type of a trait may not be
435     /// specified.
436     pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
437         match self {
438             Self::Sig(sig) | Self::Closure(sig) => Some(sig.output()),
439             Self::Trait(_, output) => output,
440         }
441     }
442 }
443
444 /// If the expression is function like, get the signature for it.
445 pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
446     if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = expr_path_res(cx, expr) {
447         Some(ExprFnSig::Sig(cx.tcx.fn_sig(id)))
448     } else {
449         let ty = cx.typeck_results().expr_ty_adjusted(expr).peel_refs();
450         match *ty.kind() {
451             ty::Closure(_, subs) => Some(ExprFnSig::Closure(subs.as_closure().sig())),
452             ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).subst(cx.tcx, subs))),
453             ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig)),
454             ty::Dynamic(bounds, _) => {
455                 let lang_items = cx.tcx.lang_items();
456                 match bounds.principal() {
457                     Some(bound)
458                         if Some(bound.def_id()) == lang_items.fn_trait()
459                             || Some(bound.def_id()) == lang_items.fn_once_trait()
460                             || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
461                     {
462                         let output = bounds
463                             .projection_bounds()
464                             .find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id()))
465                             .map(|p| p.map_bound(|p| p.term.ty().expect("return type was a const")));
466                         Some(ExprFnSig::Trait(bound.map_bound(|b| b.substs.type_at(0)), output))
467                     },
468                     _ => None,
469                 }
470             },
471             ty::Param(_) | ty::Projection(..) => {
472                 let mut inputs = None;
473                 let mut output = None;
474                 let lang_items = cx.tcx.lang_items();
475
476                 for (pred, _) in all_predicates_of(cx.tcx, cx.typeck_results().hir_owner.to_def_id()) {
477                     let mut is_input = false;
478                     if let Some(ty) = pred
479                         .kind()
480                         .map_bound(|pred| match pred {
481                             PredicateKind::Trait(p)
482                                 if (lang_items.fn_trait() == Some(p.def_id())
483                                     || lang_items.fn_mut_trait() == Some(p.def_id())
484                                     || lang_items.fn_once_trait() == Some(p.def_id()))
485                                     && p.self_ty() == ty =>
486                             {
487                                 is_input = true;
488                                 Some(p.trait_ref.substs.type_at(1))
489                             },
490                             PredicateKind::Projection(p)
491                                 if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output()
492                                     && p.projection_ty.self_ty() == ty =>
493                             {
494                                 is_input = false;
495                                 p.term.ty()
496                             },
497                             _ => None,
498                         })
499                         .transpose()
500                     {
501                         if is_input && inputs.is_none() {
502                             inputs = Some(ty);
503                         } else if !is_input && output.is_none() {
504                             output = Some(ty);
505                         } else {
506                             // Multiple different fn trait impls. Is this even allowed?
507                             return None;
508                         }
509                     }
510                 }
511
512                 inputs.map(|ty| ExprFnSig::Trait(ty, output))
513             },
514             _ => None,
515         }
516     }
517 }