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