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