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