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