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