Skip to main content

clippy_utils/ty/
mod.rs

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