]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/ty.rs
Rollup merge of #106767 - chbaker0:disable-unstable-features, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_utils / src / ty.rs
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, AdtDef, AliasTy, AssocKind, Binder, BoundRegion, DefIdTree, FnSig, IntTy, List, ParamEnv, Predicate,
20     PredicateKind, Region, RegionKind, SubstsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy,
21     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.
34 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.
39 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.
46 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.
59 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`.
71 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) {
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 substituions to find `U`.
97                             ty::PredicateKind::Clause(ty::Clause::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::PredicateKind::Clause(ty::Clause::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`
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
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
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
205 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.
221 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.needs_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(
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`.
251 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
259 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) {
271                 if let ty::PredicateKind::Clause(ty::Clause::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.iter() {
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`.
298 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
302 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`
340 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).
346 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.kind() == ty::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
357 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
378 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.
388 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`.
396 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`
404 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.
414 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.
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.
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.
489 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.
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.
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`
518 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.
541 pub fn is_uninit_value_valid_for_ty(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
542     match *ty.kind() {
543         ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
544         ty::Tuple(types) => types.iter().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
545         ty::Adt(adt, _) => cx.tcx.lang_items().maybe_uninit() == Some(adt.did()),
546         _ => false,
547     }
548 }
549
550 /// Gets an iterator over all predicates which apply to the given item.
551 pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(Predicate<'_>, Span)> {
552     let mut next_id = Some(id);
553     iter::from_fn(move || {
554         next_id.take().map(|id| {
555             let preds = tcx.predicates_of(id);
556             next_id = preds.parent;
557             preds.predicates.iter()
558         })
559     })
560     .flatten()
561 }
562
563 /// A signature for a function like type.
564 #[derive(Clone, Copy)]
565 pub enum ExprFnSig<'tcx> {
566     Sig(Binder<'tcx, FnSig<'tcx>>, Option<DefId>),
567     Closure(Option<&'tcx FnDecl<'tcx>>, Binder<'tcx, FnSig<'tcx>>),
568     Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>, Option<DefId>),
569 }
570 impl<'tcx> ExprFnSig<'tcx> {
571     /// Gets the argument type at the given offset. This will return `None` when the index is out of
572     /// bounds only for variadic functions, otherwise this will panic.
573     pub fn input(self, i: usize) -> Option<Binder<'tcx, Ty<'tcx>>> {
574         match self {
575             Self::Sig(sig, _) => {
576                 if sig.c_variadic() {
577                     sig.inputs().map_bound(|inputs| inputs.get(i).copied()).transpose()
578                 } else {
579                     Some(sig.input(i))
580                 }
581             },
582             Self::Closure(_, sig) => Some(sig.input(0).map_bound(|ty| ty.tuple_fields()[i])),
583             Self::Trait(inputs, _, _) => Some(inputs.map_bound(|ty| ty.tuple_fields()[i])),
584         }
585     }
586
587     /// Gets the argument type at the given offset. For closures this will also get the type as
588     /// written. This will return `None` when the index is out of bounds only for variadic
589     /// functions, otherwise this will panic.
590     pub fn input_with_hir(self, i: usize) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> {
591         match self {
592             Self::Sig(sig, _) => {
593                 if sig.c_variadic() {
594                     sig.inputs()
595                         .map_bound(|inputs| inputs.get(i).copied())
596                         .transpose()
597                         .map(|arg| (None, arg))
598                 } else {
599                     Some((None, sig.input(i)))
600                 }
601             },
602             Self::Closure(decl, sig) => Some((
603                 decl.and_then(|decl| decl.inputs.get(i)),
604                 sig.input(0).map_bound(|ty| ty.tuple_fields()[i]),
605             )),
606             Self::Trait(inputs, _, _) => Some((None, inputs.map_bound(|ty| ty.tuple_fields()[i]))),
607         }
608     }
609
610     /// Gets the result type, if one could be found. Note that the result type of a trait may not be
611     /// specified.
612     pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
613         match self {
614             Self::Sig(sig, _) | Self::Closure(_, sig) => Some(sig.output()),
615             Self::Trait(_, output, _) => output,
616         }
617     }
618
619     pub fn predicates_id(&self) -> Option<DefId> {
620         if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self {
621             id
622         } else {
623             None
624         }
625     }
626 }
627
628 /// If the expression is function like, get the signature for it.
629 pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
630     if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) {
631         Some(ExprFnSig::Sig(cx.tcx.fn_sig(id), Some(id)))
632     } else {
633         ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs())
634     }
635 }
636
637 /// If the type is function like, get the signature for it.
638 pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'tcx>> {
639     if ty.is_box() {
640         return ty_sig(cx, ty.boxed_ty());
641     }
642     match *ty.kind() {
643         ty::Closure(id, subs) => {
644             let decl = id
645                 .as_local()
646                 .and_then(|id| cx.tcx.hir().fn_decl_by_hir_id(cx.tcx.hir().local_def_id_to_hir_id(id)));
647             Some(ExprFnSig::Closure(decl, subs.as_closure().sig()))
648         },
649         ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.bound_fn_sig(id).subst(cx.tcx, subs), Some(id))),
650         ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
651             sig_from_bounds(cx, ty, cx.tcx.item_bounds(def_id).subst(cx.tcx, substs), cx.tcx.opt_parent(def_id))
652         },
653         ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig, None)),
654         ty::Dynamic(bounds, _, _) => {
655             let lang_items = cx.tcx.lang_items();
656             match bounds.principal() {
657                 Some(bound)
658                     if Some(bound.def_id()) == lang_items.fn_trait()
659                         || Some(bound.def_id()) == lang_items.fn_once_trait()
660                         || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
661                 {
662                     let output = bounds
663                         .projection_bounds()
664                         .find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id()))
665                         .map(|p| p.map_bound(|p| p.term.ty().unwrap()));
666                     Some(ExprFnSig::Trait(bound.map_bound(|b| b.substs.type_at(0)), output, None))
667                 },
668                 _ => None,
669             }
670         },
671         ty::Alias(ty::Projection, proj) => match cx.tcx.try_normalize_erasing_regions(cx.param_env, ty) {
672             Ok(normalized_ty) if normalized_ty != ty => ty_sig(cx, normalized_ty),
673             _ => sig_for_projection(cx, proj).or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)),
674         },
675         ty::Param(_) => sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None),
676         _ => None,
677     }
678 }
679
680 fn sig_from_bounds<'tcx>(
681     cx: &LateContext<'tcx>,
682     ty: Ty<'tcx>,
683     predicates: &'tcx [Predicate<'tcx>],
684     predicates_id: Option<DefId>,
685 ) -> Option<ExprFnSig<'tcx>> {
686     let mut inputs = None;
687     let mut output = None;
688     let lang_items = cx.tcx.lang_items();
689
690     for pred in predicates {
691         match pred.kind().skip_binder() {
692             PredicateKind::Clause(ty::Clause::Trait(p))
693                 if (lang_items.fn_trait() == Some(p.def_id())
694                     || lang_items.fn_mut_trait() == Some(p.def_id())
695                     || lang_items.fn_once_trait() == Some(p.def_id()))
696                     && p.self_ty() == ty =>
697             {
698                 let i = pred.kind().rebind(p.trait_ref.substs.type_at(1));
699                 if inputs.map_or(false, |inputs| i != inputs) {
700                     // Multiple different fn trait impls. Is this even allowed?
701                     return None;
702                 }
703                 inputs = Some(i);
704             },
705             PredicateKind::Clause(ty::Clause::Projection(p))
706                 if Some(p.projection_ty.def_id) == lang_items.fn_once_output() && p.projection_ty.self_ty() == ty =>
707             {
708                 if output.is_some() {
709                     // Multiple different fn trait impls. Is this even allowed?
710                     return None;
711                 }
712                 output = Some(pred.kind().rebind(p.term.ty().unwrap()));
713             },
714             _ => (),
715         }
716     }
717
718     inputs.map(|ty| ExprFnSig::Trait(ty, output, predicates_id))
719 }
720
721 fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: AliasTy<'tcx>) -> Option<ExprFnSig<'tcx>> {
722     let mut inputs = None;
723     let mut output = None;
724     let lang_items = cx.tcx.lang_items();
725
726     for (pred, _) in cx
727         .tcx
728         .bound_explicit_item_bounds(ty.def_id)
729         .subst_iter_copied(cx.tcx, ty.substs)
730     {
731         match pred.kind().skip_binder() {
732             PredicateKind::Clause(ty::Clause::Trait(p))
733                 if (lang_items.fn_trait() == Some(p.def_id())
734                     || lang_items.fn_mut_trait() == Some(p.def_id())
735                     || lang_items.fn_once_trait() == Some(p.def_id())) =>
736             {
737                 let i = pred.kind().rebind(p.trait_ref.substs.type_at(1));
738
739                 if inputs.map_or(false, |inputs| inputs != i) {
740                     // Multiple different fn trait impls. Is this even allowed?
741                     return None;
742                 }
743                 inputs = Some(i);
744             },
745             PredicateKind::Clause(ty::Clause::Projection(p))
746                 if Some(p.projection_ty.def_id) == lang_items.fn_once_output() =>
747             {
748                 if output.is_some() {
749                     // Multiple different fn trait impls. Is this even allowed?
750                     return None;
751                 }
752                 output = pred.kind().rebind(p.term.ty()).transpose();
753             },
754             _ => (),
755         }
756     }
757
758     inputs.map(|ty| ExprFnSig::Trait(ty, output, None))
759 }
760
761 #[derive(Clone, Copy)]
762 pub enum EnumValue {
763     Unsigned(u128),
764     Signed(i128),
765 }
766 impl core::ops::Add<u32> for EnumValue {
767     type Output = Self;
768     fn add(self, n: u32) -> Self::Output {
769         match self {
770             Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
771             Self::Signed(x) => Self::Signed(x + i128::from(n)),
772         }
773     }
774 }
775
776 /// Attempts to read the given constant as though it were an enum value.
777 #[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
778 pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
779     if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
780         match tcx.type_of(id).kind() {
781             ty::Int(_) => Some(EnumValue::Signed(match value.size().bytes() {
782                 1 => i128::from(value.assert_bits(Size::from_bytes(1)) as u8 as i8),
783                 2 => i128::from(value.assert_bits(Size::from_bytes(2)) as u16 as i16),
784                 4 => i128::from(value.assert_bits(Size::from_bytes(4)) as u32 as i32),
785                 8 => i128::from(value.assert_bits(Size::from_bytes(8)) as u64 as i64),
786                 16 => value.assert_bits(Size::from_bytes(16)) as i128,
787                 _ => return None,
788             })),
789             ty::Uint(_) => Some(EnumValue::Unsigned(match value.size().bytes() {
790                 1 => value.assert_bits(Size::from_bytes(1)),
791                 2 => value.assert_bits(Size::from_bytes(2)),
792                 4 => value.assert_bits(Size::from_bytes(4)),
793                 8 => value.assert_bits(Size::from_bytes(8)),
794                 16 => value.assert_bits(Size::from_bytes(16)),
795                 _ => return None,
796             })),
797             _ => None,
798         }
799     } else {
800         None
801     }
802 }
803
804 /// Gets the value of the given variant.
805 pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: AdtDef<'_>, i: VariantIdx) -> EnumValue {
806     let variant = &adt.variant(i);
807     match variant.discr {
808         VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
809         VariantDiscr::Relative(x) => match adt.variant((i.as_usize() - x as usize).into()).discr {
810             VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
811             VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
812         },
813     }
814 }
815
816 /// Check if the given type is either `core::ffi::c_void`, `std::os::raw::c_void`, or one of the
817 /// platform specific `libc::<platform>::c_void` types in libc.
818 pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
819     if let ty::Adt(adt, _) = ty.kind()
820         && let &[krate, .., name] = &*cx.get_def_path(adt.did())
821         && let sym::libc | sym::core | sym::std = krate
822         && name.as_str() == "c_void"
823     {
824         true
825     } else {
826         false
827     }
828 }
829
830 pub fn for_each_top_level_late_bound_region<B>(
831     ty: Ty<'_>,
832     f: impl FnMut(BoundRegion) -> ControlFlow<B>,
833 ) -> ControlFlow<B> {
834     struct V<F> {
835         index: u32,
836         f: F,
837     }
838     impl<'tcx, B, F: FnMut(BoundRegion) -> ControlFlow<B>> TypeVisitor<'tcx> for V<F> {
839         type BreakTy = B;
840         fn visit_region(&mut self, r: Region<'tcx>) -> ControlFlow<Self::BreakTy> {
841             if let RegionKind::ReLateBound(idx, bound) = r.kind() && idx.as_u32() == self.index {
842                 (self.f)(bound)
843             } else {
844                 ControlFlow::Continue(())
845             }
846         }
847         fn visit_binder<T: TypeVisitable<'tcx>>(&mut self, t: &Binder<'tcx, T>) -> ControlFlow<Self::BreakTy> {
848             self.index += 1;
849             let res = t.super_visit_with(self);
850             self.index -= 1;
851             res
852         }
853     }
854     ty.visit_with(&mut V { index: 0, f })
855 }
856
857 pub struct AdtVariantInfo {
858     pub ind: usize,
859     pub size: u64,
860
861     /// (ind, size)
862     pub fields_size: Vec<(usize, u64)>,
863 }
864
865 impl AdtVariantInfo {
866     /// Returns ADT variants ordered by size
867     pub fn new<'tcx>(cx: &LateContext<'tcx>, adt: AdtDef<'tcx>, subst: &'tcx List<GenericArg<'tcx>>) -> Vec<Self> {
868         let mut variants_size = adt
869             .variants()
870             .iter()
871             .enumerate()
872             .map(|(i, variant)| {
873                 let mut fields_size = variant
874                     .fields
875                     .iter()
876                     .enumerate()
877                     .map(|(i, f)| (i, approx_ty_size(cx, f.ty(cx.tcx, subst))))
878                     .collect::<Vec<_>>();
879                 fields_size.sort_by(|(_, a_size), (_, b_size)| (a_size.cmp(b_size)));
880
881                 Self {
882                     ind: i,
883                     size: fields_size.iter().map(|(_, size)| size).sum(),
884                     fields_size,
885                 }
886             })
887             .collect::<Vec<_>>();
888         variants_size.sort_by(|a, b| (b.size.cmp(&a.size)));
889         variants_size
890     }
891 }
892
893 /// Gets the struct or enum variant from the given `Res`
894 pub fn variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option<&'tcx VariantDef> {
895     match res {
896         Res::Def(DefKind::Struct, id) => Some(cx.tcx.adt_def(id).non_enum_variant()),
897         Res::Def(DefKind::Variant, id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).variant_with_id(id)),
898         Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => Some(cx.tcx.adt_def(cx.tcx.parent(id)).non_enum_variant()),
899         Res::Def(DefKind::Ctor(CtorOf::Variant, _), id) => {
900             let var_id = cx.tcx.parent(id);
901             Some(cx.tcx.adt_def(cx.tcx.parent(var_id)).variant_with_id(var_id))
902         },
903         Res::SelfCtor(id) => Some(cx.tcx.type_of(id).ty_adt_def().unwrap().non_enum_variant()),
904         _ => None,
905     }
906 }
907
908 /// Checks if the type is a type parameter implementing `FnOnce`, but not `FnMut`.
909 pub fn ty_is_fn_once_param<'tcx>(tcx: TyCtxt<'_>, ty: Ty<'tcx>, predicates: &'tcx [Predicate<'_>]) -> bool {
910     let ty::Param(ty) = *ty.kind() else {
911         return false;
912     };
913     let lang = tcx.lang_items();
914     let (Some(fn_once_id), Some(fn_mut_id), Some(fn_id))
915         = (lang.fn_once_trait(), lang.fn_mut_trait(), lang.fn_trait())
916     else {
917         return false;
918     };
919     predicates
920         .iter()
921         .try_fold(false, |found, p| {
922             if let PredicateKind::Clause(ty::Clause::Trait(p)) = p.kind().skip_binder()
923             && let ty::Param(self_ty) = p.trait_ref.self_ty().kind()
924             && ty.index == self_ty.index
925         {
926             // This should use `super_traits_of`, but that's a private function.
927             if p.trait_ref.def_id == fn_once_id {
928                 return Some(true);
929             } else if p.trait_ref.def_id == fn_mut_id || p.trait_ref.def_id == fn_id {
930                 return None;
931             }
932         }
933             Some(found)
934         })
935         .unwrap_or(false)
936 }
937
938 /// Comes up with an "at least" guesstimate for the type's size, not taking into
939 /// account the layout of type parameters.
940 pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 {
941     use rustc_middle::ty::layout::LayoutOf;
942     if !is_normalizable(cx, cx.param_env, ty) {
943         return 0;
944     }
945     match (cx.layout_of(ty).map(|layout| layout.size.bytes()), ty.kind()) {
946         (Ok(size), _) => size,
947         (Err(_), ty::Tuple(list)) => list.as_substs().types().map(|t| approx_ty_size(cx, t)).sum(),
948         (Err(_), ty::Array(t, n)) => {
949             n.try_eval_usize(cx.tcx, cx.param_env).unwrap_or_default() * approx_ty_size(cx, *t)
950         },
951         (Err(_), ty::Adt(def, subst)) if def.is_struct() => def
952             .variants()
953             .iter()
954             .map(|v| {
955                 v.fields
956                     .iter()
957                     .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
958                     .sum::<u64>()
959             })
960             .sum(),
961         (Err(_), ty::Adt(def, subst)) if def.is_enum() => def
962             .variants()
963             .iter()
964             .map(|v| {
965                 v.fields
966                     .iter()
967                     .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
968                     .sum::<u64>()
969             })
970             .max()
971             .unwrap_or_default(),
972         (Err(_), ty::Adt(def, subst)) if def.is_union() => def
973             .variants()
974             .iter()
975             .map(|v| {
976                 v.fields
977                     .iter()
978                     .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
979                     .max()
980                     .unwrap_or_default()
981             })
982             .max()
983             .unwrap_or_default(),
984         (Err(_), _) => 0,
985     }
986 }
987
988 /// Makes the projection type for the named associated type in the given impl or trait impl.
989 ///
990 /// This function is for associated types which are "known" to exist, and as such, will only return
991 /// `None` when debug assertions are disabled in order to prevent ICE's. With debug assertions
992 /// enabled this will check that the named associated type exists, the correct number of
993 /// substitutions are given, and that the correct kinds of substitutions are given (lifetime,
994 /// constant or type). This will not check if type normalization would succeed.
995 pub fn make_projection<'tcx>(
996     tcx: TyCtxt<'tcx>,
997     container_id: DefId,
998     assoc_ty: Symbol,
999     substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1000 ) -> Option<AliasTy<'tcx>> {
1001     fn helper<'tcx>(
1002         tcx: TyCtxt<'tcx>,
1003         container_id: DefId,
1004         assoc_ty: Symbol,
1005         substs: SubstsRef<'tcx>,
1006     ) -> Option<AliasTy<'tcx>> {
1007         let Some(assoc_item) = tcx
1008             .associated_items(container_id)
1009             .find_by_name_and_kind(tcx, Ident::with_dummy_span(assoc_ty), AssocKind::Type, container_id)
1010         else {
1011             debug_assert!(false, "type `{assoc_ty}` not found in `{container_id:?}`");
1012             return None;
1013         };
1014         #[cfg(debug_assertions)]
1015         {
1016             let generics = tcx.generics_of(assoc_item.def_id);
1017             let generic_count = generics.parent_count + generics.params.len();
1018             let params = generics
1019                 .parent
1020                 .map_or([].as_slice(), |id| &*tcx.generics_of(id).params)
1021                 .iter()
1022                 .chain(&generics.params)
1023                 .map(|x| &x.kind);
1024
1025             debug_assert!(
1026                 generic_count == substs.len(),
1027                 "wrong number of substs for `{:?}`: found `{}` expected `{generic_count}`.\n\
1028                     note: the expected parameters are: {:#?}\n\
1029                     the given arguments are: `{substs:#?}`",
1030                 assoc_item.def_id,
1031                 substs.len(),
1032                 params.map(ty::GenericParamDefKind::descr).collect::<Vec<_>>(),
1033             );
1034
1035             if let Some((idx, (param, arg))) = params
1036                 .clone()
1037                 .zip(substs.iter().map(GenericArg::unpack))
1038                 .enumerate()
1039                 .find(|(_, (param, arg))| {
1040                     !matches!(
1041                         (param, arg),
1042                         (ty::GenericParamDefKind::Lifetime, GenericArgKind::Lifetime(_))
1043                             | (ty::GenericParamDefKind::Type { .. }, GenericArgKind::Type(_))
1044                             | (ty::GenericParamDefKind::Const { .. }, GenericArgKind::Const(_))
1045                     )
1046                 })
1047             {
1048                 debug_assert!(
1049                     false,
1050                     "mismatched subst type at index {idx}: expected a {}, found `{arg:?}`\n\
1051                         note: the expected parameters are {:#?}\n\
1052                         the given arguments are {substs:#?}",
1053                     param.descr(),
1054                     params.map(ty::GenericParamDefKind::descr).collect::<Vec<_>>()
1055                 );
1056             }
1057         }
1058
1059         Some(tcx.mk_alias_ty(assoc_item.def_id, substs))
1060     }
1061     helper(
1062         tcx,
1063         container_id,
1064         assoc_ty,
1065         tcx.mk_substs(substs.into_iter().map(Into::into)),
1066     )
1067 }
1068
1069 /// Normalizes the named associated type in the given impl or trait impl.
1070 ///
1071 /// This function is for associated types which are "known" to be valid with the given
1072 /// substitutions, and as such, will only return `None` when debug assertions are disabled in order
1073 /// to prevent ICE's. With debug assertions enabled this will check that that type normalization
1074 /// succeeds as well as everything checked by `make_projection`.
1075 pub fn make_normalized_projection<'tcx>(
1076     tcx: TyCtxt<'tcx>,
1077     param_env: ParamEnv<'tcx>,
1078     container_id: DefId,
1079     assoc_ty: Symbol,
1080     substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1081 ) -> Option<Ty<'tcx>> {
1082     fn helper<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1083         #[cfg(debug_assertions)]
1084         if let Some((i, subst)) = ty
1085             .substs
1086             .iter()
1087             .enumerate()
1088             .find(|(_, subst)| subst.has_late_bound_regions())
1089         {
1090             debug_assert!(
1091                 false,
1092                 "substs contain late-bound region at index `{i}` which can't be normalized.\n\
1093                     use `TyCtxt::erase_late_bound_regions`\n\
1094                     note: subst is `{subst:#?}`",
1095             );
1096             return None;
1097         }
1098         match tcx.try_normalize_erasing_regions(param_env, tcx.mk_projection(ty.def_id, ty.substs)) {
1099             Ok(ty) => Some(ty),
1100             Err(e) => {
1101                 debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1102                 None
1103             },
1104         }
1105     }
1106     helper(tcx, param_env, make_projection(tcx, container_id, assoc_ty, substs)?)
1107 }