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