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