Skip to main content

clippy_utils/ty/
mod.rs

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