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