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