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