Skip to main content

clippy_utils/ty/
mod.rs

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