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