]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/ty.rs
Fix fallout from not ignoring warnings anymore
[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(ref 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(ref ty)
148         | ty::Array(ref ty, _)
149         | ty::RawPtr(ty::TypeAndMut { ref ty, .. })
150         | ty::Ref(_, ref ty, _) => {
151             // for the Array case we don't need to care for the len == 0 case
152             // because we don't want to lint functions returning empty arrays
153             is_must_use_ty(cx, *ty)
154         },
155         ty::Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
156         ty::Opaque(ref def_id, _) => {
157             for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) {
158                 if let ty::PredicateKind::Trait(trait_predicate, _) = predicate.kind().skip_binder() {
159                     if must_use_attr(&cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() {
160                         return true;
161                     }
162                 }
163             }
164             false
165         },
166         ty::Dynamic(binder, _) => {
167             for predicate in binder.iter() {
168                 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
169                     if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
170                         return true;
171                     }
172                 }
173             }
174             false
175         },
176         _ => false,
177     }
178 }
179
180 // FIXME: Per https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/infer/at/struct.At.html#method.normalize
181 // this function can be removed once the `normalizie` method does not panic when normalization does
182 // not succeed
183 /// Checks if `Ty` is normalizable. This function is useful
184 /// to avoid crashes on `layout_of`.
185 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
186     is_normalizable_helper(cx, param_env, ty, &mut FxHashMap::default())
187 }
188
189 fn is_normalizable_helper<'tcx>(
190     cx: &LateContext<'tcx>,
191     param_env: ty::ParamEnv<'tcx>,
192     ty: Ty<'tcx>,
193     cache: &mut FxHashMap<Ty<'tcx>, bool>,
194 ) -> bool {
195     if let Some(&cached_result) = cache.get(ty) {
196         return cached_result;
197     }
198     // prevent recursive loops, false-negative is better than endless loop leading to stack overflow
199     cache.insert(ty, false);
200     let result = cx.tcx.infer_ctxt().enter(|infcx| {
201         let cause = rustc_middle::traits::ObligationCause::dummy();
202         if infcx.at(&cause, param_env).normalize(ty).is_ok() {
203             match ty.kind() {
204                 ty::Adt(def, substs) => def.variants.iter().all(|variant| {
205                     variant
206                         .fields
207                         .iter()
208                         .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache))
209                 }),
210                 _ => ty.walk().all(|generic_arg| match generic_arg.unpack() {
211                     GenericArgKind::Type(inner_ty) if inner_ty != ty => {
212                         is_normalizable_helper(cx, param_env, inner_ty, cache)
213                     },
214                     _ => true, // if inner_ty == ty, we've already checked it
215                 }),
216             }
217         } else {
218             false
219         }
220     });
221     cache.insert(ty, result);
222     result
223 }
224
225 /// Returns true iff the given type is a primitive (a bool or char, any integer or floating-point
226 /// number type, a str, or an array, slice, or tuple of those types).
227 pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
228     match ty.kind() {
229         ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
230         ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true,
231         ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
232         ty::Tuple(inner_types) => inner_types.types().all(is_recursively_primitive_type),
233         _ => false,
234     }
235 }
236
237 /// Checks if the type is equal to a diagnostic item
238 ///
239 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
240 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
241     match ty.kind() {
242         ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
243         _ => false,
244     }
245 }
246
247 /// Checks if the type is equal to a lang item
248 pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool {
249     match ty.kind() {
250         ty::Adt(adt, _) => cx.tcx.lang_items().require(lang_item).unwrap() == adt.did,
251         _ => false,
252     }
253 }
254
255 /// Return `true` if the passed `typ` is `isize` or `usize`.
256 pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
257     matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
258 }
259
260 /// Checks if type is struct, enum or union type with the given def path.
261 ///
262 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
263 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
264 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
265     match ty.kind() {
266         ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
267         _ => false,
268     }
269 }
270
271 /// Peels off all references on the type. Returns the underlying type and the number of references
272 /// removed.
273 pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
274     fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) {
275         if let ty::Ref(_, ty, _) = ty.kind() {
276             peel(ty, count + 1)
277         } else {
278             (ty, count)
279         }
280     }
281     peel(ty, 0)
282 }
283
284 /// Peels off all references on the type.Returns the underlying type, the number of references
285 /// removed, and whether the pointer is ultimately mutable or not.
286 pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
287     fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
288         match ty.kind() {
289             ty::Ref(_, ty, Mutability::Mut) => f(ty, count + 1, mutability),
290             ty::Ref(_, ty, Mutability::Not) => f(ty, count + 1, Mutability::Not),
291             _ => (ty, count, mutability),
292         }
293     }
294     f(ty, 0, Mutability::Mut)
295 }
296
297 /// Returns `true` if the given type is an `unsafe` function.
298 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
299     match ty.kind() {
300         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
301         _ => false,
302     }
303 }
304
305 /// Returns the base type for HIR references and pointers.
306 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
307     match ty.kind {
308         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
309         _ => ty,
310     }
311 }
312
313 /// Returns the base type for references and raw pointers, and count reference
314 /// depth.
315 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
316     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
317         match ty.kind() {
318             ty::Ref(_, ty, _) => inner(ty, depth + 1),
319             _ => (ty, depth),
320         }
321     }
322     inner(ty, 0)
323 }
324
325 /// Returns `true` if types `a` and `b` are same types having same `Const` generic args,
326 /// otherwise returns `false`
327 pub fn same_type_and_consts(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
328     match (&a.kind(), &b.kind()) {
329         (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
330             if did_a != did_b {
331                 return false;
332             }
333
334             substs_a
335                 .iter()
336                 .zip(substs_b.iter())
337                 .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) {
338                     (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
339                     (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
340                         same_type_and_consts(type_a, type_b)
341                     },
342                     _ => true,
343                 })
344         },
345         _ => a == b,
346     }
347 }