Thanks to visit codestin.com
Credit goes to doc.rust-lang.org

clippy_utils/ty/
mod.rs

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