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