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, ProjectionAliasTy, Region, RegionKind, TraitRef, Ty, TyCtxt,
24    TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, UintTy, Unnormalized, Upcast, VariantDef,
25    VariantDiscr,
26};
27use rustc_span::symbol::Ident;
28use rustc_span::{DUMMY_SP, Span, Symbol};
29use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
30use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
31use rustc_trait_selection::traits::{Obligation, ObligationCause};
32use std::collections::hash_map::Entry;
33use std::{debug_assert_matches, iter, mem};
34
35use crate::paths::{PathNS, lookup_path_str};
36use crate::res::{MaybeDef, MaybeQPath};
37use crate::sym;
38
39mod type_certainty;
40pub use type_certainty::expr_type_is_certain;
41
42/// Lower a [`hir::Ty`] to a [`rustc_middle::ty::Ty`].
43pub fn ty_from_hir_ty<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
44    cx.maybe_typeck_results()
45        .filter(|results| results.hir_owner == hir_ty.hir_id.owner)
46        .and_then(|results| results.node_type_opt(hir_ty.hir_id))
47        .unwrap_or_else(|| lower_ty(cx.tcx, hir_ty))
48}
49
50/// Checks if the given type implements copy.
51pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
52    cx.type_is_copy_modulo_regions(ty)
53}
54
55/// This checks whether a given type is known to implement Debug.
56pub fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
57    cx.tcx
58        .get_diagnostic_item(sym::Debug)
59        .is_some_and(|debug| implements_trait(cx, ty, debug, &[]))
60}
61
62/// Checks whether a type can be partially moved.
63pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
64    if has_drop(cx, ty) || is_copy(cx, ty) {
65        return false;
66    }
67    match ty.kind() {
68        ty::Param(_) => false,
69        ty::Adt(def, subs) => def
70            .all_fields()
71            .any(|f| !is_copy(cx, f.ty(cx.tcx, subs).skip_norm_wip())),
72        _ => true,
73    }
74}
75
76/// Walks into `ty` and returns `true` if any inner type is an instance of the given adt
77/// constructor.
78pub fn contains_adt_constructor<'tcx>(ty: Ty<'tcx>, adt: AdtDef<'tcx>) -> bool {
79    ty.walk().any(|inner| match inner.kind() {
80        GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
81        GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
82    })
83}
84
85/// Walks into `ty` and returns `true` if any inner type is an instance of the given type, or adt
86/// constructor of the same type.
87///
88/// This method also recurses into opaque type predicates, so call it with `impl Trait<U>` and `U`
89/// will also return `true`.
90pub fn contains_ty_adt_constructor_opaque<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, needle: Ty<'tcx>) -> bool {
91    fn contains_ty_adt_constructor_opaque_inner<'tcx>(
92        cx: &LateContext<'tcx>,
93        ty: Ty<'tcx>,
94        needle: Ty<'tcx>,
95        seen: &mut FxHashSet<DefId>,
96    ) -> bool {
97        ty.walk().any(|inner| match inner.kind() {
98            GenericArgKind::Type(inner_ty) => {
99                if inner_ty == needle {
100                    return true;
101                }
102
103                if inner_ty.ty_adt_def() == needle.ty_adt_def() {
104                    return true;
105                }
106
107                if let ty::Alias(_, AliasTy {
108                    kind: ty::Opaque { def_id },
109                    ..
110                }) = *inner_ty.kind()
111                {
112                    if !seen.insert(def_id) {
113                        return false;
114                    }
115
116                    for (predicate, _span) in cx
117                        .tcx
118                        .explicit_item_self_bounds(def_id)
119                        .iter_identity_copied()
120                        .map(Unnormalized::skip_norm_wip)
121                    {
122                        match predicate.kind().skip_binder() {
123                            // For `impl Trait<U>`, it will register a predicate of `T: Trait<U>`, so we go through
124                            // and check substitutions to find `U`.
125                            ty::ClauseKind::Trait(trait_predicate)
126                                if trait_predicate
127                                    .trait_ref
128                                    .args
129                                    .types()
130                                    .skip(1) // Skip the implicit `Self` generic parameter
131                                    .any(|ty| contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen)) =>
132                            {
133                                return true;
134                            },
135                            // For `impl Trait<Assoc=U>`, it will register a predicate of `<T as Trait>::Assoc = U`,
136                            // so we check the term for `U`.
137                            ty::ClauseKind::Projection(projection_predicate) => {
138                                if let ty::TermKind::Ty(ty) = projection_predicate.term.kind()
139                                    && contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen)
140                                {
141                                    return true;
142                                }
143                            },
144                            _ => (),
145                        }
146                    }
147                }
148
149                false
150            },
151            GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
152        })
153    }
154
155    // A hash set to ensure that the same opaque type (`impl Trait` in RPIT or TAIT) is not
156    // visited twice.
157    let mut seen = FxHashSet::default();
158    contains_ty_adt_constructor_opaque_inner(cx, ty, needle, &mut seen)
159}
160
161/// Resolves `<T as Iterator>::Item` for `T`
162/// Do not invoke without first verifying that the type implements `Iterator`
163pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
164    cx.tcx
165        .get_diagnostic_item(sym::Iterator)
166        .and_then(|iter_did| cx.get_associated_type(ty, iter_did, sym::Item))
167}
168
169/// Returns true if `ty` is a type on which calling `Clone` through a function instead of
170/// as a method, such as `Arc::clone()` is considered idiomatic.
171///
172/// Lints should avoid suggesting to replace instances of `ty::Clone()` by `.clone()` for objects
173/// of those types.
174pub fn should_call_clone_as_function(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
175    matches!(
176        ty.opt_diag_name(cx),
177        Some(sym::Arc | sym::ArcWeak | sym::Rc | sym::RcWeak)
178    )
179}
180
181/// If `ty` is known to have a `iter` or `iter_mut` method, returns a symbol representing the type.
182pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
183    // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
184    // exists and has the desired signature. Unfortunately FnCtxt is not exported
185    // so we can't use its `lookup_method` method.
186    let into_iter_collections: &[Symbol] = &[
187        sym::Vec,
188        sym::Option,
189        sym::Result,
190        sym::BTreeMap,
191        sym::BTreeSet,
192        sym::VecDeque,
193        sym::LinkedList,
194        sym::BinaryHeap,
195        sym::HashSet,
196        sym::HashMap,
197        sym::PathBuf,
198        sym::Path,
199        sym::MpscReceiver,
200        sym::MpmcReceiver,
201    ];
202
203    let ty_to_check = match probably_ref_ty.kind() {
204        ty::Ref(_, ty_to_check, _) => *ty_to_check,
205        _ => probably_ref_ty,
206    };
207
208    let def_id = match ty_to_check.kind() {
209        ty::Array(..) => return Some(sym::array),
210        ty::Slice(..) => return Some(sym::slice),
211        ty::Adt(adt, _) => adt.did(),
212        _ => return None,
213    };
214
215    for &name in into_iter_collections {
216        if cx.tcx.is_diagnostic_item(name, def_id) {
217            return Some(cx.tcx.item_name(def_id));
218        }
219    }
220    None
221}
222
223/// Checks whether a type implements a trait.
224/// The function returns false in case the type contains an inference variable.
225///
226/// See [Common tools for writing lints] for an example how to use this function and other options.
227///
228/// [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
229pub fn implements_trait<'tcx>(
230    cx: &LateContext<'tcx>,
231    ty: Ty<'tcx>,
232    trait_id: DefId,
233    args: &[GenericArg<'tcx>],
234) -> bool {
235    implements_trait_with_env_from_iter(
236        cx.tcx,
237        cx.typing_env(),
238        ty,
239        trait_id,
240        None,
241        args.iter().map(|&x| Some(x)),
242    )
243}
244
245/// Same as `implements_trait` but allows using a `ParamEnv` different from the lint context.
246///
247/// The `callee_id` argument is used to determine whether this is a function call in a `const fn`
248/// environment, used for checking const traits.
249pub fn implements_trait_with_env<'tcx>(
250    tcx: TyCtxt<'tcx>,
251    typing_env: ty::TypingEnv<'tcx>,
252    ty: Ty<'tcx>,
253    trait_id: DefId,
254    callee_id: Option<DefId>,
255    args: &[GenericArg<'tcx>],
256) -> bool {
257    implements_trait_with_env_from_iter(tcx, typing_env, ty, trait_id, callee_id, args.iter().map(|&x| Some(x)))
258}
259
260/// Same as `implements_trait_from_env` but takes the arguments as an iterator.
261pub fn implements_trait_with_env_from_iter<'tcx>(
262    tcx: TyCtxt<'tcx>,
263    typing_env: ty::TypingEnv<'tcx>,
264    ty: Ty<'tcx>,
265    trait_id: DefId,
266    callee_id: Option<DefId>,
267    args: impl IntoIterator<Item = impl Into<Option<GenericArg<'tcx>>>>,
268) -> bool {
269    // Clippy shouldn't have infer types
270    assert!(!ty.has_infer());
271
272    // If a `callee_id` is passed, then we assert that it is a body owner
273    // through calling `body_owner_kind`, which would panic if the callee
274    // does not have a body.
275    if let Some(callee_id) = callee_id {
276        let _ = tcx.hir_body_owner_kind(callee_id);
277    }
278
279    let ty = tcx.erase_and_anonymize_regions(ty);
280    if ty.has_escaping_bound_vars() {
281        return false;
282    }
283
284    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
285    let args = args
286        .into_iter()
287        .map(|arg| arg.into().unwrap_or_else(|| infcx.next_ty_var(DUMMY_SP).into()))
288        .collect::<Vec<_>>();
289
290    let trait_ref = TraitRef::new(tcx, trait_id, [GenericArg::from(ty)].into_iter().chain(args));
291
292    debug_assert_matches!(
293        tcx.def_kind(trait_id),
294        DefKind::Trait | DefKind::TraitAlias,
295        "`DefId` must belong to a trait or trait alias"
296    );
297    #[cfg(debug_assertions)]
298    assert_generic_args_match(tcx, trait_id, trait_ref.args);
299
300    let obligation = Obligation {
301        cause: ObligationCause::dummy(),
302        param_env,
303        recursion_depth: 0,
304        predicate: trait_ref.upcast(tcx),
305    };
306    infcx
307        .evaluate_obligation(&obligation)
308        .is_ok_and(EvaluationResult::must_apply_modulo_regions)
309}
310
311/// Checks whether this type implements `Drop`.
312pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
313    match ty.ty_adt_def() {
314        Some(def) => def.has_dtor(cx.tcx),
315        None => false,
316    }
317}
318
319// Returns whether the `ty` has `#[must_use]` attribute. If `ty` is a `Result`/`ControlFlow`
320// whose `Err`/`Break` payload is an uninhabited type, the `Ok`/`Continue` payload type
321// will be used instead. See <https://github.com/rust-lang/rust/pull/148214>.
322pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
323    match ty.kind() {
324        ty::Adt(adt, args) => match cx.tcx.get_diagnostic_name(adt.did()) {
325            Some(sym::Result) if args.type_at(1).is_privately_uninhabited(cx.tcx, cx.typing_env()) => {
326                is_must_use_ty(cx, args.type_at(0))
327            },
328            Some(sym::ControlFlow) if args.type_at(0).is_privately_uninhabited(cx.tcx, cx.typing_env()) => {
329                is_must_use_ty(cx, args.type_at(1))
330            },
331            _ => find_attr!(cx.tcx, adt.did(), MustUse { .. }),
332        },
333        ty::Foreign(did) => find_attr!(cx.tcx, *did, MustUse { .. }),
334        ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty, _) | ty::Ref(_, ty, _) => {
335            // for the Array case we don't need to care for the len == 0 case
336            // because we don't want to lint functions returning empty arrays
337            is_must_use_ty(cx, *ty)
338        },
339        ty::Tuple(args) => args.iter().any(|ty| is_must_use_ty(cx, ty)),
340        ty::Alias(_, AliasTy {
341            kind: ty::Opaque { def_id },
342            ..
343        }) => {
344            for (predicate, _) in cx.tcx.explicit_item_self_bounds(*def_id).skip_binder() {
345                if let ty::ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder()
346                    && find_attr!(cx.tcx, trait_predicate.trait_ref.def_id, MustUse { .. })
347                {
348                    return true;
349                }
350            }
351            false
352        },
353        ty::Dynamic(binder, _) => {
354            for predicate in *binder {
355                if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder()
356                    && find_attr!(cx.tcx, trait_ref.def_id, MustUse { .. })
357                {
358                    return true;
359                }
360            }
361            false
362        },
363        _ => false,
364    }
365}
366
367/// Returns `true` if the given type is a non aggregate primitive (a `bool` or `char`, any
368/// integer or floating-point number type).
369///
370/// For checking aggregation of primitive types (e.g. tuples and slices of primitive type) see
371/// `is_recursively_primitive_type`
372pub fn is_non_aggregate_primitive_type(ty: Ty<'_>) -> bool {
373    matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_))
374}
375
376/// Returns `true` if the given type is a primitive (a `bool` or `char`, any integer or
377/// floating-point number type, a `str`, or an array, slice, or tuple of those types).
378pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
379    match *ty.kind() {
380        ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
381        ty::Ref(_, inner, _) if inner.is_str() => true,
382        ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
383        ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type),
384        _ => false,
385    }
386}
387
388/// Return `true` if the passed `typ` is `isize` or `usize`.
389pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
390    matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
391}
392
393/// Checks if the drop order for a type matters.
394///
395/// Some std types implement drop solely to deallocate memory. For these types, and composites
396/// containing them, changing the drop order won't result in any observable side effects.
397pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
398    fn needs_ordered_drop_inner<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
399        if !seen.insert(ty) {
400            return false;
401        }
402        if !ty.has_significant_drop(cx.tcx, cx.typing_env()) {
403            false
404        }
405        // Check for std types which implement drop, but only for memory allocation.
406        else if ty.is_lang_item(cx, LangItem::OwnedBox)
407            || matches!(
408                ty.opt_diag_name(cx),
409                Some(sym::HashSet | sym::Rc | sym::Arc | sym::cstring_type | sym::RcWeak | sym::ArcWeak)
410            )
411        {
412            // Check all of the generic arguments.
413            if let ty::Adt(_, subs) = ty.kind() {
414                subs.types().any(|ty| needs_ordered_drop_inner(cx, ty, seen))
415            } else {
416                true
417            }
418        } else if !cx
419            .tcx
420            .lang_items()
421            .drop_trait()
422            .is_some_and(|id| implements_trait(cx, ty, id, &[]))
423        {
424            // This type doesn't implement drop, so no side effects here.
425            // Check if any component type has any.
426            match ty.kind() {
427                ty::Tuple(fields) => fields.iter().any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
428                ty::Array(ty, _) => needs_ordered_drop_inner(cx, *ty, seen),
429                ty::Adt(adt, subs) => adt
430                    .all_fields()
431                    .map(|f| f.ty(cx.tcx, subs).skip_norm_wip())
432                    .any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
433                _ => true,
434            }
435        } else {
436            true
437        }
438    }
439
440    needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
441}
442
443/// Returns `true` if `ty` denotes an `unsafe fn`.
444pub fn is_unsafe_fn<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
445    ty.is_fn() && ty.fn_sig(cx.tcx).safety().is_unsafe()
446}
447
448/// Peels off all references on the type. Returns the underlying type, the number of references
449/// removed, and, if there were any such references, whether the pointer is ultimately mutable or
450/// not.
451pub fn peel_and_count_ty_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize, Option<Mutability>) {
452    let mut count = 0;
453    let mut mutbl = None;
454    while let ty::Ref(_, dest_ty, m) = ty.kind() {
455        ty = *dest_ty;
456        count += 1;
457        mutbl.replace(mutbl.map_or(*m, |mutbl: Mutability| mutbl.min(*m)));
458    }
459    (ty, count, mutbl)
460}
461
462/// Peels off `n` references on the type. Returns the underlying type and, if any references
463/// were removed, whether the pointer is ultimately mutable or not.
464pub fn peel_n_ty_refs(mut ty: Ty<'_>, n: usize) -> (Ty<'_>, Option<Mutability>) {
465    let mut mutbl = None;
466    for _ in 0..n {
467        if let ty::Ref(_, dest_ty, m) = ty.kind() {
468            ty = *dest_ty;
469            mutbl.replace(mutbl.map_or(*m, |mutbl: Mutability| mutbl.min(*m)));
470        } else {
471            break;
472        }
473    }
474    (ty, mutbl)
475}
476
477/// Checks whether `a` and `b` are same types having same `Const` generic args, but ignores
478/// lifetimes.
479///
480/// For example, the function would return `true` for
481/// - `u32` and `u32`
482/// - `[u8; N]` and `[u8; M]`, if `N=M`
483/// - `Option<T>` and `Option<U>`, if `same_type_modulo_regions(T, U)` holds
484/// - `&'a str` and `&'b str`
485///
486/// and `false` for:
487/// - `Result<u32, String>` and `Result<usize, String>`
488pub fn same_type_modulo_regions<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
489    match (&a.kind(), &b.kind()) {
490        (&ty::Adt(did_a, args_a), &ty::Adt(did_b, args_b)) => {
491            if did_a != did_b {
492                return false;
493            }
494
495            iter::zip(*args_a, *args_b).all(|(arg_a, arg_b)| match (arg_a.kind(), arg_b.kind()) {
496                (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
497                (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
498                    same_type_modulo_regions(type_a, type_b)
499                },
500                _ => true,
501            })
502        },
503        _ => a == b,
504    }
505}
506
507/// Checks if a given type looks safe to be uninitialized.
508pub fn is_uninit_value_valid_for_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
509    let typing_env = cx.typing_env().with_post_analysis_normalized(cx.tcx);
510    cx.tcx
511        .check_validity_requirement((ValidityRequirement::Uninit, typing_env.as_query_input(ty)))
512        .unwrap_or_else(|_| is_uninit_value_valid_for_ty_fallback(cx, ty))
513}
514
515/// A fallback for polymorphic types, which are not supported by `check_validity_requirement`.
516fn is_uninit_value_valid_for_ty_fallback<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
517    match *ty.kind() {
518        // The array length may be polymorphic, let's try the inner type.
519        ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
520        // Peek through tuples and try their fallbacks.
521        ty::Tuple(types) => types.iter().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
522        // Unions are always fine right now.
523        // This includes MaybeUninit, the main way people use uninitialized memory.
524        ty::Adt(adt, _) if adt.is_union() => true,
525        // Types (e.g. `UnsafeCell<MaybeUninit<T>>`) that recursively contain only types that can be uninit
526        // can themselves be uninit too.
527        // This purposefully ignores enums as they may have a discriminant that can't be uninit.
528        ty::Adt(adt, args) if adt.is_struct() => adt
529            .all_fields()
530            .all(|field| is_uninit_value_valid_for_ty(cx, field.ty(cx.tcx, args).skip_norm_wip())),
531        // For the rest, conservatively assume that they cannot be uninit.
532        _ => false,
533    }
534}
535
536/// Gets an iterator over all predicates which apply to the given item.
537pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(ty::Clause<'_>, Span)> {
538    let mut next_id = Some(id);
539    iter::from_fn(move || {
540        next_id.take().map(|id| {
541            let preds = tcx.predicates_of(id);
542            next_id = preds.parent;
543            preds.predicates.iter()
544        })
545    })
546    .flatten()
547}
548
549/// A signature for a function like type.
550#[derive(Clone, Copy, Debug)]
551pub enum ExprFnSig<'tcx> {
552    Sig(Binder<'tcx, FnSig<'tcx>>, Option<DefId>),
553    Closure(Option<&'tcx FnDecl<'tcx>>, Binder<'tcx, FnSig<'tcx>>),
554    Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>, Option<DefId>),
555}
556impl<'tcx> ExprFnSig<'tcx> {
557    /// Gets the argument type at the given offset. This will return `None` when the index is out of
558    /// bounds only for variadic functions, otherwise this will panic.
559    pub fn input(self, i: usize) -> Option<Binder<'tcx, Ty<'tcx>>> {
560        match self {
561            Self::Sig(sig, _) => {
562                if sig.c_variadic() {
563                    sig.inputs().map_bound(|inputs| inputs.get(i).copied()).transpose()
564                } else {
565                    Some(sig.input(i))
566                }
567            },
568            Self::Closure(_, sig) => Some(sig.input(0).map_bound(|ty| ty.tuple_fields()[i])),
569            Self::Trait(inputs, _, _) => Some(inputs.map_bound(|ty| ty.tuple_fields()[i])),
570        }
571    }
572
573    /// Gets the argument type at the given offset. For closures this will also get the type as
574    /// written. This will return `None` when the index is out of bounds only for variadic
575    /// functions, otherwise this will panic.
576    pub fn input_with_hir(self, i: usize) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> {
577        match self {
578            Self::Sig(sig, _) => {
579                if sig.c_variadic() {
580                    sig.inputs()
581                        .map_bound(|inputs| inputs.get(i).copied())
582                        .transpose()
583                        .map(|arg| (None, arg))
584                } else {
585                    Some((None, sig.input(i)))
586                }
587            },
588            Self::Closure(decl, sig) => Some((
589                decl.and_then(|decl| decl.inputs.get(i)),
590                sig.input(0).map_bound(|ty| ty.tuple_fields()[i]),
591            )),
592            Self::Trait(inputs, _, _) => Some((None, inputs.map_bound(|ty| ty.tuple_fields()[i]))),
593        }
594    }
595
596    /// Gets the result type, if one could be found. Note that the result type of a trait may not be
597    /// specified.
598    pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
599        match self {
600            Self::Sig(sig, _) | Self::Closure(_, sig) => Some(sig.output()),
601            Self::Trait(_, output, _) => output,
602        }
603    }
604
605    pub fn predicates_id(&self) -> Option<DefId> {
606        if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self {
607            id
608        } else {
609            None
610        }
611    }
612}
613
614/// If the expression is function like, get the signature for it.
615pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
616    if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = expr.res(cx) {
617        Some(ExprFnSig::Sig(
618            cx.tcx.fn_sig(id).instantiate_identity().skip_norm_wip(),
619            Some(id),
620        ))
621    } else {
622        ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs())
623    }
624}
625
626/// If the type is function like, get the signature for it.
627pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'tcx>> {
628    if let Some(boxed_ty) = ty.boxed_ty() {
629        return ty_sig(cx, boxed_ty);
630    }
631    match *ty.kind() {
632        ty::Closure(id, subs) => {
633            let decl = id
634                .as_local()
635                .and_then(|id| cx.tcx.hir_fn_decl_by_hir_id(cx.tcx.local_def_id_to_hir_id(id)));
636            Some(ExprFnSig::Closure(decl, subs.as_closure().sig()))
637        },
638        ty::FnDef(id, subs) => Some(ExprFnSig::Sig(
639            cx.tcx.fn_sig(id).instantiate(cx.tcx, subs).skip_norm_wip(),
640            Some(id),
641        )),
642        ty::Alias(_, AliasTy {
643            kind: ty::Opaque { def_id },
644            args,
645            ..
646        }) => sig_from_bounds(
647            cx,
648            ty,
649            cx.tcx
650                .item_self_bounds(def_id)
651                .iter_instantiated(cx.tcx, args)
652                .map(Unnormalized::skip_norm_wip),
653            cx.tcx.opt_parent(def_id),
654        ),
655        ty::FnPtr(sig_tys, hdr) => Some(ExprFnSig::Sig(sig_tys.with(hdr), None)),
656        ty::Dynamic(bounds, _) => {
657            let lang_items = cx.tcx.lang_items();
658            match bounds.principal() {
659                Some(bound)
660                    if Some(bound.def_id()) == lang_items.fn_trait()
661                        || Some(bound.def_id()) == lang_items.fn_once_trait()
662                        || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
663                {
664                    let output = bounds
665                        .projection_bounds()
666                        .find(|p| lang_items.fn_once_output().is_some_and(|id| id == p.item_def_id()))
667                        .map(|p| p.map_bound(|p| p.term.expect_type()));
668                    Some(ExprFnSig::Trait(bound.map_bound(|b| b.args.type_at(0)), output, None))
669                },
670                _ => None,
671            }
672        },
673        ty::Alias(_, alias) if let Some(proj) = alias.try_to_projection() => match cx
674            .tcx
675            .try_normalize_erasing_regions(cx.typing_env(), Unnormalized::new_wip(ty))
676        {
677            Ok(normalized_ty) if normalized_ty != ty => ty_sig(cx, normalized_ty),
678            _ => sig_for_projection(cx, proj).or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)),
679        },
680        ty::Param(_) => sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None),
681        _ => None,
682    }
683}
684
685fn sig_from_bounds<'tcx>(
686    cx: &LateContext<'tcx>,
687    ty: Ty<'tcx>,
688    predicates: impl IntoIterator<Item = ty::Clause<'tcx>>,
689    predicates_id: Option<DefId>,
690) -> Option<ExprFnSig<'tcx>> {
691    let mut inputs = None;
692    let mut output = None;
693    let lang_items = cx.tcx.lang_items();
694
695    for pred in predicates {
696        match pred.kind().skip_binder() {
697            ty::ClauseKind::Trait(p)
698                if (lang_items.fn_trait() == Some(p.def_id())
699                    || lang_items.fn_mut_trait() == Some(p.def_id())
700                    || lang_items.fn_once_trait() == Some(p.def_id()))
701                    && p.self_ty() == ty =>
702            {
703                let i = pred.kind().rebind(p.trait_ref.args.type_at(1));
704                if inputs.is_some_and(|inputs| i != inputs) {
705                    // Multiple different fn trait impls. Is this even allowed?
706                    return None;
707                }
708                inputs = Some(i);
709            },
710            ty::ClauseKind::Projection(p)
711                if Some(p.projection_term.expect_projection_def_id()) == lang_items.fn_once_output()
712                    && p.projection_term.self_ty() == ty =>
713            {
714                if output.is_some() {
715                    // Multiple different fn trait impls. Is this even allowed?
716                    return None;
717                }
718                output = Some(pred.kind().rebind(p.term.expect_type()));
719            },
720            _ => (),
721        }
722    }
723
724    inputs.map(|ty| ExprFnSig::Trait(ty, output, predicates_id))
725}
726
727fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: ProjectionAliasTy<'tcx>) -> Option<ExprFnSig<'tcx>> {
728    let mut inputs = None;
729    let mut output = None;
730    let lang_items = cx.tcx.lang_items();
731
732    for (pred, _) in cx
733        .tcx
734        .explicit_item_bounds(ty.kind)
735        .iter_instantiated_copied(cx.tcx, ty.args)
736        .map(Unnormalized::skip_norm_wip)
737    {
738        match pred.kind().skip_binder() {
739            ty::ClauseKind::Trait(p)
740                if (lang_items.fn_trait() == Some(p.def_id())
741                    || lang_items.fn_mut_trait() == Some(p.def_id())
742                    || lang_items.fn_once_trait() == Some(p.def_id())) =>
743            {
744                let i = pred.kind().rebind(p.trait_ref.args.type_at(1));
745
746                if inputs.is_some_and(|inputs| inputs != i) {
747                    // Multiple different fn trait impls. Is this even allowed?
748                    return None;
749                }
750                inputs = Some(i);
751            },
752            ty::ClauseKind::Projection(p)
753                if Some(p.projection_term.expect_projection_def_id()) == lang_items.fn_once_output() =>
754            {
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).skip_norm_wip())))
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).skip_norm_wip()))
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).skip_norm_wip()))
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).skip_norm_wip()))
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        let kind = if let DefKind::Impl { of_trait: false } = tcx.def_kind(tcx.parent(assoc_item.def_id)) {
1052            ty::AliasTyKind::Inherent { def_id: assoc_item.def_id }
1053        } else {
1054            ty::AliasTyKind::Projection { def_id: assoc_item.def_id }
1055        };
1056
1057        Some(AliasTy::new_from_args(tcx, kind, args))
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(typing_env, Unnormalized::new_wip(Ty::new_alias(tcx, ty::IsRigid::No, ty))) {
1097            Ok(ty) => Some(ty),
1098            Err(e) => {
1099                debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1100                None
1101            },
1102        }
1103    }
1104    helper(tcx, typing_env, make_projection(tcx, container_id, assoc_ty, args)?)
1105}
1106
1107/// Helper to check if given type has inner mutability such as [`std::cell::Cell`] or
1108/// [`std::cell::RefCell`].
1109#[derive(Default, Debug)]
1110pub struct InteriorMut<'tcx> {
1111    ignored_def_ids: FxHashSet<DefId>,
1112    ignore_pointers: bool,
1113    tys: FxHashMap<Ty<'tcx>, Option<&'tcx ty::List<Ty<'tcx>>>>,
1114}
1115
1116impl<'tcx> InteriorMut<'tcx> {
1117    pub fn new(tcx: TyCtxt<'tcx>, ignore_interior_mutability: &[String]) -> Self {
1118        let ignored_def_ids = ignore_interior_mutability
1119            .iter()
1120            .flat_map(|ignored_ty| lookup_path_str(tcx, PathNS::Type, ignored_ty))
1121            .collect();
1122
1123        Self {
1124            ignored_def_ids,
1125            ..Self::default()
1126        }
1127    }
1128
1129    pub fn without_pointers(tcx: TyCtxt<'tcx>, ignore_interior_mutability: &[String]) -> Self {
1130        Self {
1131            ignore_pointers: true,
1132            ..Self::new(tcx, ignore_interior_mutability)
1133        }
1134    }
1135
1136    /// Check if given type has interior mutability such as [`std::cell::Cell`] or
1137    /// [`std::cell::RefCell`] etc. and if it does, returns a chain of types that causes
1138    /// this type to be interior mutable.  False negatives may be expected for infinitely recursive
1139    /// types, and `None` will be returned there.
1140    pub fn interior_mut_ty_chain(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<&'tcx ty::List<Ty<'tcx>>> {
1141        self.interior_mut_ty_chain_inner(cx, ty, 0)
1142    }
1143
1144    fn interior_mut_ty_chain_inner(
1145        &mut self,
1146        cx: &LateContext<'tcx>,
1147        ty: Ty<'tcx>,
1148        depth: usize,
1149    ) -> Option<&'tcx ty::List<Ty<'tcx>>> {
1150        if !cx.tcx.recursion_limit().value_within_limit(depth) {
1151            return None;
1152        }
1153
1154        match self.tys.entry(ty) {
1155            Entry::Occupied(o) => return *o.get(),
1156            // Temporarily insert a `None` to break cycles
1157            Entry::Vacant(v) => v.insert(None),
1158        };
1159        let depth = depth + 1;
1160
1161        let chain = match *ty.kind() {
1162            ty::RawPtr(inner_ty, _) if !self.ignore_pointers => self.interior_mut_ty_chain_inner(cx, inner_ty, depth),
1163            ty::Ref(_, inner_ty, _) | ty::Slice(inner_ty) => self.interior_mut_ty_chain_inner(cx, inner_ty, depth),
1164            ty::Array(inner_ty, size) if size.try_to_target_usize(cx.tcx) != Some(0) => {
1165                self.interior_mut_ty_chain_inner(cx, inner_ty, depth)
1166            },
1167            ty::Tuple(fields) => fields
1168                .iter()
1169                .find_map(|ty| self.interior_mut_ty_chain_inner(cx, ty, depth)),
1170            ty::Adt(def, _) if def.is_unsafe_cell() => Some(ty::List::empty()),
1171            ty::Adt(def, args) => {
1172                let is_std_collection = matches!(
1173                    cx.tcx.get_diagnostic_name(def.did()),
1174                    Some(
1175                        sym::LinkedList
1176                            | sym::Vec
1177                            | sym::VecDeque
1178                            | sym::BTreeMap
1179                            | sym::BTreeSet
1180                            | sym::HashMap
1181                            | sym::HashSet
1182                            | sym::Arc
1183                            | sym::Rc
1184                    )
1185                );
1186
1187                if is_std_collection || def.is_box() {
1188                    // Include the types from std collections that are behind pointers internally
1189                    args.types()
1190                        .find_map(|ty| self.interior_mut_ty_chain_inner(cx, ty, depth))
1191                } else if self.ignored_def_ids.contains(&def.did()) || def.is_phantom_data() {
1192                    None
1193                } else {
1194                    def.all_fields()
1195                        .find_map(|f| self.interior_mut_ty_chain_inner(cx, f.ty(cx.tcx, args).skip_norm_wip(), depth))
1196                }
1197            },
1198            ty::Alias(_, AliasTy {
1199                kind: ty::Projection { .. },
1200                ..
1201            }) => match cx
1202                .tcx
1203                .try_normalize_erasing_regions(cx.typing_env(), Unnormalized::new_wip(ty))
1204            {
1205                Ok(normalized_ty) if ty != normalized_ty => self.interior_mut_ty_chain_inner(cx, normalized_ty, depth),
1206                _ => None,
1207            },
1208            _ => None,
1209        };
1210
1211        chain.map(|chain| {
1212            let list = cx.tcx.mk_type_list_from_iter(chain.iter().chain([ty]));
1213            self.tys.insert(ty, Some(list));
1214            list
1215        })
1216    }
1217
1218    /// Check if given type has interior mutability such as [`std::cell::Cell`] or
1219    /// [`std::cell::RefCell`] etc.
1220    pub fn is_interior_mut_ty(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1221        self.interior_mut_ty_chain(cx, ty).is_some()
1222    }
1223}
1224
1225pub fn make_normalized_projection_with_regions<'tcx>(
1226    tcx: TyCtxt<'tcx>,
1227    typing_env: ty::TypingEnv<'tcx>,
1228    container_id: DefId,
1229    assoc_ty: Symbol,
1230    args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1231) -> Option<Ty<'tcx>> {
1232    fn helper<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1233        #[cfg(debug_assertions)]
1234        if let Some((i, arg)) = ty
1235            .args
1236            .iter()
1237            .enumerate()
1238            .find(|(_, arg)| arg.has_escaping_bound_vars())
1239        {
1240            debug_assert!(
1241                false,
1242                "args contain late-bound region at index `{i}` which can't be normalized.\n\
1243                    use `TyCtxt::instantiate_bound_regions_with_erased`\n\
1244                    note: arg is `{arg:#?}`",
1245            );
1246            return None;
1247        }
1248        let cause = ObligationCause::dummy();
1249        let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
1250        match infcx.at(&cause, param_env).query_normalize(Ty::new_alias(tcx, ty::IsRigid::No, ty)) {
1251            Ok(ty) => Some(ty.value),
1252            Err(e) => {
1253                debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1254                None
1255            },
1256        }
1257    }
1258    helper(tcx, typing_env, make_projection(tcx, container_id, assoc_ty, args)?)
1259}
1260
1261pub fn normalize_with_regions<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1262    let cause = ObligationCause::dummy();
1263    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
1264    infcx
1265        .at(&cause, param_env)
1266        .query_normalize(ty)
1267        .map_or(ty, |ty| ty.value)
1268}
1269
1270/// Checks if the type is `core::mem::ManuallyDrop<_>`
1271pub fn is_manually_drop(ty: Ty<'_>) -> bool {
1272    ty.ty_adt_def().is_some_and(AdtDef::is_manually_drop)
1273}
1274
1275/// Returns the deref chain of a type, starting with the type itself.
1276pub fn deref_chain<'cx, 'tcx>(cx: &'cx LateContext<'tcx>, ty: Ty<'tcx>) -> impl Iterator<Item = Ty<'tcx>> + 'cx {
1277    iter::successors(Some(ty), |&ty| {
1278        if let Some(deref_did) = cx.tcx.lang_items().deref_trait()
1279            && implements_trait(cx, ty, deref_did, &[])
1280        {
1281            make_normalized_projection(cx.tcx, cx.typing_env(), deref_did, sym::Target, [ty])
1282        } else {
1283            None
1284        }
1285    })
1286}
1287
1288/// Checks if a Ty<'_> has some inherent method Symbol.
1289///
1290/// This does not look for impls in the type's `Deref::Target` type.
1291/// If you need this, you should wrap this call in `clippy_utils::ty::deref_chain().any(...)`.
1292pub fn get_adt_inherent_method<'a>(cx: &'a LateContext<'_>, ty: Ty<'_>, method_name: Symbol) -> Option<&'a AssocItem> {
1293    let ty_did = ty.ty_adt_def().map(AdtDef::did)?;
1294    cx.tcx.inherent_impls(ty_did).iter().find_map(|&did| {
1295        cx.tcx
1296            .associated_items(did)
1297            .filter_by_name_unhygienic(method_name)
1298            .next()
1299            .filter(|item| item.tag() == AssocTag::Fn)
1300    })
1301}
1302
1303/// Gets the type of a field by name.
1304pub fn get_field_by_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
1305    match *ty.kind() {
1306        ty::Adt(def, args) if def.is_union() || def.is_struct() => def
1307            .non_enum_variant()
1308            .fields
1309            .iter()
1310            .find(|f| f.name == name)
1311            .map(|f| f.ty(tcx, args).skip_norm_wip()),
1312        ty::Tuple(args) => name.as_str().parse::<usize>().ok().and_then(|i| args.get(i).copied()),
1313        _ => None,
1314    }
1315}
1316
1317pub fn get_field_def_id_by_name(ty: Ty<'_>, name: Symbol) -> Option<DefId> {
1318    let ty::Adt(adt_def, ..) = ty.kind() else { return None };
1319    adt_def
1320        .all_fields()
1321        .find_map(|field| if field.name == name { Some(field.did) } else { None })
1322}
1323
1324/// Check if `ty` is an `Option` and return its argument type if it is.
1325pub fn option_arg_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1326    match *ty.kind() {
1327        ty::Adt(adt, args)
1328            if let [arg] = &**args
1329                && let Some(arg) = arg.as_type()
1330                && adt.is_diag_item(cx, sym::Option) =>
1331        {
1332            Some(arg)
1333        },
1334        _ => None,
1335    }
1336}
1337
1338/// Check if a Ty<'_> of `Iterator` contains any mutable access to non-owning types by checking if
1339/// it contains fields of mutable references or pointers, or references/pointers to non-`Freeze`
1340/// types, or `PhantomData` types containing any of the previous. This can be used to check whether
1341/// skipping iterating over an iterator will change its behavior.
1342pub fn has_non_owning_mutable_access<'tcx>(cx: &LateContext<'tcx>, iter_ty: Ty<'tcx>) -> bool {
1343    fn normalize_ty<'tcx>(cx: &LateContext<'tcx>, ty: Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
1344        cx.tcx
1345            .try_normalize_erasing_regions(cx.typing_env(), ty)
1346            .unwrap_or(ty.skip_norm_wip())
1347    }
1348
1349    /// Check if `ty` contains mutable references or equivalent, which includes:
1350    /// - A mutable reference/pointer.
1351    /// - A reference/pointer to a non-`Freeze` type.
1352    /// - A `PhantomData` type containing any of the previous.
1353    fn has_non_owning_mutable_access_inner<'tcx>(
1354        cx: &LateContext<'tcx>,
1355        phantoms: &mut FxHashSet<Ty<'tcx>>,
1356        ty: Ty<'tcx>,
1357    ) -> bool {
1358        match ty.kind() {
1359            ty::Adt(adt_def, args) if adt_def.is_phantom_data() => {
1360                phantoms.insert(ty)
1361                    && args
1362                        .types()
1363                        .any(|arg_ty| has_non_owning_mutable_access_inner(cx, phantoms, arg_ty))
1364            },
1365            ty::Adt(adt_def, args) => adt_def.all_fields().any(|field| {
1366                has_non_owning_mutable_access_inner(cx, phantoms, normalize_ty(cx, field.ty(cx.tcx, args)))
1367            }),
1368            ty::Array(elem_ty, _) | ty::Slice(elem_ty) => has_non_owning_mutable_access_inner(cx, phantoms, *elem_ty),
1369            ty::RawPtr(pointee_ty, mutability) | ty::Ref(_, pointee_ty, mutability) => {
1370                mutability.is_mut() || !pointee_ty.is_freeze(cx.tcx, cx.typing_env())
1371            },
1372            ty::Closure(_, closure_args) => {
1373                matches!(closure_args.types().next_back(),
1374                         Some(captures) if has_non_owning_mutable_access_inner(cx, phantoms, captures))
1375            },
1376            ty::Tuple(tuple_args) => tuple_args
1377                .iter()
1378                .any(|arg_ty| has_non_owning_mutable_access_inner(cx, phantoms, arg_ty)),
1379            _ => false,
1380        }
1381    }
1382
1383    let mut phantoms = FxHashSet::default();
1384    has_non_owning_mutable_access_inner(cx, &mut phantoms, iter_ty)
1385}
1386
1387/// Check if `ty` is slice-like, i.e., `&[T]`, `[T; N]`, or `Vec<T>`.
1388pub fn is_slice_like<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1389    ty.is_slice() || ty.is_array() || ty.is_diag_item(cx, sym::Vec)
1390}
1391
1392pub fn get_field_idx_by_name(ty: Ty<'_>, name: Symbol) -> Option<usize> {
1393    match *ty.kind() {
1394        ty::Adt(def, _) if def.is_union() || def.is_struct() => {
1395            def.non_enum_variant().fields.iter().position(|f| f.name == name)
1396        },
1397        ty::Tuple(_) => name.as_str().parse::<usize>().ok(),
1398        _ => None,
1399    }
1400}
1401
1402/// Checks if the adjustments contain a mutable dereference of a `ManuallyDrop<_>`.
1403pub fn adjust_derefs_manually_drop<'tcx>(adjustments: &'tcx [Adjustment<'tcx>], mut ty: Ty<'tcx>) -> bool {
1404    adjustments.iter().any(|a| {
1405        let ty = mem::replace(&mut ty, a.target);
1406        matches!(a.kind, Adjust::Deref(DerefAdjustKind::Overloaded(op)) if op.mutbl == Mutability::Mut)
1407            && is_manually_drop(ty)
1408    })
1409}