1 //! Util methods for [`rustc_middle::ty`]
3 #![allow(clippy::module_name_repetitions)]
5 use rustc_ast::ast::Mutability;
6 use rustc_data_structures::fx::FxHashMap;
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;
20 use crate::{match_def_path, must_use_attr};
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)
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) {
33 ty::Param(_) => false,
34 ty::Adt(def, subs) => def.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
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,
47 /// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
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,
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>> {
60 .get_diagnostic_item(sym::Iterator)
61 .and_then(|iter_did| get_associated_type(cx, ty, iter_did, "Item"))
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>,
71 ) -> Option<Ty<'tcx>> {
73 .associated_items(trait_id)
74 .find_by_name_and_kind(cx.tcx, Ident::from_str(name), ty::AssocKind::Type, trait_id)
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)
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] = &[
102 let ty_to_check = match probably_ref_ty.kind() {
103 ty::Ref(_, ty_to_check, _) => ty_to_check,
104 _ => probably_ref_ty,
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,
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));
122 /// Checks whether a type implements a trait.
123 /// The function returns false in case the type contains an inference variable.
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.
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>,
134 ty_params: &[GenericArg<'tcx>],
136 // Clippy shouldn't have infer types
137 assert!(!ty.needs_infer());
139 let ty = cx.tcx.erase_regions(ty);
140 if ty.has_escaping_bound_vars() {
143 let ty_params = cx.tcx.mk_substs(ty_params.iter());
144 cx.tcx.infer_ctxt().enter(|infcx| {
146 .type_implements_trait(trait_id, ty, ty_params, cx.param_env)
147 .must_apply_modulo_regions()
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),
159 // Returns whether the type has #[must_use] attribute
160 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
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)
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() {
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() {
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
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())
203 fn is_normalizable_helper<'tcx>(
204 cx: &LateContext<'tcx>,
205 param_env: ty::ParamEnv<'tcx>,
207 cache: &mut FxHashMap<Ty<'tcx>, bool>,
209 if let Some(&cached_result) = cache.get(ty) {
210 return cached_result;
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() {
218 ty::Adt(def, substs) => def.variants.iter().all(|variant| {
222 .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache))
224 _ => ty.walk(cx.tcx).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)
228 _ => true, // if inner_ty == ty, we've already checked it
235 cache.insert(ty, result);
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(_))
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 {
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),
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 {
261 ty::Ref(_, ref_ty, _) => match ref_ty.kind() {
262 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
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`].
272 /// For a further exploitation what diagnostic items are see [diagnostic items] in
277 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
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 {
282 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
287 /// Checks if the type is equal to a lang item.
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 {
292 ty::Adt(adt, _) => cx.tcx.lang_items().require(lang_item).map_or(false, |li| li == adt.did),
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))
302 /// Checks if type is struct, enum or union type with the given def path.
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 {
308 ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
313 /// Peels off all references on the type. Returns the underlying type and the number of references
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() {
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) {
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),
336 f(ty, 0, Mutability::Mut)
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 {
342 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
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> {
350 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(mut_ty.ty),
355 /// Returns the base type for references and raw pointers, and count reference
357 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
358 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
360 ty::Ref(_, ty, _) => inner(ty, depth + 1),
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(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)) => {
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)
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 {
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),
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()