]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/ty.rs
Fix test comment for `while_let_on_iterator`
[rust.git] / clippy_utils / src / ty.rs
1 //! Util methods for [`rustc_middle::ty`]
2
3 #![allow(clippy::module_name_repetitions)]
4
5 use std::collections::HashMap;
6
7 use rustc_ast::ast::Mutability;
8 use rustc_hir as hir;
9 use rustc_hir::def_id::DefId;
10 use rustc_hir::{TyKind, Unsafety};
11 use rustc_infer::infer::TyCtxtInferExt;
12 use rustc_lint::LateContext;
13 use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
14 use rustc_middle::ty::{self, AdtDef, IntTy, Ty, TypeFoldable, UintTy};
15 use rustc_span::sym;
16 use rustc_span::symbol::{Ident, Symbol};
17 use rustc_span::DUMMY_SP;
18 use rustc_trait_selection::traits::query::normalize::AtExt;
19
20 use crate::{match_def_path, must_use_attr};
21
22 pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
23     ty.is_copy_modulo_regions(cx.tcx.at(DUMMY_SP), cx.param_env)
24 }
25
26 /// Checks whether a type can be partially moved.
27 pub fn can_partially_move_ty(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
28     if has_drop(cx, ty) || is_copy(cx, ty) {
29         return false;
30     }
31     match ty.kind() {
32         ty::Param(_) => false,
33         ty::Adt(def, subs) => def.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
34         _ => true,
35     }
36 }
37
38 /// Walks into `ty` and returns `true` if any inner type is the same as `other_ty`
39 pub fn contains_ty(ty: Ty<'_>, other_ty: Ty<'_>) -> bool {
40     ty.walk().any(|inner| match inner.unpack() {
41         GenericArgKind::Type(inner_ty) => ty::TyS::same_type(other_ty, inner_ty),
42         GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
43     })
44 }
45
46 /// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
47 /// constructor.
48 pub fn contains_adt_constructor(ty: Ty<'_>, adt: &AdtDef) -> bool {
49     ty.walk().any(|inner| match inner.unpack() {
50         GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
51         GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
52     })
53 }
54
55 /// Resolves `<T as Iterator>::Item` for `T`
56 /// Do not invoke without first verifying that the type implements `Iterator`
57 pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
58     cx.tcx
59         .get_diagnostic_item(sym::Iterator)
60         .and_then(|iter_did| {
61             cx.tcx.associated_items(iter_did).find_by_name_and_kind(
62                 cx.tcx,
63                 Ident::from_str("Item"),
64                 ty::AssocKind::Type,
65                 iter_did,
66             )
67         })
68         .map(|assoc| {
69             let proj = cx.tcx.mk_projection(assoc.def_id, cx.tcx.mk_substs_trait(ty, &[]));
70             cx.tcx.normalize_erasing_regions(cx.param_env, proj)
71         })
72 }
73
74 /// Returns true if ty has `iter` or `iter_mut` methods
75 pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
76     // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
77     // exists and has the desired signature. Unfortunately FnCtxt is not exported
78     // so we can't use its `lookup_method` method.
79     let into_iter_collections: &[Symbol] = &[
80         sym::vec_type,
81         sym::option_type,
82         sym::result_type,
83         sym::BTreeMap,
84         sym::BTreeSet,
85         sym::vecdeque_type,
86         sym::LinkedList,
87         sym::BinaryHeap,
88         sym::hashset_type,
89         sym::hashmap_type,
90         sym::PathBuf,
91         sym::Path,
92         sym::Receiver,
93     ];
94
95     let ty_to_check = match probably_ref_ty.kind() {
96         ty::Ref(_, ty_to_check, _) => ty_to_check,
97         _ => probably_ref_ty,
98     };
99
100     let def_id = match ty_to_check.kind() {
101         ty::Array(..) => return Some(sym::array),
102         ty::Slice(..) => return Some(sym::slice),
103         ty::Adt(adt, _) => adt.did,
104         _ => return None,
105     };
106
107     for &name in into_iter_collections {
108         if cx.tcx.is_diagnostic_item(name, def_id) {
109             return Some(cx.tcx.item_name(def_id));
110         }
111     }
112     None
113 }
114
115 /// Checks whether a type implements a trait.
116 /// See also `get_trait_def_id`.
117 pub fn implements_trait<'tcx>(
118     cx: &LateContext<'tcx>,
119     ty: Ty<'tcx>,
120     trait_id: DefId,
121     ty_params: &[GenericArg<'tcx>],
122 ) -> bool {
123     // Do not check on infer_types to avoid panic in evaluate_obligation.
124     if ty.has_infer_types() {
125         return false;
126     }
127     let ty = cx.tcx.erase_regions(ty);
128     if ty.has_escaping_bound_vars() {
129         return false;
130     }
131     let ty_params = cx.tcx.mk_substs(ty_params.iter());
132     cx.tcx.type_implements_trait((trait_id, ty, ty_params, cx.param_env))
133 }
134
135 /// Checks whether this type implements `Drop`.
136 pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
137     match ty.ty_adt_def() {
138         Some(def) => def.has_dtor(cx.tcx),
139         None => false,
140     }
141 }
142
143 // Returns whether the type has #[must_use] attribute
144 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
145     match ty.kind() {
146         ty::Adt(ref adt, _) => must_use_attr(&cx.tcx.get_attrs(adt.did)).is_some(),
147         ty::Foreign(ref did) => must_use_attr(&cx.tcx.get_attrs(*did)).is_some(),
148         ty::Slice(ref ty)
149         | ty::Array(ref ty, _)
150         | ty::RawPtr(ty::TypeAndMut { ref ty, .. })
151         | ty::Ref(_, ref ty, _) => {
152             // for the Array case we don't need to care for the len == 0 case
153             // because we don't want to lint functions returning empty arrays
154             is_must_use_ty(cx, *ty)
155         },
156         ty::Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
157         ty::Opaque(ref def_id, _) => {
158             for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) {
159                 if let ty::PredicateKind::Trait(trait_predicate, _) = predicate.kind().skip_binder() {
160                     if must_use_attr(&cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() {
161                         return true;
162                     }
163                 }
164             }
165             false
166         },
167         ty::Dynamic(binder, _) => {
168             for predicate in binder.iter() {
169                 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
170                     if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
171                         return true;
172                     }
173                 }
174             }
175             false
176         },
177         _ => false,
178     }
179 }
180
181 // FIXME: Per https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/infer/at/struct.At.html#method.normalize
182 // this function can be removed once the `normalizie` method does not panic when normalization does
183 // not succeed
184 /// Checks if `Ty` is normalizable. This function is useful
185 /// to avoid crashes on `layout_of`.
186 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
187     is_normalizable_helper(cx, param_env, ty, &mut HashMap::new())
188 }
189
190 fn is_normalizable_helper<'tcx>(
191     cx: &LateContext<'tcx>,
192     param_env: ty::ParamEnv<'tcx>,
193     ty: Ty<'tcx>,
194     cache: &mut HashMap<Ty<'tcx>, bool>,
195 ) -> bool {
196     if let Some(&cached_result) = cache.get(ty) {
197         return cached_result;
198     }
199     // prevent recursive loops, false-negative is better than endless loop leading to stack overflow
200     cache.insert(ty, false);
201     let result = cx.tcx.infer_ctxt().enter(|infcx| {
202         let cause = rustc_middle::traits::ObligationCause::dummy();
203         if infcx.at(&cause, param_env).normalize(ty).is_ok() {
204             match ty.kind() {
205                 ty::Adt(def, substs) => def.variants.iter().all(|variant| {
206                     variant
207                         .fields
208                         .iter()
209                         .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache))
210                 }),
211                 _ => ty.walk().all(|generic_arg| match generic_arg.unpack() {
212                     GenericArgKind::Type(inner_ty) if inner_ty != ty => {
213                         is_normalizable_helper(cx, param_env, inner_ty, cache)
214                     },
215                     _ => true, // if inner_ty == ty, we've already checked it
216                 }),
217             }
218         } else {
219             false
220         }
221     });
222     cache.insert(ty, result);
223     result
224 }
225
226 /// Returns true iff the given type is a primitive (a bool or char, any integer or floating-point
227 /// number type, a str, or an array, slice, or tuple of those types).
228 pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
229     match ty.kind() {
230         ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
231         ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true,
232         ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
233         ty::Tuple(inner_types) => inner_types.types().all(is_recursively_primitive_type),
234         _ => false,
235     }
236 }
237
238 /// Checks if the type is equal to a diagnostic item
239 ///
240 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
241 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
242     match ty.kind() {
243         ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
244         _ => false,
245     }
246 }
247
248 /// Checks if the type is equal to a lang item
249 pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool {
250     match ty.kind() {
251         ty::Adt(adt, _) => cx.tcx.lang_items().require(lang_item).unwrap() == adt.did,
252         _ => false,
253     }
254 }
255
256 /// Return `true` if the passed `typ` is `isize` or `usize`.
257 pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
258     matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
259 }
260
261 /// Checks if type is struct, enum or union type with the given def path.
262 ///
263 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
264 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
265 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
266     match ty.kind() {
267         ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
268         _ => false,
269     }
270 }
271
272 /// Peels off all references on the type. Returns the underlying type and the number of references
273 /// removed.
274 pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
275     fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) {
276         if let ty::Ref(_, ty, _) = ty.kind() {
277             peel(ty, count + 1)
278         } else {
279             (ty, count)
280         }
281     }
282     peel(ty, 0)
283 }
284
285 /// Peels off all references on the type.Returns the underlying type, the number of references
286 /// removed, and whether the pointer is ultimately mutable or not.
287 pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
288     fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
289         match ty.kind() {
290             ty::Ref(_, ty, Mutability::Mut) => f(ty, count + 1, mutability),
291             ty::Ref(_, ty, Mutability::Not) => f(ty, count + 1, Mutability::Not),
292             _ => (ty, count, mutability),
293         }
294     }
295     f(ty, 0, Mutability::Mut)
296 }
297
298 /// Returns `true` if the given type is an `unsafe` function.
299 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
300     match ty.kind() {
301         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
302         _ => false,
303     }
304 }
305
306 /// Returns the base type for HIR references and pointers.
307 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
308     match ty.kind {
309         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
310         _ => ty,
311     }
312 }
313
314 /// Returns the base type for references and raw pointers, and count reference
315 /// depth.
316 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
317     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
318         match ty.kind() {
319             ty::Ref(_, ty, _) => inner(ty, depth + 1),
320             _ => (ty, depth),
321         }
322     }
323     inner(ty, 0)
324 }