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