Skip to main content

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