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