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::{CtorKind, DefKind, Res};
9 use rustc_hir::def_id::DefId;
10 use rustc_hir::{Expr, TyKind, Unsafety};
11 use rustc_infer::infer::TyCtxtInferExt;
12 use rustc_lint::LateContext;
13 use rustc_middle::mir::interpret::{ConstValue, Scalar};
14 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
15 use rustc_middle::ty::{
16 self, AdtDef, Binder, FnSig, IntTy, Predicate, PredicateKind, Ty, TyCtxt, TypeFoldable, UintTy, VariantDiscr,
18 use rustc_span::symbol::Ident;
19 use rustc_span::{sym, Span, Symbol, DUMMY_SP};
20 use rustc_target::abi::{Size, VariantIdx};
21 use rustc_trait_selection::infer::InferCtxtExt;
22 use rustc_trait_selection::traits::query::normalize::AtExt;
25 use crate::{match_def_path, must_use_attr, path_res};
27 // Checks if the given type implements copy.
28 pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
29 ty.is_copy_modulo_regions(cx.tcx.at(DUMMY_SP), cx.param_env)
32 /// Checks whether a type can be partially moved.
33 pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
34 if has_drop(cx, ty) || is_copy(cx, ty) {
38 ty::Param(_) => false,
39 ty::Adt(def, subs) => def.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
44 /// Walks into `ty` and returns `true` if any inner type is the same as `other_ty`
45 pub fn contains_ty(ty: Ty<'_>, other_ty: Ty<'_>) -> bool {
46 ty.walk().any(|inner| match inner.unpack() {
47 GenericArgKind::Type(inner_ty) => other_ty == inner_ty,
48 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
52 /// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
54 pub fn contains_adt_constructor(ty: Ty<'_>, adt: AdtDef<'_>) -> bool {
55 ty.walk().any(|inner| match inner.unpack() {
56 GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
57 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
61 /// Resolves `<T as Iterator>::Item` for `T`
62 /// Do not invoke without first verifying that the type implements `Iterator`
63 pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
65 .get_diagnostic_item(sym::Iterator)
66 .and_then(|iter_did| get_associated_type(cx, ty, iter_did, "Item"))
69 /// Returns the associated type `name` for `ty` as an implementation of `trait_id`.
70 /// Do not invoke without first verifying that the type implements the trait.
71 pub fn get_associated_type<'tcx>(
72 cx: &LateContext<'tcx>,
76 ) -> Option<Ty<'tcx>> {
78 .associated_items(trait_id)
79 .find_by_name_and_kind(cx.tcx, Ident::from_str(name), ty::AssocKind::Type, trait_id)
81 let proj = cx.tcx.mk_projection(assoc.def_id, cx.tcx.mk_substs_trait(ty, &[]));
82 cx.tcx.normalize_erasing_regions(cx.param_env, proj)
86 /// Returns true if ty has `iter` or `iter_mut` methods
87 pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
88 // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
89 // exists and has the desired signature. Unfortunately FnCtxt is not exported
90 // so we can't use its `lookup_method` method.
91 let into_iter_collections: &[Symbol] = &[
107 let ty_to_check = match probably_ref_ty.kind() {
108 ty::Ref(_, ty_to_check, _) => *ty_to_check,
109 _ => probably_ref_ty,
112 let def_id = match ty_to_check.kind() {
113 ty::Array(..) => return Some(sym::array),
114 ty::Slice(..) => return Some(sym::slice),
115 ty::Adt(adt, _) => adt.did(),
119 for &name in into_iter_collections {
120 if cx.tcx.is_diagnostic_item(name, def_id) {
121 return Some(cx.tcx.item_name(def_id));
127 /// Checks whether a type implements a trait.
128 /// The function returns false in case the type contains an inference variable.
131 /// * [`get_trait_def_id`](super::get_trait_def_id) to get a trait [`DefId`].
132 /// * [Common tools for writing lints] for an example how to use this function and other options.
134 /// [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
135 pub fn implements_trait<'tcx>(
136 cx: &LateContext<'tcx>,
139 ty_params: &[GenericArg<'tcx>],
141 // Clippy shouldn't have infer types
142 assert!(!ty.needs_infer());
144 let ty = cx.tcx.erase_regions(ty);
145 if ty.has_escaping_bound_vars() {
148 let ty_params = cx.tcx.mk_substs(ty_params.iter());
149 cx.tcx.infer_ctxt().enter(|infcx| {
151 .type_implements_trait(trait_id, ty, ty_params, cx.param_env)
152 .must_apply_modulo_regions()
156 /// Checks whether this type implements `Drop`.
157 pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
158 match ty.ty_adt_def() {
159 Some(def) => def.has_dtor(cx.tcx),
164 // Returns whether the type has #[must_use] attribute
165 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
167 ty::Adt(adt, _) => must_use_attr(cx.tcx.get_attrs(adt.did())).is_some(),
168 ty::Foreign(ref did) => must_use_attr(cx.tcx.get_attrs(*did)).is_some(),
169 ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => {
170 // for the Array case we don't need to care for the len == 0 case
171 // because we don't want to lint functions returning empty arrays
172 is_must_use_ty(cx, *ty)
174 ty::Tuple(substs) => substs.iter().any(|ty| is_must_use_ty(cx, ty)),
175 ty::Opaque(ref def_id, _) => {
176 for (predicate, _) in cx.tcx.explicit_item_bounds(*def_id) {
177 if let ty::PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder() {
178 if must_use_attr(cx.tcx.get_attrs(trait_predicate.trait_ref.def_id)).is_some() {
185 ty::Dynamic(binder, _) => {
186 for predicate in binder.iter() {
187 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
188 if must_use_attr(cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
199 // FIXME: Per https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/infer/at/struct.At.html#method.normalize
200 // this function can be removed once the `normalize` method does not panic when normalization does
202 /// Checks if `Ty` is normalizable. This function is useful
203 /// to avoid crashes on `layout_of`.
204 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
205 is_normalizable_helper(cx, param_env, ty, &mut FxHashMap::default())
208 fn is_normalizable_helper<'tcx>(
209 cx: &LateContext<'tcx>,
210 param_env: ty::ParamEnv<'tcx>,
212 cache: &mut FxHashMap<Ty<'tcx>, bool>,
214 if let Some(&cached_result) = cache.get(&ty) {
215 return cached_result;
217 // prevent recursive loops, false-negative is better than endless loop leading to stack overflow
218 cache.insert(ty, false);
219 let result = cx.tcx.infer_ctxt().enter(|infcx| {
220 let cause = rustc_middle::traits::ObligationCause::dummy();
221 if infcx.at(&cause, param_env).normalize(ty).is_ok() {
223 ty::Adt(def, substs) => def.variants().iter().all(|variant| {
227 .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache))
229 _ => ty.walk().all(|generic_arg| match generic_arg.unpack() {
230 GenericArgKind::Type(inner_ty) if inner_ty != ty => {
231 is_normalizable_helper(cx, param_env, inner_ty, cache)
233 _ => true, // if inner_ty == ty, we've already checked it
240 cache.insert(ty, result);
244 /// Returns `true` if the given type is a non aggregate primitive (a `bool` or `char`, any
245 /// integer or floating-point number type). For checking aggregation of primitive types (e.g.
246 /// tuples and slices of primitive type) see `is_recursively_primitive_type`
247 pub fn is_non_aggregate_primitive_type(ty: Ty<'_>) -> bool {
248 matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_))
251 /// Returns `true` if the given type is a primitive (a `bool` or `char`, any integer or
252 /// floating-point number type, a `str`, or an array, slice, or tuple of those types).
253 pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
255 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
256 ty::Ref(_, inner, _) if *inner.kind() == ty::Str => true,
257 ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
258 ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type),
263 /// Checks if the type is a reference equals to a diagnostic item
264 pub fn is_type_ref_to_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
266 ty::Ref(_, ref_ty, _) => match ref_ty.kind() {
267 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did()),
274 /// Checks if the type is equal to a diagnostic item. To check if a type implements a
275 /// trait marked with a diagnostic item use [`implements_trait`].
277 /// For a further exploitation what diagnostic items are see [diagnostic items] in
282 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
284 /// [Diagnostic Items]: https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-items.html
285 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
287 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did()),
292 /// Checks if the type is equal to a lang item.
294 /// Returns `false` if the `LangItem` is not defined.
295 pub fn is_type_lang_item(cx: &LateContext<'_>, ty: Ty<'_>, lang_item: hir::LangItem) -> bool {
297 ty::Adt(adt, _) => cx
301 .map_or(false, |li| li == adt.did()),
306 /// Return `true` if the passed `typ` is `isize` or `usize`.
307 pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
308 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
311 /// Checks if type is struct, enum or union type with the given def path.
313 /// If the type is a diagnostic item, use `is_type_diagnostic_item` instead.
314 /// If you change the signature, remember to update the internal lint `MatchTypeOnDiagItem`
315 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
317 ty::Adt(adt, _) => match_def_path(cx, adt.did(), path),
322 /// Peels off all references on the type. Returns the underlying type and the number of references
324 pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) {
325 fn peel(ty: Ty<'_>, count: usize) -> (Ty<'_>, usize) {
326 if let ty::Ref(_, ty, _) = ty.kind() {
335 /// Peels off all references on the type.Returns the underlying type, the number of references
336 /// removed, and whether the pointer is ultimately mutable or not.
337 pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
338 fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) {
340 ty::Ref(_, ty, Mutability::Mut) => f(*ty, count + 1, mutability),
341 ty::Ref(_, ty, Mutability::Not) => f(*ty, count + 1, Mutability::Not),
342 _ => (ty, count, mutability),
345 f(ty, 0, Mutability::Mut)
348 /// Returns `true` if the given type is an `unsafe` function.
349 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
351 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
356 /// Returns the base type for HIR references and pointers.
357 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
359 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(mut_ty.ty),
364 /// Returns the base type for references and raw pointers, and count reference
366 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
367 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
369 ty::Ref(_, ty, _) => inner(*ty, depth + 1),
376 /// Returns `true` if types `a` and `b` are same types having same `Const` generic args,
377 /// otherwise returns `false`
378 pub fn same_type_and_consts<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
379 match (&a.kind(), &b.kind()) {
380 (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
387 .zip(substs_b.iter())
388 .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) {
389 (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
390 (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
391 same_type_and_consts(type_a, type_b)
400 /// Checks if a given type looks safe to be uninitialized.
401 pub fn is_uninit_value_valid_for_ty(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
403 ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
404 ty::Tuple(types) => types.iter().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
405 ty::Adt(adt, _) => cx.tcx.lang_items().maybe_uninit() == Some(adt.did()),
410 /// Gets an iterator over all predicates which apply to the given item.
411 pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(Predicate<'_>, Span)> {
412 let mut next_id = Some(id);
413 iter::from_fn(move || {
414 next_id.take().map(|id| {
415 let preds = tcx.predicates_of(id);
416 next_id = preds.parent;
417 preds.predicates.iter()
423 /// A signature for a function like type.
424 #[derive(Clone, Copy)]
425 pub enum ExprFnSig<'tcx> {
426 Sig(Binder<'tcx, FnSig<'tcx>>),
427 Closure(Binder<'tcx, FnSig<'tcx>>),
428 Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>),
430 impl<'tcx> ExprFnSig<'tcx> {
431 /// Gets the argument type at the given offset.
432 pub fn input(self, i: usize) -> Binder<'tcx, Ty<'tcx>> {
434 Self::Sig(sig) => sig.input(i),
435 Self::Closure(sig) => sig.input(0).map_bound(|ty| ty.tuple_fields()[i]),
436 Self::Trait(inputs, _) => inputs.map_bound(|ty| ty.tuple_fields()[i]),
440 /// Gets the result type, if one could be found. Note that the result type of a trait may not be
442 pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
444 Self::Sig(sig) | Self::Closure(sig) => Some(sig.output()),
445 Self::Trait(_, output) => output,
450 /// If the expression is function like, get the signature for it.
451 pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
452 if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) {
453 Some(ExprFnSig::Sig(cx.tcx.fn_sig(id)))
455 let ty = cx.typeck_results().expr_ty_adjusted(expr).peel_refs();
457 ty::Closure(_, subs) => Some(ExprFnSig::Closure(subs.as_closure().sig())),
458 ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).subst(cx.tcx, subs))),
459 ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig)),
460 ty::Dynamic(bounds, _) => {
461 let lang_items = cx.tcx.lang_items();
462 match bounds.principal() {
464 if Some(bound.def_id()) == lang_items.fn_trait()
465 || Some(bound.def_id()) == lang_items.fn_once_trait()
466 || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
470 .find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id()))
471 .map(|p| p.map_bound(|p| p.term.ty().expect("return type was a const")));
472 Some(ExprFnSig::Trait(bound.map_bound(|b| b.substs.type_at(0)), output))
477 ty::Param(_) | ty::Projection(..) => {
478 let mut inputs = None;
479 let mut output = None;
480 let lang_items = cx.tcx.lang_items();
482 for (pred, _) in all_predicates_of(cx.tcx, cx.typeck_results().hir_owner.to_def_id()) {
483 let mut is_input = false;
484 if let Some(ty) = pred
486 .map_bound(|pred| match pred {
487 PredicateKind::Trait(p)
488 if (lang_items.fn_trait() == Some(p.def_id())
489 || lang_items.fn_mut_trait() == Some(p.def_id())
490 || lang_items.fn_once_trait() == Some(p.def_id()))
491 && p.self_ty() == ty =>
494 Some(p.trait_ref.substs.type_at(1))
496 PredicateKind::Projection(p)
497 if Some(p.projection_ty.item_def_id) == lang_items.fn_once_output()
498 && p.projection_ty.self_ty() == ty =>
507 if is_input && inputs.is_none() {
509 } else if !is_input && output.is_none() {
512 // Multiple different fn trait impls. Is this even allowed?
518 inputs.map(|ty| ExprFnSig::Trait(ty, output))
525 #[derive(Clone, Copy)]
530 impl core::ops::Add<u32> for EnumValue {
532 fn add(self, n: u32) -> Self::Output {
534 Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
535 Self::Signed(x) => Self::Signed(x + i128::from(n)),
540 /// Attempts to read the given constant as though it were an an enum value.
541 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
542 pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
543 if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
544 match tcx.type_of(id).kind() {
545 ty::Int(_) => Some(EnumValue::Signed(match value.size().bytes() {
546 1 => i128::from(value.assert_bits(Size::from_bytes(1)) as u8 as i8),
547 2 => i128::from(value.assert_bits(Size::from_bytes(2)) as u16 as i16),
548 4 => i128::from(value.assert_bits(Size::from_bytes(4)) as u32 as i32),
549 8 => i128::from(value.assert_bits(Size::from_bytes(8)) as u64 as i64),
550 16 => value.assert_bits(Size::from_bytes(16)) as i128,
553 ty::Uint(_) => Some(EnumValue::Unsigned(match value.size().bytes() {
554 1 => value.assert_bits(Size::from_bytes(1)),
555 2 => value.assert_bits(Size::from_bytes(2)),
556 4 => value.assert_bits(Size::from_bytes(4)),
557 8 => value.assert_bits(Size::from_bytes(8)),
558 16 => value.assert_bits(Size::from_bytes(16)),
568 /// Gets the value of the given variant.
569 pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: AdtDef<'_>, i: VariantIdx) -> EnumValue {
570 let variant = &adt.variant(i);
571 match variant.discr {
572 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
573 VariantDiscr::Relative(x) => match adt.variant((i.as_usize() - x as usize).into()).discr {
574 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
575 VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
580 /// Check if the given type is either `core::ffi::c_void`, `std::os::raw::c_void`, or one of the
581 /// platform specific `libc::<platform>::c_void` types in libc.
582 pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
583 if let ty::Adt(adt, _) = ty.kind()
584 && let &[krate, .., name] = &*cx.get_def_path(adt.did())
585 && let sym::libc | sym::core | sym::std = krate
586 && name.as_str() == "c_void"