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