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