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