clippy_utils/ty/
mod.rs

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