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, Ty, TypeFoldable, UintTy};
15 use rustc_span::symbol::{Ident, Symbol};
16 use rustc_span::DUMMY_SP;
17 use rustc_trait_selection::traits::query::normalize::AtExt;
19 use crate::{match_def_path, must_use_attr};
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)
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) {
31 ty::Param(_) => false,
32 ty::Adt(def, subs) => def.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
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,
45 /// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
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,
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>> {
58 .get_diagnostic_item(sym::Iterator)
59 .and_then(|iter_did| {
60 cx.tcx.associated_items(iter_did).find_by_name_and_kind(
62 Ident::from_str("Item"),
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)
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] = &[
94 let ty_to_check = match probably_ref_ty.kind() {
95 ty::Ref(_, ty_to_check, _) => ty_to_check,
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,
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));
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>,
120 ty_params: &[GenericArg<'tcx>],
122 // Do not check on infer_types to avoid panic in evaluate_obligation.
123 if ty.has_infer_types() {
126 let ty = cx.tcx.erase_regions(ty);
127 if ty.has_escaping_bound_vars() {
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))
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),
142 // Returns whether the type has #[must_use] attribute
143 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
145 ty::Adt(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(ty) | ty::Array(ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => {
148 // for the Array case we don't need to care for the len == 0 case
149 // because we don't want to lint functions returning empty arrays
150 is_must_use_ty(cx, *ty)
152 ty::Tuple(substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
153 ty::Opaque(ref def_id, _) => {
154 for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) {
155 if let ty::PredicateKind::Trait(trait_predicate, _) = predicate.kind().skip_binder() {
156 if must_use_attr(cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() {
163 ty::Dynamic(binder, _) => {
164 for predicate in binder.iter() {
165 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
166 if must_use_attr(cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
177 // FIXME: Per https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/infer/at/struct.At.html#method.normalize
178 // this function can be removed once the `normalizie` method does not panic when normalization does
180 /// Checks if `Ty` is normalizable. This function is useful
181 /// to avoid crashes on `layout_of`.
182 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
183 is_normalizable_helper(cx, param_env, ty, &mut FxHashMap::default())
186 fn is_normalizable_helper<'tcx>(
187 cx: &LateContext<'tcx>,
188 param_env: ty::ParamEnv<'tcx>,
190 cache: &mut FxHashMap<Ty<'tcx>, bool>,
192 if let Some(&cached_result) = cache.get(ty) {
193 return cached_result;
195 // prevent recursive loops, false-negative is better than endless loop leading to stack overflow
196 cache.insert(ty, false);
197 let result = cx.tcx.infer_ctxt().enter(|infcx| {
198 let cause = rustc_middle::traits::ObligationCause::dummy();
199 if infcx.at(&cause, param_env).normalize(ty).is_ok() {
201 ty::Adt(def, substs) => def.variants.iter().all(|variant| {
205 .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache))
207 _ => ty.walk().all(|generic_arg| match generic_arg.unpack() {
208 GenericArgKind::Type(inner_ty) if inner_ty != ty => {
209 is_normalizable_helper(cx, param_env, inner_ty, cache)
211 _ => true, // if inner_ty == ty, we've already checked it
218 cache.insert(ty, result);
222 /// Returns true iff the given type is a primitive (a bool or char, any integer or floating-point
223 /// number type, a str, or an array, slice, or tuple of those types).
224 pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
226 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
227 ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true,
228 ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
229 ty::Tuple(inner_types) => inner_types.types().all(is_recursively_primitive_type),
234 /// Checks if the type is equal to a diagnostic item
236 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
237 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
239 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
244 /// Checks if the type is equal to a lang item
245 pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool {
247 ty::Adt(adt, _) => cx.tcx.lang_items().require(lang_item).unwrap() == adt.did,
252 /// Return `true` if the passed `typ` is `isize` or `usize`.
253 pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
254 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
257 /// Checks if type is struct, enum or union type with the given def path.
259 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
260 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
261 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
263 ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
268 /// Peels off all references on the type. Returns the underlying type and the number of references
270 pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
271 fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) {
272 if let ty::Ref(_, ty, _) = ty.kind() {
281 /// Peels off all references on the type.Returns the underlying type, the number of references
282 /// removed, and whether the pointer is ultimately mutable or not.
283 pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
284 fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
286 ty::Ref(_, ty, Mutability::Mut) => f(ty, count + 1, mutability),
287 ty::Ref(_, ty, Mutability::Not) => f(ty, count + 1, Mutability::Not),
288 _ => (ty, count, mutability),
291 f(ty, 0, Mutability::Mut)
294 /// Returns `true` if the given type is an `unsafe` function.
295 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
297 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
302 /// Returns the base type for HIR references and pointers.
303 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
305 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(mut_ty.ty),
310 /// Returns the base type for references and raw pointers, and count reference
312 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
313 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
315 ty::Ref(_, ty, _) => inner(ty, depth + 1),
322 /// Returns `true` if types `a` and `b` are same types having same `Const` generic args,
323 /// otherwise returns `false`
324 pub fn same_type_and_consts(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
325 match (&a.kind(), &b.kind()) {
326 (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
333 .zip(substs_b.iter())
334 .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) {
335 (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
336 (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
337 same_type_and_consts(type_a, type_b)