]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_utils/src/ty.rs
New upstream version 1.70.0+dfsg1
[rustc.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, layout::ValidityRequirement, AdtDef, AliasTy, AssocKind, Binder, BoundRegion, FnSig, IntTy, List, ParamEnv,
20 Predicate, PredicateKind, Region, RegionKind, SubstsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
21 TypeVisitableExt, TypeVisitor, 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.
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_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`.
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.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
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<'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`.
548 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.
566 pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(Predicate<'_>, 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.
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.
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.
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
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.
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.
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(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
698 fn sig_from_bounds<'tcx>(
699 cx: &LateContext<'tcx>,
700 ty: Ty<'tcx>,
701 predicates: &'tcx [Predicate<'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 PredicateKind::Clause(ty::Clause::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 PredicateKind::Clause(ty::Clause::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
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 .bound_explicit_item_bounds(ty.def_id)
747 .subst_iter_copied(cx.tcx, ty.substs)
748 {
749 match pred.kind().skip_binder() {
750 PredicateKind::Clause(ty::Clause::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 PredicateKind::Clause(ty::Clause::Projection(p))
764 if Some(p.projection_ty.def_id) == lang_items.fn_once_output() =>
765 {
766 if output.is_some() {
767 // Multiple different fn trait impls. Is this even allowed?
768 return None;
769 }
770 output = pred.kind().rebind(p.term.ty()).transpose();
771 },
772 _ => (),
773 }
774 }
775
776 inputs.map(|ty| ExprFnSig::Trait(ty, output, None))
777 }
778
779 #[derive(Clone, Copy)]
780 pub enum EnumValue {
781 Unsigned(u128),
782 Signed(i128),
783 }
784 impl core::ops::Add<u32> for EnumValue {
785 type Output = Self;
786 fn add(self, n: u32) -> Self::Output {
787 match self {
788 Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
789 Self::Signed(x) => Self::Signed(x + i128::from(n)),
790 }
791 }
792 }
793
794 /// Attempts to read the given constant as though it were an enum value.
795 #[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
796 pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
797 if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
798 match tcx.type_of(id).subst_identity().kind() {
799 ty::Int(_) => Some(EnumValue::Signed(match value.size().bytes() {
800 1 => i128::from(value.assert_bits(Size::from_bytes(1)) as u8 as i8),
801 2 => i128::from(value.assert_bits(Size::from_bytes(2)) as u16 as i16),
802 4 => i128::from(value.assert_bits(Size::from_bytes(4)) as u32 as i32),
803 8 => i128::from(value.assert_bits(Size::from_bytes(8)) as u64 as i64),
804 16 => value.assert_bits(Size::from_bytes(16)) as i128,
805 _ => return None,
806 })),
807 ty::Uint(_) => Some(EnumValue::Unsigned(match value.size().bytes() {
808 1 => value.assert_bits(Size::from_bytes(1)),
809 2 => value.assert_bits(Size::from_bytes(2)),
810 4 => value.assert_bits(Size::from_bytes(4)),
811 8 => value.assert_bits(Size::from_bytes(8)),
812 16 => value.assert_bits(Size::from_bytes(16)),
813 _ => return None,
814 })),
815 _ => None,
816 }
817 } else {
818 None
819 }
820 }
821
822 /// Gets the value of the given variant.
823 pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: AdtDef<'_>, i: VariantIdx) -> EnumValue {
824 let variant = &adt.variant(i);
825 match variant.discr {
826 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
827 VariantDiscr::Relative(x) => match adt.variant((i.as_usize() - x as usize).into()).discr {
828 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
829 VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
830 },
831 }
832 }
833
834 /// Check if the given type is either `core::ffi::c_void`, `std::os::raw::c_void`, or one of the
835 /// platform specific `libc::<platform>::c_void` types in libc.
836 pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
837 if let ty::Adt(adt, _) = ty.kind()
838 && let &[krate, .., name] = &*cx.get_def_path(adt.did())
839 && let sym::libc | sym::core | sym::std = krate
840 && name.as_str() == "c_void"
841 {
842 true
843 } else {
844 false
845 }
846 }
847
848 pub fn for_each_top_level_late_bound_region<B>(
849 ty: Ty<'_>,
850 f: impl FnMut(BoundRegion) -> ControlFlow<B>,
851 ) -> ControlFlow<B> {
852 struct V<F> {
853 index: u32,
854 f: F,
855 }
856 impl<'tcx, B, F: FnMut(BoundRegion) -> ControlFlow<B>> TypeVisitor<TyCtxt<'tcx>> for V<F> {
857 type BreakTy = B;
858 fn visit_region(&mut self, r: Region<'tcx>) -> ControlFlow<Self::BreakTy> {
859 if let RegionKind::ReLateBound(idx, bound) = r.kind() && idx.as_u32() == self.index {
860 (self.f)(bound)
861 } else {
862 ControlFlow::Continue(())
863 }
864 }
865 fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(&mut self, t: &Binder<'tcx, T>) -> ControlFlow<Self::BreakTy> {
866 self.index += 1;
867 let res = t.super_visit_with(self);
868 self.index -= 1;
869 res
870 }
871 }
872 ty.visit_with(&mut V { index: 0, f })
873 }
874
875 pub struct AdtVariantInfo {
876 pub ind: usize,
877 pub size: u64,
878
879 /// (ind, size)
880 pub fields_size: Vec<(usize, u64)>,
881 }
882
883 impl AdtVariantInfo {
884 /// Returns ADT variants ordered by size
885 pub fn new<'tcx>(cx: &LateContext<'tcx>, adt: AdtDef<'tcx>, subst: &'tcx List<GenericArg<'tcx>>) -> Vec<Self> {
886 let mut variants_size = adt
887 .variants()
888 .iter()
889 .enumerate()
890 .map(|(i, variant)| {
891 let mut fields_size = variant
892 .fields
893 .iter()
894 .enumerate()
895 .map(|(i, f)| (i, approx_ty_size(cx, f.ty(cx.tcx, subst))))
896 .collect::<Vec<_>>();
897 fields_size.sort_by(|(_, a_size), (_, b_size)| (a_size.cmp(b_size)));
898
899 Self {
900 ind: i,
901 size: fields_size.iter().map(|(_, size)| size).sum(),
902 fields_size,
903 }
904 })
905 .collect::<Vec<_>>();
906 variants_size.sort_by(|a, b| (b.size.cmp(&a.size)));
907 variants_size
908 }
909 }
910
911 /// Gets the struct or enum variant from the given `Res`
912 pub fn adt_and_variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option<(AdtDef<'tcx>, &'tcx VariantDef)> {
913 match res {
914 Res::Def(DefKind::Struct, id) => {
915 let adt = cx.tcx.adt_def(id);
916 Some((adt, adt.non_enum_variant()))
917 },
918 Res::Def(DefKind::Variant, id) => {
919 let adt = cx.tcx.adt_def(cx.tcx.parent(id));
920 Some((adt, adt.variant_with_id(id)))
921 },
922 Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => {
923 let adt = cx.tcx.adt_def(cx.tcx.parent(id));
924 Some((adt, adt.non_enum_variant()))
925 },
926 Res::Def(DefKind::Ctor(CtorOf::Variant, _), id) => {
927 let var_id = cx.tcx.parent(id);
928 let adt = cx.tcx.adt_def(cx.tcx.parent(var_id));
929 Some((adt, adt.variant_with_id(var_id)))
930 },
931 Res::SelfCtor(id) => {
932 let adt = cx.tcx.type_of(id).subst_identity().ty_adt_def().unwrap();
933 Some((adt, adt.non_enum_variant()))
934 },
935 _ => None,
936 }
937 }
938
939 /// Checks if the type is a type parameter implementing `FnOnce`, but not `FnMut`.
940 pub fn ty_is_fn_once_param<'tcx>(tcx: TyCtxt<'_>, ty: Ty<'tcx>, predicates: &'tcx [Predicate<'_>]) -> bool {
941 let ty::Param(ty) = *ty.kind() else {
942 return false;
943 };
944 let lang = tcx.lang_items();
945 let (Some(fn_once_id), Some(fn_mut_id), Some(fn_id))
946 = (lang.fn_once_trait(), lang.fn_mut_trait(), lang.fn_trait())
947 else {
948 return false;
949 };
950 predicates
951 .iter()
952 .try_fold(false, |found, p| {
953 if let PredicateKind::Clause(ty::Clause::Trait(p)) = p.kind().skip_binder()
954 && let ty::Param(self_ty) = p.trait_ref.self_ty().kind()
955 && ty.index == self_ty.index
956 {
957 // This should use `super_traits_of`, but that's a private function.
958 if p.trait_ref.def_id == fn_once_id {
959 return Some(true);
960 } else if p.trait_ref.def_id == fn_mut_id || p.trait_ref.def_id == fn_id {
961 return None;
962 }
963 }
964 Some(found)
965 })
966 .unwrap_or(false)
967 }
968
969 /// Comes up with an "at least" guesstimate for the type's size, not taking into
970 /// account the layout of type parameters.
971 pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 {
972 use rustc_middle::ty::layout::LayoutOf;
973 if !is_normalizable(cx, cx.param_env, ty) {
974 return 0;
975 }
976 match (cx.layout_of(ty).map(|layout| layout.size.bytes()), ty.kind()) {
977 (Ok(size), _) => size,
978 (Err(_), ty::Tuple(list)) => list.as_substs().types().map(|t| approx_ty_size(cx, t)).sum(),
979 (Err(_), ty::Array(t, n)) => {
980 n.try_eval_target_usize(cx.tcx, cx.param_env).unwrap_or_default() * approx_ty_size(cx, *t)
981 },
982 (Err(_), ty::Adt(def, subst)) if def.is_struct() => def
983 .variants()
984 .iter()
985 .map(|v| {
986 v.fields
987 .iter()
988 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
989 .sum::<u64>()
990 })
991 .sum(),
992 (Err(_), ty::Adt(def, subst)) if def.is_enum() => def
993 .variants()
994 .iter()
995 .map(|v| {
996 v.fields
997 .iter()
998 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
999 .sum::<u64>()
1000 })
1001 .max()
1002 .unwrap_or_default(),
1003 (Err(_), ty::Adt(def, subst)) if def.is_union() => def
1004 .variants()
1005 .iter()
1006 .map(|v| {
1007 v.fields
1008 .iter()
1009 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
1010 .max()
1011 .unwrap_or_default()
1012 })
1013 .max()
1014 .unwrap_or_default(),
1015 (Err(_), _) => 0,
1016 }
1017 }
1018
1019 /// Makes the projection type for the named associated type in the given impl or trait impl.
1020 ///
1021 /// This function is for associated types which are "known" to exist, and as such, will only return
1022 /// `None` when debug assertions are disabled in order to prevent ICE's. With debug assertions
1023 /// enabled this will check that the named associated type exists, the correct number of
1024 /// substitutions are given, and that the correct kinds of substitutions are given (lifetime,
1025 /// constant or type). This will not check if type normalization would succeed.
1026 pub fn make_projection<'tcx>(
1027 tcx: TyCtxt<'tcx>,
1028 container_id: DefId,
1029 assoc_ty: Symbol,
1030 substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1031 ) -> Option<AliasTy<'tcx>> {
1032 fn helper<'tcx>(
1033 tcx: TyCtxt<'tcx>,
1034 container_id: DefId,
1035 assoc_ty: Symbol,
1036 substs: SubstsRef<'tcx>,
1037 ) -> Option<AliasTy<'tcx>> {
1038 let Some(assoc_item) = tcx
1039 .associated_items(container_id)
1040 .find_by_name_and_kind(tcx, Ident::with_dummy_span(assoc_ty), AssocKind::Type, container_id)
1041 else {
1042 debug_assert!(false, "type `{assoc_ty}` not found in `{container_id:?}`");
1043 return None;
1044 };
1045 #[cfg(debug_assertions)]
1046 {
1047 let generics = tcx.generics_of(assoc_item.def_id);
1048 let generic_count = generics.parent_count + generics.params.len();
1049 let params = generics
1050 .parent
1051 .map_or([].as_slice(), |id| &*tcx.generics_of(id).params)
1052 .iter()
1053 .chain(&generics.params)
1054 .map(|x| &x.kind);
1055
1056 debug_assert!(
1057 generic_count == substs.len(),
1058 "wrong number of substs for `{:?}`: found `{}` expected `{generic_count}`.\n\
1059 note: the expected parameters are: {:#?}\n\
1060 the given arguments are: `{substs:#?}`",
1061 assoc_item.def_id,
1062 substs.len(),
1063 params.map(ty::GenericParamDefKind::descr).collect::<Vec<_>>(),
1064 );
1065
1066 if let Some((idx, (param, arg))) = params
1067 .clone()
1068 .zip(substs.iter().map(GenericArg::unpack))
1069 .enumerate()
1070 .find(|(_, (param, arg))| {
1071 !matches!(
1072 (param, arg),
1073 (ty::GenericParamDefKind::Lifetime, GenericArgKind::Lifetime(_))
1074 | (ty::GenericParamDefKind::Type { .. }, GenericArgKind::Type(_))
1075 | (ty::GenericParamDefKind::Const { .. }, GenericArgKind::Const(_))
1076 )
1077 })
1078 {
1079 debug_assert!(
1080 false,
1081 "mismatched subst type at index {idx}: expected a {}, found `{arg:?}`\n\
1082 note: the expected parameters are {:#?}\n\
1083 the given arguments are {substs:#?}",
1084 param.descr(),
1085 params.map(ty::GenericParamDefKind::descr).collect::<Vec<_>>()
1086 );
1087 }
1088 }
1089
1090 Some(tcx.mk_alias_ty(assoc_item.def_id, substs))
1091 }
1092 helper(
1093 tcx,
1094 container_id,
1095 assoc_ty,
1096 tcx.mk_substs_from_iter(substs.into_iter().map(Into::into)),
1097 )
1098 }
1099
1100 /// Normalizes the named associated type in the given impl or trait impl.
1101 ///
1102 /// This function is for associated types which are "known" to be valid with the given
1103 /// substitutions, and as such, will only return `None` when debug assertions are disabled in order
1104 /// to prevent ICE's. With debug assertions enabled this will check that that type normalization
1105 /// succeeds as well as everything checked by `make_projection`.
1106 pub fn make_normalized_projection<'tcx>(
1107 tcx: TyCtxt<'tcx>,
1108 param_env: ParamEnv<'tcx>,
1109 container_id: DefId,
1110 assoc_ty: Symbol,
1111 substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1112 ) -> Option<Ty<'tcx>> {
1113 fn helper<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1114 #[cfg(debug_assertions)]
1115 if let Some((i, subst)) = ty
1116 .substs
1117 .iter()
1118 .enumerate()
1119 .find(|(_, subst)| subst.has_late_bound_regions())
1120 {
1121 debug_assert!(
1122 false,
1123 "substs contain late-bound region at index `{i}` which can't be normalized.\n\
1124 use `TyCtxt::erase_late_bound_regions`\n\
1125 note: subst is `{subst:#?}`",
1126 );
1127 return None;
1128 }
1129 match tcx.try_normalize_erasing_regions(param_env, tcx.mk_projection(ty.def_id, ty.substs)) {
1130 Ok(ty) => Some(ty),
1131 Err(e) => {
1132 debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1133 None
1134 },
1135 }
1136 }
1137 helper(tcx, param_env, make_projection(tcx, container_id, assoc_ty, substs)?)
1138 }
1139
1140 /// Check if given type has inner mutability such as [`std::cell::Cell`] or [`std::cell::RefCell`]
1141 /// etc.
1142 pub fn is_interior_mut_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1143 match *ty.kind() {
1144 ty::Ref(_, inner_ty, mutbl) => mutbl == Mutability::Mut || is_interior_mut_ty(cx, inner_ty),
1145 ty::Slice(inner_ty) => is_interior_mut_ty(cx, inner_ty),
1146 ty::Array(inner_ty, size) => {
1147 size.try_eval_target_usize(cx.tcx, cx.param_env)
1148 .map_or(true, |u| u != 0)
1149 && is_interior_mut_ty(cx, inner_ty)
1150 },
1151 ty::Tuple(fields) => fields.iter().any(|ty| is_interior_mut_ty(cx, ty)),
1152 ty::Adt(def, substs) => {
1153 // Special case for collections in `std` who's impl of `Hash` or `Ord` delegates to
1154 // that of their type parameters. Note: we don't include `HashSet` and `HashMap`
1155 // because they have no impl for `Hash` or `Ord`.
1156 let def_id = def.did();
1157 let is_std_collection = [
1158 sym::Option,
1159 sym::Result,
1160 sym::LinkedList,
1161 sym::Vec,
1162 sym::VecDeque,
1163 sym::BTreeMap,
1164 sym::BTreeSet,
1165 sym::Rc,
1166 sym::Arc,
1167 ]
1168 .iter()
1169 .any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, def_id));
1170 let is_box = Some(def_id) == cx.tcx.lang_items().owned_box();
1171 if is_std_collection || is_box {
1172 // The type is mutable if any of its type parameters are
1173 substs.types().any(|ty| is_interior_mut_ty(cx, ty))
1174 } else {
1175 !ty.has_escaping_bound_vars()
1176 && cx.tcx.layout_of(cx.param_env.and(ty)).is_ok()
1177 && !ty.is_freeze(cx.tcx, cx.param_env)
1178 }
1179 },
1180 _ => false,
1181 }
1182 }