clippy_utils/ty/
mod.rs

1//! Util methods for [`rustc_middle::ty`]
2
3#![allow(clippy::module_name_repetitions)]
4
5use core::ops::ControlFlow;
6use rustc_abi::VariantIdx;
7use rustc_ast::ast::Mutability;
8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9use rustc_hir as hir;
10use rustc_hir::attrs::AttributeKind;
11use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
12use rustc_hir::def_id::DefId;
13use rustc_hir::{Expr, FnDecl, LangItem, find_attr};
14use rustc_hir_analysis::lower_ty;
15use rustc_infer::infer::TyCtxtInferExt;
16use rustc_lint::LateContext;
17use rustc_middle::mir::ConstValue;
18use rustc_middle::mir::interpret::Scalar;
19use rustc_middle::traits::EvaluationResult;
20use rustc_middle::ty::adjustment::{Adjust, Adjustment};
21use rustc_middle::ty::layout::ValidityRequirement;
22use rustc_middle::ty::{
23    self, AdtDef, AliasTy, AssocItem, AssocTag, Binder, BoundRegion, BoundVarIndexKind, FnSig, GenericArg,
24    GenericArgKind, GenericArgsRef, IntTy, Region, RegionKind, TraitRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
25    TypeVisitableExt, TypeVisitor, UintTy, Upcast, VariantDef, VariantDiscr,
26};
27use rustc_span::symbol::Ident;
28use rustc_span::{DUMMY_SP, Span, Symbol, sym};
29use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
30use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
31use rustc_trait_selection::traits::{Obligation, ObligationCause};
32use std::assert_matches::debug_assert_matches;
33use std::collections::hash_map::Entry;
34use std::{iter, mem};
35
36use crate::paths::{PathNS, lookup_path_str};
37use crate::res::{MaybeDef, MaybeQPath};
38
39mod type_certainty;
40pub use type_certainty::expr_type_is_certain;
41
42/// Lower a [`hir::Ty`] to a [`rustc_middle::ty::Ty`].
43pub fn ty_from_hir_ty<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
44    cx.maybe_typeck_results()
45        .filter(|results| results.hir_owner == hir_ty.hir_id.owner)
46        .and_then(|results| results.node_type_opt(hir_ty.hir_id))
47        .unwrap_or_else(|| lower_ty(cx.tcx, hir_ty))
48}
49
50/// Checks if the given type implements copy.
51pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
52    cx.type_is_copy_modulo_regions(ty)
53}
54
55/// This checks whether a given type is known to implement Debug.
56pub fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
57    cx.tcx
58        .get_diagnostic_item(sym::Debug)
59        .is_some_and(|debug| implements_trait(cx, ty, debug, &[]))
60}
61
62/// Checks whether a type can be partially moved.
63pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
64    if has_drop(cx, ty) || is_copy(cx, ty) {
65        return false;
66    }
67    match ty.kind() {
68        ty::Param(_) => false,
69        ty::Adt(def, subs) => def.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
70        _ => true,
71    }
72}
73
74/// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
75/// constructor.
76pub fn contains_adt_constructor<'tcx>(ty: Ty<'tcx>, adt: AdtDef<'tcx>) -> bool {
77    ty.walk().any(|inner| match inner.kind() {
78        GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
79        GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
80    })
81}
82
83/// Walks into `ty` and returns `true` if any inner type is an instance of the given type, or adt
84/// constructor of the same type.
85///
86/// This method also recurses into opaque type predicates, so call it with `impl Trait<U>` and `U`
87/// will also return `true`.
88pub fn contains_ty_adt_constructor_opaque<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, needle: Ty<'tcx>) -> bool {
89    fn contains_ty_adt_constructor_opaque_inner<'tcx>(
90        cx: &LateContext<'tcx>,
91        ty: Ty<'tcx>,
92        needle: Ty<'tcx>,
93        seen: &mut FxHashSet<DefId>,
94    ) -> bool {
95        ty.walk().any(|inner| match inner.kind() {
96            GenericArgKind::Type(inner_ty) => {
97                if inner_ty == needle {
98                    return true;
99                }
100
101                if inner_ty.ty_adt_def() == needle.ty_adt_def() {
102                    return true;
103                }
104
105                if let ty::Alias(ty::Opaque, AliasTy { def_id, .. }) = *inner_ty.kind() {
106                    if !seen.insert(def_id) {
107                        return false;
108                    }
109
110                    for (predicate, _span) in cx.tcx.explicit_item_self_bounds(def_id).iter_identity_copied() {
111                        match predicate.kind().skip_binder() {
112                            // For `impl Trait<U>`, it will register a predicate of `T: Trait<U>`, so we go through
113                            // and check substitutions to find `U`.
114                            ty::ClauseKind::Trait(trait_predicate) => {
115                                if trait_predicate
116                                    .trait_ref
117                                    .args
118                                    .types()
119                                    .skip(1) // Skip the implicit `Self` generic parameter
120                                    .any(|ty| contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen))
121                                {
122                                    return true;
123                                }
124                            },
125                            // For `impl Trait<Assoc=U>`, it will register a predicate of `<T as Trait>::Assoc = U`,
126                            // so we check the term for `U`.
127                            ty::ClauseKind::Projection(projection_predicate) => {
128                                if let ty::TermKind::Ty(ty) = projection_predicate.term.kind()
129                                    && contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen)
130                                {
131                                    return true;
132                                }
133                            },
134                            _ => (),
135                        }
136                    }
137                }
138
139                false
140            },
141            GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
142        })
143    }
144
145    // A hash set to ensure that the same opaque type (`impl Trait` in RPIT or TAIT) is not
146    // visited twice.
147    let mut seen = FxHashSet::default();
148    contains_ty_adt_constructor_opaque_inner(cx, ty, needle, &mut seen)
149}
150
151/// Resolves `<T as Iterator>::Item` for `T`
152/// Do not invoke without first verifying that the type implements `Iterator`
153pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
154    cx.tcx
155        .get_diagnostic_item(sym::Iterator)
156        .and_then(|iter_did| cx.get_associated_type(ty, iter_did, sym::Item))
157}
158
159/// Returns true if `ty` is a type on which calling `Clone` through a function instead of
160/// as a method, such as `Arc::clone()` is considered idiomatic.
161///
162/// Lints should avoid suggesting to replace instances of `ty::Clone()` by `.clone()` for objects
163/// of those types.
164pub fn should_call_clone_as_function(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
165    matches!(
166        ty.opt_diag_name(cx),
167        Some(sym::Arc | sym::ArcWeak | sym::Rc | sym::RcWeak)
168    )
169}
170
171/// If `ty` is known to have a `iter` or `iter_mut` method, returns a symbol representing the type.
172pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
173    // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
174    // exists and has the desired signature. Unfortunately FnCtxt is not exported
175    // so we can't use its `lookup_method` method.
176    let into_iter_collections: &[Symbol] = &[
177        sym::Vec,
178        sym::Option,
179        sym::Result,
180        sym::BTreeMap,
181        sym::BTreeSet,
182        sym::VecDeque,
183        sym::LinkedList,
184        sym::BinaryHeap,
185        sym::HashSet,
186        sym::HashMap,
187        sym::PathBuf,
188        sym::Path,
189        sym::Receiver,
190    ];
191
192    let ty_to_check = match probably_ref_ty.kind() {
193        ty::Ref(_, ty_to_check, _) => *ty_to_check,
194        _ => probably_ref_ty,
195    };
196
197    let def_id = match ty_to_check.kind() {
198        ty::Array(..) => return Some(sym::array),
199        ty::Slice(..) => return Some(sym::slice),
200        ty::Adt(adt, _) => adt.did(),
201        _ => return None,
202    };
203
204    for &name in into_iter_collections {
205        if cx.tcx.is_diagnostic_item(name, def_id) {
206            return Some(cx.tcx.item_name(def_id));
207        }
208    }
209    None
210}
211
212/// Checks whether a type implements a trait.
213/// The function returns false in case the type contains an inference variable.
214///
215/// See [Common tools for writing lints] for an example how to use this function and other options.
216///
217/// [Common tools for writing lints]: https://github.com/rust-lang/rust-clippy/blob/master/book/src/development/common_tools_writing_lints.md#checking-if-a-type-implements-a-specific-trait
218pub fn implements_trait<'tcx>(
219    cx: &LateContext<'tcx>,
220    ty: Ty<'tcx>,
221    trait_id: DefId,
222    args: &[GenericArg<'tcx>],
223) -> bool {
224    implements_trait_with_env_from_iter(
225        cx.tcx,
226        cx.typing_env(),
227        ty,
228        trait_id,
229        None,
230        args.iter().map(|&x| Some(x)),
231    )
232}
233
234/// Same as `implements_trait` but allows using a `ParamEnv` different from the lint context.
235///
236/// The `callee_id` argument is used to determine whether this is a function call in a `const fn`
237/// environment, used for checking const traits.
238pub fn implements_trait_with_env<'tcx>(
239    tcx: TyCtxt<'tcx>,
240    typing_env: ty::TypingEnv<'tcx>,
241    ty: Ty<'tcx>,
242    trait_id: DefId,
243    callee_id: Option<DefId>,
244    args: &[GenericArg<'tcx>],
245) -> bool {
246    implements_trait_with_env_from_iter(tcx, typing_env, ty, trait_id, callee_id, args.iter().map(|&x| Some(x)))
247}
248
249/// Same as `implements_trait_from_env` but takes the arguments as an iterator.
250pub fn implements_trait_with_env_from_iter<'tcx>(
251    tcx: TyCtxt<'tcx>,
252    typing_env: ty::TypingEnv<'tcx>,
253    ty: Ty<'tcx>,
254    trait_id: DefId,
255    callee_id: Option<DefId>,
256    args: impl IntoIterator<Item = impl Into<Option<GenericArg<'tcx>>>>,
257) -> bool {
258    // Clippy shouldn't have infer types
259    assert!(!ty.has_infer());
260
261    // If a `callee_id` is passed, then we assert that it is a body owner
262    // through calling `body_owner_kind`, which would panic if the callee
263    // does not have a body.
264    if let Some(callee_id) = callee_id {
265        let _ = tcx.hir_body_owner_kind(callee_id);
266    }
267
268    let ty = tcx.erase_and_anonymize_regions(ty);
269    if ty.has_escaping_bound_vars() {
270        return false;
271    }
272
273    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
274    let args = args
275        .into_iter()
276        .map(|arg| arg.into().unwrap_or_else(|| infcx.next_ty_var(DUMMY_SP).into()))
277        .collect::<Vec<_>>();
278
279    let trait_ref = TraitRef::new(tcx, trait_id, [GenericArg::from(ty)].into_iter().chain(args));
280
281    debug_assert_matches!(
282        tcx.def_kind(trait_id),
283        DefKind::Trait | DefKind::TraitAlias,
284        "`DefId` must belong to a trait or trait alias"
285    );
286    #[cfg(debug_assertions)]
287    assert_generic_args_match(tcx, trait_id, trait_ref.args);
288
289    let obligation = Obligation {
290        cause: ObligationCause::dummy(),
291        param_env,
292        recursion_depth: 0,
293        predicate: trait_ref.upcast(tcx),
294    };
295    infcx
296        .evaluate_obligation(&obligation)
297        .is_ok_and(EvaluationResult::must_apply_modulo_regions)
298}
299
300/// Checks whether this type implements `Drop`.
301pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
302    match ty.ty_adt_def() {
303        Some(def) => def.has_dtor(cx.tcx),
304        None => false,
305    }
306}
307
308// Returns whether the type has #[must_use] attribute
309pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
310    match ty.kind() {
311        ty::Adt(adt, _) => find_attr!(cx.tcx.get_all_attrs(adt.did()), AttributeKind::MustUse { .. }),
312        ty::Foreign(did) => find_attr!(cx.tcx.get_all_attrs(*did), AttributeKind::MustUse { .. }),
313        ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty, _) | ty::Ref(_, ty, _) => {
314            // for the Array case we don't need to care for the len == 0 case
315            // because we don't want to lint functions returning empty arrays
316            is_must_use_ty(cx, *ty)
317        },
318        ty::Tuple(args) => args.iter().any(|ty| is_must_use_ty(cx, ty)),
319        ty::Alias(ty::Opaque, AliasTy { def_id, .. }) => {
320            for (predicate, _) in cx.tcx.explicit_item_self_bounds(def_id).skip_binder() {
321                if let ty::ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder()
322                    && find_attr!(
323                        cx.tcx.get_all_attrs(trait_predicate.trait_ref.def_id),
324                        AttributeKind::MustUse { .. }
325                    )
326                {
327                    return true;
328                }
329            }
330            false
331        },
332        ty::Dynamic(binder, _) => {
333            for predicate in *binder {
334                if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder()
335                    && find_attr!(cx.tcx.get_all_attrs(trait_ref.def_id), AttributeKind::MustUse { .. })
336                {
337                    return true;
338                }
339            }
340            false
341        },
342        _ => false,
343    }
344}
345
346/// Returns `true` if the given type is a non aggregate primitive (a `bool` or `char`, any
347/// integer or floating-point number type).
348///
349/// For checking aggregation of primitive types (e.g. tuples and slices of primitive type) see
350/// `is_recursively_primitive_type`
351pub fn is_non_aggregate_primitive_type(ty: Ty<'_>) -> bool {
352    matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_))
353}
354
355/// Returns `true` if the given type is a primitive (a `bool` or `char`, any integer or
356/// floating-point number type, a `str`, or an array, slice, or tuple of those types).
357pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
358    match *ty.kind() {
359        ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
360        ty::Ref(_, inner, _) if inner.is_str() => true,
361        ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
362        ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type),
363        _ => false,
364    }
365}
366
367/// Return `true` if the passed `typ` is `isize` or `usize`.
368pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
369    matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
370}
371
372/// Checks if the drop order for a type matters.
373///
374/// Some std types implement drop solely to deallocate memory. For these types, and composites
375/// containing them, changing the drop order won't result in any observable side effects.
376pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
377    fn needs_ordered_drop_inner<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
378        if !seen.insert(ty) {
379            return false;
380        }
381        if !ty.has_significant_drop(cx.tcx, cx.typing_env()) {
382            false
383        }
384        // Check for std types which implement drop, but only for memory allocation.
385        else if ty.is_lang_item(cx, LangItem::OwnedBox)
386            || matches!(
387                ty.opt_diag_name(cx),
388                Some(sym::HashSet | sym::Rc | sym::Arc | sym::cstring_type | sym::RcWeak | sym::ArcWeak)
389            )
390        {
391            // Check all of the generic arguments.
392            if let ty::Adt(_, subs) = ty.kind() {
393                subs.types().any(|ty| needs_ordered_drop_inner(cx, ty, seen))
394            } else {
395                true
396            }
397        } else if !cx
398            .tcx
399            .lang_items()
400            .drop_trait()
401            .is_some_and(|id| implements_trait(cx, ty, id, &[]))
402        {
403            // This type doesn't implement drop, so no side effects here.
404            // Check if any component type has any.
405            match ty.kind() {
406                ty::Tuple(fields) => fields.iter().any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
407                ty::Array(ty, _) => needs_ordered_drop_inner(cx, *ty, seen),
408                ty::Adt(adt, subs) => adt
409                    .all_fields()
410                    .map(|f| f.ty(cx.tcx, subs))
411                    .any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
412                _ => true,
413            }
414        } else {
415            true
416        }
417    }
418
419    needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
420}
421
422/// Returns `true` if `ty` denotes an `unsafe fn`.
423pub fn is_unsafe_fn<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
424    ty.is_fn() && ty.fn_sig(cx.tcx).safety().is_unsafe()
425}
426
427/// Peels off all references on the type. Returns the underlying type, the number of references
428/// removed, and, if there were any such references, whether the pointer is ultimately mutable or
429/// not.
430pub fn peel_and_count_ty_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize, Option<Mutability>) {
431    let mut count = 0;
432    let mut mutbl = None;
433    while let ty::Ref(_, dest_ty, m) = ty.kind() {
434        ty = *dest_ty;
435        count += 1;
436        mutbl.replace(mutbl.map_or(*m, |mutbl: Mutability| mutbl.min(*m)));
437    }
438    (ty, count, mutbl)
439}
440
441/// Checks whether `a` and `b` are same types having same `Const` generic args, but ignores
442/// lifetimes.
443///
444/// For example, the function would return `true` for
445/// - `u32` and `u32`
446/// - `[u8; N]` and `[u8; M]`, if `N=M`
447/// - `Option<T>` and `Option<U>`, if `same_type_modulo_regions(T, U)` holds
448/// - `&'a str` and `&'b str`
449///
450/// and `false` for:
451/// - `Result<u32, String>` and `Result<usize, String>`
452pub fn same_type_modulo_regions<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
453    match (&a.kind(), &b.kind()) {
454        (&ty::Adt(did_a, args_a), &ty::Adt(did_b, args_b)) => {
455            if did_a != did_b {
456                return false;
457            }
458
459            iter::zip(*args_a, *args_b).all(|(arg_a, arg_b)| match (arg_a.kind(), arg_b.kind()) {
460                (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
461                (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
462                    same_type_modulo_regions(type_a, type_b)
463                },
464                _ => true,
465            })
466        },
467        _ => a == b,
468    }
469}
470
471/// Checks if a given type looks safe to be uninitialized.
472pub fn is_uninit_value_valid_for_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
473    let typing_env = cx.typing_env().with_post_analysis_normalized(cx.tcx);
474    cx.tcx
475        .check_validity_requirement((ValidityRequirement::Uninit, typing_env.as_query_input(ty)))
476        .unwrap_or_else(|_| is_uninit_value_valid_for_ty_fallback(cx, ty))
477}
478
479/// A fallback for polymorphic types, which are not supported by `check_validity_requirement`.
480fn is_uninit_value_valid_for_ty_fallback<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
481    match *ty.kind() {
482        // The array length may be polymorphic, let's try the inner type.
483        ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
484        // Peek through tuples and try their fallbacks.
485        ty::Tuple(types) => types.iter().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
486        // Unions are always fine right now.
487        // This includes MaybeUninit, the main way people use uninitialized memory.
488        ty::Adt(adt, _) if adt.is_union() => true,
489        // Types (e.g. `UnsafeCell<MaybeUninit<T>>`) that recursively contain only types that can be uninit
490        // can themselves be uninit too.
491        // This purposefully ignores enums as they may have a discriminant that can't be uninit.
492        ty::Adt(adt, args) if adt.is_struct() => adt
493            .all_fields()
494            .all(|field| is_uninit_value_valid_for_ty(cx, field.ty(cx.tcx, args))),
495        // For the rest, conservatively assume that they cannot be uninit.
496        _ => false,
497    }
498}
499
500/// Gets an iterator over all predicates which apply to the given item.
501pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(ty::Clause<'_>, Span)> {
502    let mut next_id = Some(id);
503    iter::from_fn(move || {
504        next_id.take().map(|id| {
505            let preds = tcx.predicates_of(id);
506            next_id = preds.parent;
507            preds.predicates.iter()
508        })
509    })
510    .flatten()
511}
512
513/// A signature for a function like type.
514#[derive(Clone, Copy, Debug)]
515pub enum ExprFnSig<'tcx> {
516    Sig(Binder<'tcx, FnSig<'tcx>>, Option<DefId>),
517    Closure(Option<&'tcx FnDecl<'tcx>>, Binder<'tcx, FnSig<'tcx>>),
518    Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>, Option<DefId>),
519}
520impl<'tcx> ExprFnSig<'tcx> {
521    /// Gets the argument type at the given offset. This will return `None` when the index is out of
522    /// bounds only for variadic functions, otherwise this will panic.
523    pub fn input(self, i: usize) -> Option<Binder<'tcx, Ty<'tcx>>> {
524        match self {
525            Self::Sig(sig, _) => {
526                if sig.c_variadic() {
527                    sig.inputs().map_bound(|inputs| inputs.get(i).copied()).transpose()
528                } else {
529                    Some(sig.input(i))
530                }
531            },
532            Self::Closure(_, sig) => Some(sig.input(0).map_bound(|ty| ty.tuple_fields()[i])),
533            Self::Trait(inputs, _, _) => Some(inputs.map_bound(|ty| ty.tuple_fields()[i])),
534        }
535    }
536
537    /// Gets the argument type at the given offset. For closures this will also get the type as
538    /// written. This will return `None` when the index is out of bounds only for variadic
539    /// functions, otherwise this will panic.
540    pub fn input_with_hir(self, i: usize) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> {
541        match self {
542            Self::Sig(sig, _) => {
543                if sig.c_variadic() {
544                    sig.inputs()
545                        .map_bound(|inputs| inputs.get(i).copied())
546                        .transpose()
547                        .map(|arg| (None, arg))
548                } else {
549                    Some((None, sig.input(i)))
550                }
551            },
552            Self::Closure(decl, sig) => Some((
553                decl.and_then(|decl| decl.inputs.get(i)),
554                sig.input(0).map_bound(|ty| ty.tuple_fields()[i]),
555            )),
556            Self::Trait(inputs, _, _) => Some((None, inputs.map_bound(|ty| ty.tuple_fields()[i]))),
557        }
558    }
559
560    /// Gets the result type, if one could be found. Note that the result type of a trait may not be
561    /// specified.
562    pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
563        match self {
564            Self::Sig(sig, _) | Self::Closure(_, sig) => Some(sig.output()),
565            Self::Trait(_, output, _) => output,
566        }
567    }
568
569    pub fn predicates_id(&self) -> Option<DefId> {
570        if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self {
571            id
572        } else {
573            None
574        }
575    }
576}
577
578/// If the expression is function like, get the signature for it.
579pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
580    if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = expr.res(cx) {
581        Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).instantiate_identity(), Some(id)))
582    } else {
583        ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs())
584    }
585}
586
587/// If the type is function like, get the signature for it.
588pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'tcx>> {
589    if let Some(boxed_ty) = ty.boxed_ty() {
590        return ty_sig(cx, boxed_ty);
591    }
592    match *ty.kind() {
593        ty::Closure(id, subs) => {
594            let decl = id
595                .as_local()
596                .and_then(|id| cx.tcx.hir_fn_decl_by_hir_id(cx.tcx.local_def_id_to_hir_id(id)));
597            Some(ExprFnSig::Closure(decl, subs.as_closure().sig()))
598        },
599        ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).instantiate(cx.tcx, subs), Some(id))),
600        ty::Alias(ty::Opaque, AliasTy { def_id, args, .. }) => sig_from_bounds(
601            cx,
602            ty,
603            cx.tcx.item_self_bounds(def_id).iter_instantiated(cx.tcx, args),
604            cx.tcx.opt_parent(def_id),
605        ),
606        ty::FnPtr(sig_tys, hdr) => Some(ExprFnSig::Sig(sig_tys.with(hdr), None)),
607        ty::Dynamic(bounds, _) => {
608            let lang_items = cx.tcx.lang_items();
609            match bounds.principal() {
610                Some(bound)
611                    if Some(bound.def_id()) == lang_items.fn_trait()
612                        || Some(bound.def_id()) == lang_items.fn_once_trait()
613                        || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
614                {
615                    let output = bounds
616                        .projection_bounds()
617                        .find(|p| lang_items.fn_once_output().is_some_and(|id| id == p.item_def_id()))
618                        .map(|p| p.map_bound(|p| p.term.expect_type()));
619                    Some(ExprFnSig::Trait(bound.map_bound(|b| b.args.type_at(0)), output, None))
620                },
621                _ => None,
622            }
623        },
624        ty::Alias(ty::Projection, proj) => match cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty) {
625            Ok(normalized_ty) if normalized_ty != ty => ty_sig(cx, normalized_ty),
626            _ => sig_for_projection(cx, proj).or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)),
627        },
628        ty::Param(_) => sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None),
629        _ => None,
630    }
631}
632
633fn sig_from_bounds<'tcx>(
634    cx: &LateContext<'tcx>,
635    ty: Ty<'tcx>,
636    predicates: impl IntoIterator<Item = ty::Clause<'tcx>>,
637    predicates_id: Option<DefId>,
638) -> Option<ExprFnSig<'tcx>> {
639    let mut inputs = None;
640    let mut output = None;
641    let lang_items = cx.tcx.lang_items();
642
643    for pred in predicates {
644        match pred.kind().skip_binder() {
645            ty::ClauseKind::Trait(p)
646                if (lang_items.fn_trait() == Some(p.def_id())
647                    || lang_items.fn_mut_trait() == Some(p.def_id())
648                    || lang_items.fn_once_trait() == Some(p.def_id()))
649                    && p.self_ty() == ty =>
650            {
651                let i = pred.kind().rebind(p.trait_ref.args.type_at(1));
652                if inputs.is_some_and(|inputs| i != inputs) {
653                    // Multiple different fn trait impls. Is this even allowed?
654                    return None;
655                }
656                inputs = Some(i);
657            },
658            ty::ClauseKind::Projection(p)
659                if Some(p.projection_term.def_id) == lang_items.fn_once_output()
660                    && p.projection_term.self_ty() == ty =>
661            {
662                if output.is_some() {
663                    // Multiple different fn trait impls. Is this even allowed?
664                    return None;
665                }
666                output = Some(pred.kind().rebind(p.term.expect_type()));
667            },
668            _ => (),
669        }
670    }
671
672    inputs.map(|ty| ExprFnSig::Trait(ty, output, predicates_id))
673}
674
675fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: AliasTy<'tcx>) -> Option<ExprFnSig<'tcx>> {
676    let mut inputs = None;
677    let mut output = None;
678    let lang_items = cx.tcx.lang_items();
679
680    for (pred, _) in cx
681        .tcx
682        .explicit_item_bounds(ty.def_id)
683        .iter_instantiated_copied(cx.tcx, ty.args)
684    {
685        match pred.kind().skip_binder() {
686            ty::ClauseKind::Trait(p)
687                if (lang_items.fn_trait() == Some(p.def_id())
688                    || lang_items.fn_mut_trait() == Some(p.def_id())
689                    || lang_items.fn_once_trait() == Some(p.def_id())) =>
690            {
691                let i = pred.kind().rebind(p.trait_ref.args.type_at(1));
692
693                if inputs.is_some_and(|inputs| inputs != i) {
694                    // Multiple different fn trait impls. Is this even allowed?
695                    return None;
696                }
697                inputs = Some(i);
698            },
699            ty::ClauseKind::Projection(p) if Some(p.projection_term.def_id) == lang_items.fn_once_output() => {
700                if output.is_some() {
701                    // Multiple different fn trait impls. Is this even allowed?
702                    return None;
703                }
704                output = pred.kind().rebind(p.term.as_type()).transpose();
705            },
706            _ => (),
707        }
708    }
709
710    inputs.map(|ty| ExprFnSig::Trait(ty, output, None))
711}
712
713#[derive(Clone, Copy)]
714pub enum EnumValue {
715    Unsigned(u128),
716    Signed(i128),
717}
718impl core::ops::Add<u32> for EnumValue {
719    type Output = Self;
720    fn add(self, n: u32) -> Self::Output {
721        match self {
722            Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
723            Self::Signed(x) => Self::Signed(x + i128::from(n)),
724        }
725    }
726}
727
728/// Attempts to read the given constant as though it were an enum value.
729pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
730    if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
731        match tcx.type_of(id).instantiate_identity().kind() {
732            ty::Int(_) => Some(EnumValue::Signed(value.to_int(value.size()))),
733            ty::Uint(_) => Some(EnumValue::Unsigned(value.to_uint(value.size()))),
734            _ => None,
735        }
736    } else {
737        None
738    }
739}
740
741/// Gets the value of the given variant.
742pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: AdtDef<'_>, i: VariantIdx) -> EnumValue {
743    let variant = &adt.variant(i);
744    match variant.discr {
745        VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
746        VariantDiscr::Relative(x) => match adt.variant((i.as_usize() - x as usize).into()).discr {
747            VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
748            VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
749        },
750    }
751}
752
753/// Check if the given type is either `core::ffi::c_void`, `std::os::raw::c_void`, or one of the
754/// platform specific `libc::<platform>::c_void` types in libc.
755pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
756    if let ty::Adt(adt, _) = ty.kind()
757        && let &[krate, .., name] = &*cx.get_def_path(adt.did())
758        && let sym::libc | sym::core | sym::std = krate
759        && name == sym::c_void
760    {
761        true
762    } else {
763        false
764    }
765}
766
767pub fn for_each_top_level_late_bound_region<B>(
768    ty: Ty<'_>,
769    f: impl FnMut(BoundRegion) -> ControlFlow<B>,
770) -> ControlFlow<B> {
771    struct V<F> {
772        index: u32,
773        f: F,
774    }
775    impl<'tcx, B, F: FnMut(BoundRegion) -> ControlFlow<B>> TypeVisitor<TyCtxt<'tcx>> for V<F> {
776        type Result = ControlFlow<B>;
777        fn visit_region(&mut self, r: Region<'tcx>) -> Self::Result {
778            if let RegionKind::ReBound(BoundVarIndexKind::Bound(idx), bound) = r.kind()
779                && idx.as_u32() == self.index
780            {
781                (self.f)(bound)
782            } else {
783                ControlFlow::Continue(())
784            }
785        }
786        fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(&mut self, t: &Binder<'tcx, T>) -> Self::Result {
787            self.index += 1;
788            let res = t.super_visit_with(self);
789            self.index -= 1;
790            res
791        }
792    }
793    ty.visit_with(&mut V { index: 0, f })
794}
795
796pub struct AdtVariantInfo {
797    pub ind: usize,
798    pub size: u64,
799
800    /// (ind, size)
801    pub fields_size: Vec<(usize, u64)>,
802}
803
804impl AdtVariantInfo {
805    /// Returns ADT variants ordered by size
806    pub fn new<'tcx>(cx: &LateContext<'tcx>, adt: AdtDef<'tcx>, subst: GenericArgsRef<'tcx>) -> Vec<Self> {
807        let mut variants_size = adt
808            .variants()
809            .iter()
810            .enumerate()
811            .map(|(i, variant)| {
812                let mut fields_size = variant
813                    .fields
814                    .iter()
815                    .enumerate()
816                    .map(|(i, f)| (i, approx_ty_size(cx, f.ty(cx.tcx, subst))))
817                    .collect::<Vec<_>>();
818                fields_size.sort_by(|(_, a_size), (_, b_size)| a_size.cmp(b_size));
819
820                Self {
821                    ind: i,
822                    size: fields_size.iter().map(|(_, size)| size).sum(),
823                    fields_size,
824                }
825            })
826            .collect::<Vec<_>>();
827        variants_size.sort_by(|a, b| b.size.cmp(&a.size));
828        variants_size
829    }
830}
831
832/// Gets the struct or enum variant from the given `Res`
833pub fn adt_and_variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option<(AdtDef<'tcx>, &'tcx VariantDef)> {
834    match res {
835        Res::Def(DefKind::Struct, id) => {
836            let adt = cx.tcx.adt_def(id);
837            Some((adt, adt.non_enum_variant()))
838        },
839        Res::Def(DefKind::Variant, id) => {
840            let adt = cx.tcx.adt_def(cx.tcx.parent(id));
841            Some((adt, adt.variant_with_id(id)))
842        },
843        Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => {
844            let adt = cx.tcx.adt_def(cx.tcx.parent(id));
845            Some((adt, adt.non_enum_variant()))
846        },
847        Res::Def(DefKind::Ctor(CtorOf::Variant, _), id) => {
848            let var_id = cx.tcx.parent(id);
849            let adt = cx.tcx.adt_def(cx.tcx.parent(var_id));
850            Some((adt, adt.variant_with_id(var_id)))
851        },
852        Res::SelfCtor(id) => {
853            let adt = cx.tcx.type_of(id).instantiate_identity().ty_adt_def().unwrap();
854            Some((adt, adt.non_enum_variant()))
855        },
856        _ => None,
857    }
858}
859
860/// Comes up with an "at least" guesstimate for the type's size, not taking into
861/// account the layout of type parameters.
862pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 {
863    use rustc_middle::ty::layout::LayoutOf;
864    match (cx.layout_of(ty).map(|layout| layout.size.bytes()), ty.kind()) {
865        (Ok(size), _) => size,
866        (Err(_), ty::Tuple(list)) => list.iter().map(|t| approx_ty_size(cx, t)).sum(),
867        (Err(_), ty::Array(t, n)) => n.try_to_target_usize(cx.tcx).unwrap_or_default() * approx_ty_size(cx, *t),
868        (Err(_), ty::Adt(def, subst)) if def.is_struct() => def
869            .variants()
870            .iter()
871            .map(|v| {
872                v.fields
873                    .iter()
874                    .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
875                    .sum::<u64>()
876            })
877            .sum(),
878        (Err(_), ty::Adt(def, subst)) if def.is_enum() => def
879            .variants()
880            .iter()
881            .map(|v| {
882                v.fields
883                    .iter()
884                    .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
885                    .sum::<u64>()
886            })
887            .max()
888            .unwrap_or_default(),
889        (Err(_), ty::Adt(def, subst)) if def.is_union() => def
890            .variants()
891            .iter()
892            .map(|v| {
893                v.fields
894                    .iter()
895                    .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
896                    .max()
897                    .unwrap_or_default()
898            })
899            .max()
900            .unwrap_or_default(),
901        (Err(_), _) => 0,
902    }
903}
904
905#[cfg(debug_assertions)]
906/// Asserts that the given arguments match the generic parameters of the given item.
907fn assert_generic_args_match<'tcx>(tcx: TyCtxt<'tcx>, did: DefId, args: &[GenericArg<'tcx>]) {
908    use itertools::Itertools;
909    let g = tcx.generics_of(did);
910    let parent = g.parent.map(|did| tcx.generics_of(did));
911    let count = g.parent_count + g.own_params.len();
912    let params = parent
913        .map_or([].as_slice(), |p| p.own_params.as_slice())
914        .iter()
915        .chain(&g.own_params)
916        .map(|x| &x.kind);
917
918    assert!(
919        count == args.len(),
920        "wrong number of arguments for `{did:?}`: expected `{count}`, found {}\n\
921            note: the expected arguments are: `[{}]`\n\
922            the given arguments are: `{args:#?}`",
923        args.len(),
924        params.clone().map(ty::GenericParamDefKind::descr).format(", "),
925    );
926
927    if let Some((idx, (param, arg))) =
928        params
929            .clone()
930            .zip(args.iter().map(|&x| x.kind()))
931            .enumerate()
932            .find(|(_, (param, arg))| match (param, arg) {
933                (ty::GenericParamDefKind::Lifetime, GenericArgKind::Lifetime(_))
934                | (ty::GenericParamDefKind::Type { .. }, GenericArgKind::Type(_))
935                | (ty::GenericParamDefKind::Const { .. }, GenericArgKind::Const(_)) => false,
936                (
937                    ty::GenericParamDefKind::Lifetime
938                    | ty::GenericParamDefKind::Type { .. }
939                    | ty::GenericParamDefKind::Const { .. },
940                    _,
941                ) => true,
942            })
943    {
944        panic!(
945            "incorrect argument for `{did:?}` at index `{idx}`: expected a {}, found `{arg:?}`\n\
946                note: the expected arguments are `[{}]`\n\
947                the given arguments are `{args:#?}`",
948            param.descr(),
949            params.clone().map(ty::GenericParamDefKind::descr).format(", "),
950        );
951    }
952}
953
954/// Returns whether `ty` is never-like; i.e., `!` (never) or an enum with zero variants.
955pub fn is_never_like(ty: Ty<'_>) -> bool {
956    ty.is_never() || (ty.is_enum() && ty.ty_adt_def().is_some_and(|def| def.variants().is_empty()))
957}
958
959/// Makes the projection type for the named associated type in the given impl or trait impl.
960///
961/// This function is for associated types which are "known" to exist, and as such, will only return
962/// `None` when debug assertions are disabled in order to prevent ICE's. With debug assertions
963/// enabled this will check that the named associated type exists, the correct number of
964/// arguments are given, and that the correct kinds of arguments are given (lifetime,
965/// constant or type). This will not check if type normalization would succeed.
966pub fn make_projection<'tcx>(
967    tcx: TyCtxt<'tcx>,
968    container_id: DefId,
969    assoc_ty: Symbol,
970    args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
971) -> Option<AliasTy<'tcx>> {
972    fn helper<'tcx>(
973        tcx: TyCtxt<'tcx>,
974        container_id: DefId,
975        assoc_ty: Symbol,
976        args: GenericArgsRef<'tcx>,
977    ) -> Option<AliasTy<'tcx>> {
978        let Some(assoc_item) = tcx.associated_items(container_id).find_by_ident_and_kind(
979            tcx,
980            Ident::with_dummy_span(assoc_ty),
981            AssocTag::Type,
982            container_id,
983        ) else {
984            debug_assert!(false, "type `{assoc_ty}` not found in `{container_id:?}`");
985            return None;
986        };
987        #[cfg(debug_assertions)]
988        assert_generic_args_match(tcx, assoc_item.def_id, args);
989
990        Some(AliasTy::new_from_args(tcx, assoc_item.def_id, args))
991    }
992    helper(
993        tcx,
994        container_id,
995        assoc_ty,
996        tcx.mk_args_from_iter(args.into_iter().map(Into::into)),
997    )
998}
999
1000/// Normalizes the named associated type in the given impl or trait impl.
1001///
1002/// This function is for associated types which are "known" to be valid with the given
1003/// arguments, and as such, will only return `None` when debug assertions are disabled in order
1004/// to prevent ICE's. With debug assertions enabled this will check that type normalization
1005/// succeeds as well as everything checked by `make_projection`.
1006pub fn make_normalized_projection<'tcx>(
1007    tcx: TyCtxt<'tcx>,
1008    typing_env: ty::TypingEnv<'tcx>,
1009    container_id: DefId,
1010    assoc_ty: Symbol,
1011    args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1012) -> Option<Ty<'tcx>> {
1013    fn helper<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1014        #[cfg(debug_assertions)]
1015        if let Some((i, arg)) = ty
1016            .args
1017            .iter()
1018            .enumerate()
1019            .find(|(_, arg)| arg.has_escaping_bound_vars())
1020        {
1021            debug_assert!(
1022                false,
1023                "args contain late-bound region at index `{i}` which can't be normalized.\n\
1024                    use `TyCtxt::instantiate_bound_regions_with_erased`\n\
1025                    note: arg is `{arg:#?}`",
1026            );
1027            return None;
1028        }
1029        match tcx.try_normalize_erasing_regions(typing_env, Ty::new_projection_from_args(tcx, ty.def_id, ty.args)) {
1030            Ok(ty) => Some(ty),
1031            Err(e) => {
1032                debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1033                None
1034            },
1035        }
1036    }
1037    helper(tcx, typing_env, make_projection(tcx, container_id, assoc_ty, args)?)
1038}
1039
1040/// Helper to check if given type has inner mutability such as [`std::cell::Cell`] or
1041/// [`std::cell::RefCell`].
1042#[derive(Default, Debug)]
1043pub struct InteriorMut<'tcx> {
1044    ignored_def_ids: FxHashSet<DefId>,
1045    ignore_pointers: bool,
1046    tys: FxHashMap<Ty<'tcx>, Option<&'tcx ty::List<Ty<'tcx>>>>,
1047}
1048
1049impl<'tcx> InteriorMut<'tcx> {
1050    pub fn new(tcx: TyCtxt<'tcx>, ignore_interior_mutability: &[String]) -> Self {
1051        let ignored_def_ids = ignore_interior_mutability
1052            .iter()
1053            .flat_map(|ignored_ty| lookup_path_str(tcx, PathNS::Type, ignored_ty))
1054            .collect();
1055
1056        Self {
1057            ignored_def_ids,
1058            ..Self::default()
1059        }
1060    }
1061
1062    pub fn without_pointers(tcx: TyCtxt<'tcx>, ignore_interior_mutability: &[String]) -> Self {
1063        Self {
1064            ignore_pointers: true,
1065            ..Self::new(tcx, ignore_interior_mutability)
1066        }
1067    }
1068
1069    /// Check if given type has interior mutability such as [`std::cell::Cell`] or
1070    /// [`std::cell::RefCell`] etc. and if it does, returns a chain of types that causes
1071    /// this type to be interior mutable.  False negatives may be expected for infinitely recursive
1072    /// types, and `None` will be returned there.
1073    pub fn interior_mut_ty_chain(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<&'tcx ty::List<Ty<'tcx>>> {
1074        self.interior_mut_ty_chain_inner(cx, ty, 0)
1075    }
1076
1077    fn interior_mut_ty_chain_inner(
1078        &mut self,
1079        cx: &LateContext<'tcx>,
1080        ty: Ty<'tcx>,
1081        depth: usize,
1082    ) -> Option<&'tcx ty::List<Ty<'tcx>>> {
1083        if !cx.tcx.recursion_limit().value_within_limit(depth) {
1084            return None;
1085        }
1086
1087        match self.tys.entry(ty) {
1088            Entry::Occupied(o) => return *o.get(),
1089            // Temporarily insert a `None` to break cycles
1090            Entry::Vacant(v) => v.insert(None),
1091        };
1092        let depth = depth + 1;
1093
1094        let chain = match *ty.kind() {
1095            ty::RawPtr(inner_ty, _) if !self.ignore_pointers => self.interior_mut_ty_chain_inner(cx, inner_ty, depth),
1096            ty::Ref(_, inner_ty, _) | ty::Slice(inner_ty) => self.interior_mut_ty_chain_inner(cx, inner_ty, depth),
1097            ty::Array(inner_ty, size) if size.try_to_target_usize(cx.tcx) != Some(0) => {
1098                self.interior_mut_ty_chain_inner(cx, inner_ty, depth)
1099            },
1100            ty::Tuple(fields) => fields
1101                .iter()
1102                .find_map(|ty| self.interior_mut_ty_chain_inner(cx, ty, depth)),
1103            ty::Adt(def, _) if def.is_unsafe_cell() => Some(ty::List::empty()),
1104            ty::Adt(def, args) => {
1105                let is_std_collection = matches!(
1106                    cx.tcx.get_diagnostic_name(def.did()),
1107                    Some(
1108                        sym::LinkedList
1109                            | sym::Vec
1110                            | sym::VecDeque
1111                            | sym::BTreeMap
1112                            | sym::BTreeSet
1113                            | sym::HashMap
1114                            | sym::HashSet
1115                            | sym::Arc
1116                            | sym::Rc
1117                    )
1118                );
1119
1120                if is_std_collection || def.is_box() {
1121                    // Include the types from std collections that are behind pointers internally
1122                    args.types()
1123                        .find_map(|ty| self.interior_mut_ty_chain_inner(cx, ty, depth))
1124                } else if self.ignored_def_ids.contains(&def.did()) || def.is_phantom_data() {
1125                    None
1126                } else {
1127                    def.all_fields()
1128                        .find_map(|f| self.interior_mut_ty_chain_inner(cx, f.ty(cx.tcx, args), depth))
1129                }
1130            },
1131            ty::Alias(ty::Projection, _) => match cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty) {
1132                Ok(normalized_ty) if ty != normalized_ty => self.interior_mut_ty_chain_inner(cx, normalized_ty, depth),
1133                _ => None,
1134            },
1135            _ => None,
1136        };
1137
1138        chain.map(|chain| {
1139            let list = cx.tcx.mk_type_list_from_iter(chain.iter().chain([ty]));
1140            self.tys.insert(ty, Some(list));
1141            list
1142        })
1143    }
1144
1145    /// Check if given type has interior mutability such as [`std::cell::Cell`] or
1146    /// [`std::cell::RefCell`] etc.
1147    pub fn is_interior_mut_ty(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1148        self.interior_mut_ty_chain(cx, ty).is_some()
1149    }
1150}
1151
1152pub fn make_normalized_projection_with_regions<'tcx>(
1153    tcx: TyCtxt<'tcx>,
1154    typing_env: ty::TypingEnv<'tcx>,
1155    container_id: DefId,
1156    assoc_ty: Symbol,
1157    args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1158) -> Option<Ty<'tcx>> {
1159    fn helper<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1160        #[cfg(debug_assertions)]
1161        if let Some((i, arg)) = ty
1162            .args
1163            .iter()
1164            .enumerate()
1165            .find(|(_, arg)| arg.has_escaping_bound_vars())
1166        {
1167            debug_assert!(
1168                false,
1169                "args contain late-bound region at index `{i}` which can't be normalized.\n\
1170                    use `TyCtxt::instantiate_bound_regions_with_erased`\n\
1171                    note: arg is `{arg:#?}`",
1172            );
1173            return None;
1174        }
1175        let cause = ObligationCause::dummy();
1176        let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
1177        match infcx
1178            .at(&cause, param_env)
1179            .query_normalize(Ty::new_projection_from_args(tcx, ty.def_id, ty.args))
1180        {
1181            Ok(ty) => Some(ty.value),
1182            Err(e) => {
1183                debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1184                None
1185            },
1186        }
1187    }
1188    helper(tcx, typing_env, make_projection(tcx, container_id, assoc_ty, args)?)
1189}
1190
1191pub fn normalize_with_regions<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1192    let cause = ObligationCause::dummy();
1193    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
1194    infcx
1195        .at(&cause, param_env)
1196        .query_normalize(ty)
1197        .map_or(ty, |ty| ty.value)
1198}
1199
1200/// Checks if the type is `core::mem::ManuallyDrop<_>`
1201pub fn is_manually_drop(ty: Ty<'_>) -> bool {
1202    ty.ty_adt_def().is_some_and(AdtDef::is_manually_drop)
1203}
1204
1205/// Returns the deref chain of a type, starting with the type itself.
1206pub fn deref_chain<'cx, 'tcx>(cx: &'cx LateContext<'tcx>, ty: Ty<'tcx>) -> impl Iterator<Item = Ty<'tcx>> + 'cx {
1207    iter::successors(Some(ty), |&ty| {
1208        if let Some(deref_did) = cx.tcx.lang_items().deref_trait()
1209            && implements_trait(cx, ty, deref_did, &[])
1210        {
1211            make_normalized_projection(cx.tcx, cx.typing_env(), deref_did, sym::Target, [ty])
1212        } else {
1213            None
1214        }
1215    })
1216}
1217
1218/// Checks if a Ty<'_> has some inherent method Symbol.
1219///
1220/// This does not look for impls in the type's `Deref::Target` type.
1221/// If you need this, you should wrap this call in `clippy_utils::ty::deref_chain().any(...)`.
1222pub fn get_adt_inherent_method<'a>(cx: &'a LateContext<'_>, ty: Ty<'_>, method_name: Symbol) -> Option<&'a AssocItem> {
1223    if let Some(ty_did) = ty.ty_adt_def().map(AdtDef::did) {
1224        cx.tcx.inherent_impls(ty_did).iter().find_map(|&did| {
1225            cx.tcx
1226                .associated_items(did)
1227                .filter_by_name_unhygienic(method_name)
1228                .next()
1229                .filter(|item| item.as_tag() == AssocTag::Fn)
1230        })
1231    } else {
1232        None
1233    }
1234}
1235
1236/// Gets the type of a field by name.
1237pub fn get_field_by_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
1238    match *ty.kind() {
1239        ty::Adt(def, args) if def.is_union() || def.is_struct() => def
1240            .non_enum_variant()
1241            .fields
1242            .iter()
1243            .find(|f| f.name == name)
1244            .map(|f| f.ty(tcx, args)),
1245        ty::Tuple(args) => name.as_str().parse::<usize>().ok().and_then(|i| args.get(i).copied()),
1246        _ => None,
1247    }
1248}
1249
1250/// Check if `ty` is an `Option` and return its argument type if it is.
1251pub fn option_arg_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1252    match *ty.kind() {
1253        ty::Adt(adt, args)
1254            if let [arg] = &**args
1255                && let Some(arg) = arg.as_type()
1256                && adt.is_diag_item(cx, sym::Option) =>
1257        {
1258            Some(arg)
1259        },
1260        _ => None,
1261    }
1262}
1263
1264/// Check if a Ty<'_> of `Iterator` contains any mutable access to non-owning types by checking if
1265/// it contains fields of mutable references or pointers, or references/pointers to non-`Freeze`
1266/// types, or `PhantomData` types containing any of the previous. This can be used to check whether
1267/// skipping iterating over an iterator will change its behavior.
1268pub fn has_non_owning_mutable_access<'tcx>(cx: &LateContext<'tcx>, iter_ty: Ty<'tcx>) -> bool {
1269    fn normalize_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1270        cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty).unwrap_or(ty)
1271    }
1272
1273    /// Check if `ty` contains mutable references or equivalent, which includes:
1274    /// - A mutable reference/pointer.
1275    /// - A reference/pointer to a non-`Freeze` type.
1276    /// - A `PhantomData` type containing any of the previous.
1277    fn has_non_owning_mutable_access_inner<'tcx>(
1278        cx: &LateContext<'tcx>,
1279        phantoms: &mut FxHashSet<Ty<'tcx>>,
1280        ty: Ty<'tcx>,
1281    ) -> bool {
1282        match ty.kind() {
1283            ty::Adt(adt_def, args) if adt_def.is_phantom_data() => {
1284                phantoms.insert(ty)
1285                    && args
1286                        .types()
1287                        .any(|arg_ty| has_non_owning_mutable_access_inner(cx, phantoms, arg_ty))
1288            },
1289            ty::Adt(adt_def, args) => adt_def.all_fields().any(|field| {
1290                has_non_owning_mutable_access_inner(cx, phantoms, normalize_ty(cx, field.ty(cx.tcx, args)))
1291            }),
1292            ty::Array(elem_ty, _) | ty::Slice(elem_ty) => has_non_owning_mutable_access_inner(cx, phantoms, *elem_ty),
1293            ty::RawPtr(pointee_ty, mutability) | ty::Ref(_, pointee_ty, mutability) => {
1294                mutability.is_mut() || !pointee_ty.is_freeze(cx.tcx, cx.typing_env())
1295            },
1296            ty::Closure(_, closure_args) => {
1297                matches!(closure_args.types().next_back(),
1298                         Some(captures) if has_non_owning_mutable_access_inner(cx, phantoms, captures))
1299            },
1300            ty::Tuple(tuple_args) => tuple_args
1301                .iter()
1302                .any(|arg_ty| has_non_owning_mutable_access_inner(cx, phantoms, arg_ty)),
1303            _ => false,
1304        }
1305    }
1306
1307    let mut phantoms = FxHashSet::default();
1308    has_non_owning_mutable_access_inner(cx, &mut phantoms, iter_ty)
1309}
1310
1311/// Check if `ty` is slice-like, i.e., `&[T]`, `[T; N]`, or `Vec<T>`.
1312pub fn is_slice_like<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1313    ty.is_slice() || ty.is_array() || ty.is_diag_item(cx, sym::Vec)
1314}
1315
1316pub fn get_field_idx_by_name(ty: Ty<'_>, name: Symbol) -> Option<usize> {
1317    match *ty.kind() {
1318        ty::Adt(def, _) if def.is_union() || def.is_struct() => {
1319            def.non_enum_variant().fields.iter().position(|f| f.name == name)
1320        },
1321        ty::Tuple(_) => name.as_str().parse::<usize>().ok(),
1322        _ => None,
1323    }
1324}
1325
1326/// Checks if the adjustments contain a mutable dereference of a `ManuallyDrop<_>`.
1327pub fn adjust_derefs_manually_drop<'tcx>(adjustments: &'tcx [Adjustment<'tcx>], mut ty: Ty<'tcx>) -> bool {
1328    adjustments.iter().any(|a| {
1329        let ty = mem::replace(&mut ty, a.target);
1330        matches!(a.kind, Adjust::Deref(Some(op)) if op.mutbl == Mutability::Mut) && is_manually_drop(ty)
1331    })
1332}