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