Skip to main content

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