Skip to main content

clippy_utils/ty/
mod.rs

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