1#![allow(clippy::module_name_repetitions)]
4
5use core::ops::ControlFlow;
6use rustc_abi::{BackendRepr, FieldsShape, VariantIdx, Variants};
7use rustc_ast::ast::Mutability;
8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9use rustc_hir as hir;
10use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
11use rustc_hir::def_id::DefId;
12use rustc_hir::{Expr, FnDecl, LangItem, find_attr};
13use rustc_hir_analysis::lower_ty;
14use rustc_infer::infer::TyCtxtInferExt;
15use rustc_lint::LateContext;
16use rustc_middle::mir::ConstValue;
17use rustc_middle::mir::interpret::Scalar;
18use rustc_middle::traits::EvaluationResult;
19use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind};
20use rustc_middle::ty::layout::{LayoutError, LayoutOf, TyAndLayout};
21use rustc_middle::ty::{
22 self, AdtDef, AliasTy, AssocItem, AssocTag, Binder, BoundRegion, BoundVarIndexKind, FnSig, GenericArg,
23 GenericArgKind, GenericArgsRef, IntTy, ProjectionAliasTy, Region, RegionKind, TraitRef, Ty, TyCtxt,
24 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, UintTy, Unnormalized, Upcast, VariantDef,
25 VariantDiscr,
26};
27use rustc_span::symbol::Ident;
28use rustc_span::{DUMMY_SP, Span, Symbol};
29use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
30use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
31use rustc_trait_selection::traits::{Obligation, ObligationCause};
32use std::collections::hash_map::Entry;
33use std::{debug_assert_matches, iter, mem};
34
35use crate::paths::{PathNS, lookup_path_str};
36use crate::res::{MaybeDef, MaybeQPath};
37use crate::{over, sym};
38
39mod type_certainty;
40pub use type_certainty::expr_type_is_certain;
41
42pub fn ty_from_hir_ty<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
44 cx.maybe_typeck_results()
45 .filter(|results| results.hir_owner == hir_ty.hir_id.owner)
46 .and_then(|results| results.node_type_opt(hir_ty.hir_id))
47 .unwrap_or_else(|| lower_ty(cx.tcx, hir_ty))
48}
49
50pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
52 cx.type_is_copy_modulo_regions(ty)
53}
54
55pub fn has_debug_impl<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
57 cx.tcx
58 .get_diagnostic_item(sym::Debug)
59 .is_some_and(|debug| implements_trait(cx, ty, debug, &[]))
60}
61
62pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
64 if has_drop(cx, ty) || is_copy(cx, ty) {
65 return false;
66 }
67 match ty.kind() {
68 ty::Param(_) => false,
69 ty::Adt(def, subs) => def
70 .all_fields()
71 .any(|f| !is_copy(cx, f.ty(cx.tcx, subs).skip_norm_wip())),
72 _ => true,
73 }
74}
75
76pub fn contains_adt_constructor<'tcx>(ty: Ty<'tcx>, adt: AdtDef<'tcx>) -> bool {
79 ty.walk().any(|inner| match inner.kind() {
80 GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
81 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
82 })
83}
84
85pub fn contains_ty_adt_constructor_opaque<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, needle: Ty<'tcx>) -> bool {
91 fn contains_ty_adt_constructor_opaque_inner<'tcx>(
92 cx: &LateContext<'tcx>,
93 ty: Ty<'tcx>,
94 needle: Ty<'tcx>,
95 seen: &mut FxHashSet<DefId>,
96 ) -> bool {
97 ty.walk().any(|inner| match inner.kind() {
98 GenericArgKind::Type(inner_ty) => {
99 if inner_ty == needle {
100 return true;
101 }
102
103 if inner_ty.ty_adt_def() == needle.ty_adt_def() {
104 return true;
105 }
106
107 if let ty::Alias(_, AliasTy {
108 kind: ty::Opaque { def_id },
109 ..
110 }) = *inner_ty.kind()
111 {
112 if !seen.insert(def_id) {
113 return false;
114 }
115
116 for (predicate, _span) in cx
117 .tcx
118 .explicit_item_self_bounds(def_id)
119 .iter_identity_copied()
120 .map(Unnormalized::skip_norm_wip)
121 {
122 match predicate.kind().skip_binder() {
123 ty::ClauseKind::Trait(trait_predicate)
126 if trait_predicate
127 .trait_ref
128 .args
129 .types()
130 .skip(1) .any(|ty| contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen)) =>
132 {
133 return true;
134 },
135 ty::ClauseKind::Projection(projection_predicate) => {
138 if let ty::TermKind::Ty(ty) = projection_predicate.term.kind()
139 && contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen)
140 {
141 return true;
142 }
143 },
144 _ => (),
145 }
146 }
147 }
148
149 false
150 },
151 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
152 })
153 }
154
155 let mut seen = FxHashSet::default();
158 contains_ty_adt_constructor_opaque_inner(cx, ty, needle, &mut seen)
159}
160
161pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
164 cx.tcx
165 .get_diagnostic_item(sym::Iterator)
166 .and_then(|iter_did| cx.get_associated_type(ty, iter_did, sym::Item))
167}
168
169pub fn should_call_clone_as_function(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
175 matches!(
176 ty.opt_diag_name(cx),
177 Some(sym::Arc | sym::ArcWeak | sym::Rc | sym::RcWeak)
178 )
179}
180
181pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
183 let into_iter_collections: &[Symbol] = &[
187 sym::Vec,
188 sym::Option,
189 sym::Result,
190 sym::BTreeMap,
191 sym::BTreeSet,
192 sym::VecDeque,
193 sym::LinkedList,
194 sym::BinaryHeap,
195 sym::HashSet,
196 sym::HashMap,
197 sym::PathBuf,
198 sym::Path,
199 sym::MpscReceiver,
200 sym::MpmcReceiver,
201 ];
202
203 let ty_to_check = match probably_ref_ty.kind() {
204 ty::Ref(_, ty_to_check, _) => *ty_to_check,
205 _ => probably_ref_ty,
206 };
207
208 let def_id = match ty_to_check.kind() {
209 ty::Array(..) => return Some(sym::array),
210 ty::Slice(..) => return Some(sym::slice),
211 ty::Adt(adt, _) => adt.did(),
212 _ => return None,
213 };
214
215 for &name in into_iter_collections {
216 if cx.tcx.is_diagnostic_item(name, def_id) {
217 return Some(cx.tcx.item_name(def_id));
218 }
219 }
220 None
221}
222
223pub fn implements_trait<'tcx>(
230 cx: &LateContext<'tcx>,
231 ty: Ty<'tcx>,
232 trait_id: DefId,
233 args: &[GenericArg<'tcx>],
234) -> bool {
235 implements_trait_with_env_from_iter(
236 cx.tcx,
237 cx.typing_env(),
238 ty,
239 trait_id,
240 None,
241 args.iter().map(|&x| Some(x)),
242 )
243}
244
245pub fn implements_trait_with_env<'tcx>(
250 tcx: TyCtxt<'tcx>,
251 typing_env: ty::TypingEnv<'tcx>,
252 ty: Ty<'tcx>,
253 trait_id: DefId,
254 callee_id: Option<DefId>,
255 args: &[GenericArg<'tcx>],
256) -> bool {
257 implements_trait_with_env_from_iter(tcx, typing_env, ty, trait_id, callee_id, args.iter().map(|&x| Some(x)))
258}
259
260pub fn implements_trait_with_env_from_iter<'tcx>(
262 tcx: TyCtxt<'tcx>,
263 typing_env: ty::TypingEnv<'tcx>,
264 ty: Ty<'tcx>,
265 trait_id: DefId,
266 callee_id: Option<DefId>,
267 args: impl IntoIterator<Item = impl Into<Option<GenericArg<'tcx>>>>,
268) -> bool {
269 assert!(!ty.has_infer());
271
272 if let Some(callee_id) = callee_id {
276 let _ = tcx.hir_body_owner_kind(callee_id);
277 }
278
279 let ty = tcx.erase_and_anonymize_regions(ty);
280 if ty.has_escaping_bound_vars() {
281 return false;
282 }
283
284 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
285 let args = args
286 .into_iter()
287 .map(|arg| arg.into().unwrap_or_else(|| infcx.next_ty_var(DUMMY_SP).into()))
288 .collect::<Vec<_>>();
289
290 let trait_ref = TraitRef::new(tcx, trait_id, [GenericArg::from(ty)].into_iter().chain(args));
291
292 debug_assert_matches!(
293 tcx.def_kind(trait_id),
294 DefKind::Trait | DefKind::TraitAlias,
295 "`DefId` must belong to a trait or trait alias"
296 );
297 #[cfg(debug_assertions)]
298 assert_generic_args_match(tcx, trait_id, trait_ref.args);
299
300 let obligation = Obligation {
301 cause: ObligationCause::dummy(),
302 param_env,
303 recursion_depth: 0,
304 predicate: trait_ref.upcast(tcx),
305 };
306 infcx
307 .evaluate_obligation(&obligation)
308 .is_ok_and(EvaluationResult::must_apply_modulo_regions)
309}
310
311pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
313 match ty.ty_adt_def() {
314 Some(def) => def.has_dtor(cx.tcx),
315 None => false,
316 }
317}
318
319pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
323 match ty.kind() {
324 ty::Adt(adt, args) => match cx.tcx.get_diagnostic_name(adt.did()) {
325 Some(sym::Result) if args.type_at(1).is_privately_uninhabited(cx.tcx, cx.typing_env()) => {
326 is_must_use_ty(cx, args.type_at(0))
327 },
328 Some(sym::ControlFlow) if args.type_at(0).is_privately_uninhabited(cx.tcx, cx.typing_env()) => {
329 is_must_use_ty(cx, args.type_at(1))
330 },
331 _ => find_attr!(cx.tcx, adt.did(), MustUse { .. }),
332 },
333 ty::Foreign(did) => find_attr!(cx.tcx, *did, MustUse { .. }),
334 ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty, _) | ty::Ref(_, ty, _) => {
335 is_must_use_ty(cx, *ty)
338 },
339 ty::Tuple(args) => args.iter().any(|ty| is_must_use_ty(cx, ty)),
340 ty::Alias(_, AliasTy {
341 kind: ty::Opaque { def_id },
342 ..
343 }) => {
344 for (predicate, _) in cx.tcx.explicit_item_self_bounds(*def_id).skip_binder() {
345 if let ty::ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder()
346 && find_attr!(cx.tcx, trait_predicate.trait_ref.def_id, MustUse { .. })
347 {
348 return true;
349 }
350 }
351 false
352 },
353 ty::Dynamic(binder, _) => {
354 for predicate in *binder {
355 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder()
356 && find_attr!(cx.tcx, trait_ref.def_id, MustUse { .. })
357 {
358 return true;
359 }
360 }
361 false
362 },
363 _ => false,
364 }
365}
366
367pub fn is_non_aggregate_primitive_type(ty: Ty<'_>) -> bool {
373 matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_))
374}
375
376pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
379 match *ty.kind() {
380 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
381 ty::Ref(_, inner, _) if inner.is_str() => true,
382 ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
383 ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type),
384 _ => false,
385 }
386}
387
388pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
390 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
391}
392
393pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
398 fn needs_ordered_drop_inner<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
399 if !seen.insert(ty) {
400 return false;
401 }
402 if !ty.has_significant_drop(cx.tcx, cx.typing_env()) {
403 false
404 }
405 else if ty.is_lang_item(cx, LangItem::OwnedBox)
407 || matches!(
408 ty.opt_diag_name(cx),
409 Some(sym::HashSet | sym::Rc | sym::Arc | sym::cstring_type | sym::RcWeak | sym::ArcWeak)
410 )
411 {
412 if let ty::Adt(_, subs) = ty.kind() {
414 subs.types().any(|ty| needs_ordered_drop_inner(cx, ty, seen))
415 } else {
416 true
417 }
418 } else if !cx
419 .tcx
420 .lang_items()
421 .drop_trait()
422 .is_some_and(|id| implements_trait(cx, ty, id, &[]))
423 {
424 match ty.kind() {
427 ty::Tuple(fields) => fields.iter().any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
428 ty::Array(ty, _) => needs_ordered_drop_inner(cx, *ty, seen),
429 ty::Adt(adt, subs) => adt
430 .all_fields()
431 .map(|f| f.ty(cx.tcx, subs).skip_norm_wip())
432 .any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
433 _ => true,
434 }
435 } else {
436 true
437 }
438 }
439
440 needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
441}
442
443pub fn is_unsafe_fn<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
445 ty.is_fn() && ty.fn_sig(cx.tcx).safety().is_unsafe()
446}
447
448pub fn peel_and_count_ty_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize, Option<Mutability>) {
452 let mut count = 0;
453 let mut mutbl = None;
454 while let ty::Ref(_, dest_ty, m) = ty.kind() {
455 ty = *dest_ty;
456 count += 1;
457 mutbl.replace(mutbl.map_or(*m, |mutbl: Mutability| mutbl.min(*m)));
458 }
459 (ty, count, mutbl)
460}
461
462pub fn peel_n_ty_refs(mut ty: Ty<'_>, n: usize) -> (Ty<'_>, Option<Mutability>) {
465 let mut mutbl = None;
466 for _ in 0..n {
467 if let ty::Ref(_, dest_ty, m) = ty.kind() {
468 ty = *dest_ty;
469 mutbl.replace(mutbl.map_or(*m, |mutbl: Mutability| mutbl.min(*m)));
470 } else {
471 break;
472 }
473 }
474 (ty, mutbl)
475}
476
477pub fn same_type_modulo_regions<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
489 match (a.kind(), b.kind()) {
490 (ty::Adt(did_a, args_a), ty::Adt(did_b, args_b)) => {
491 if did_a != did_b {
492 return false;
493 }
494
495 iter::zip(*args_a, *args_b).all(|(arg_a, arg_b)| match (arg_a.kind(), arg_b.kind()) {
496 (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
497 (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
498 same_type_modulo_regions(type_a, type_b)
499 },
500 _ => true,
501 })
502 },
503 (ty::Ref(_, a, mut_a), ty::Ref(_, b, mut_b)) => mut_a == mut_b && same_type_modulo_regions(*a, *b),
504 (ty::Tuple(as_), ty::Tuple(bs)) => over(as_, bs, |a, b| same_type_modulo_regions(*a, *b)),
505 (ty::Array(a, na), ty::Array(b, nb)) => na == nb && same_type_modulo_regions(*a, *b),
506 _ => a == b,
507 }
508}
509
510pub fn is_uninit_value_valid_for_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
512 match cx.layout_of(ty) {
513 Ok(layout) => is_uninit_value_valid_for_layout(cx, layout),
514 Err(LayoutError::TooGeneric(_) | LayoutError::SizeOverflow(_)) => is_uninit_value_valid_for_ty_fallback(cx, ty),
516 Err(_) => false,
517 }
518}
519
520fn is_uninit_value_valid_for_layout<'tcx>(cx: &LateContext<'tcx>, layout: TyAndLayout<'tcx>) -> bool {
521 if layout.layout.is_zst() {
523 return true;
524 }
525
526 match layout.layout.backend_repr {
527 BackendRepr::Scalar(s) => s.is_uninit_valid(),
528 BackendRepr::ScalarPair(a, b) => a.is_uninit_valid() && b.is_uninit_valid(),
529 BackendRepr::SimdVector { element, count } => count == 0 || element.is_uninit_valid(),
530 BackendRepr::SimdScalableVector { element, .. } => element.is_uninit_valid(),
531 BackendRepr::Memory { .. } => match &layout.layout.variants {
533 Variants::Single { .. } => match &layout.layout.fields {
534 FieldsShape::Primitive => {
535 debug_assert!(false, "Both Scalar primitives and ! should be handled above.");
536 false
537 },
538 FieldsShape::Array { count, .. } => {
540 if *count == 0 {
541 true
542 } else {
543 is_uninit_value_valid_for_layout(cx, layout.field(cx, 0))
544 }
545 },
546 FieldsShape::Arbitrary { offsets, .. } => {
548 (0..offsets.len()).all(|i| is_uninit_value_valid_for_layout(cx, layout.field(cx, i)))
549 },
550 FieldsShape::Union(count) => {
552 (0..count.get()).any(|i| is_uninit_value_valid_for_layout(cx, layout.field(cx, i)))
553 },
554 },
555 Variants::Empty => true,
557 Variants::Multiple { .. } => false,
559 },
560 }
561}
562
563fn is_uninit_value_valid_for_ty_fallback<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
565 let typing_env = cx.typing_env().with_post_analysis_normalized(cx.tcx);
566
567 match *ty.kind() {
568 ty::Array(component, len) => {
570 if len.try_to_target_usize(cx.tcx) == Some(0) {
572 return true;
573 }
574 is_uninit_value_valid_for_ty(cx, component)
575 },
576 ty::Tuple(types) => types.iter().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
578 ty::Adt(adt, args) if adt.is_union() => adt.all_fields().any(|field| {
580 let unnormalized_field_ty = field.ty(cx.tcx, args);
581 let Ok(field_ty) = cx.tcx.try_normalize_erasing_regions(typing_env, unnormalized_field_ty) else {
582 debug_assert!(
583 false,
584 "failed to normalize field type `{unnormalized_field_ty:?}`, ParamEnv is likely set incorrectly."
585 );
586 return false;
587 };
588 is_uninit_value_valid_for_ty(cx, field_ty)
589 }),
590 ty::Adt(adt, args) if adt.is_struct() || adt.variants().len() == 1 => adt.all_fields().all(|field| {
594 let unnormalized_field_ty = field.ty(cx.tcx, args);
595 let Ok(field_ty) = cx.tcx.try_normalize_erasing_regions(typing_env, unnormalized_field_ty) else {
596 debug_assert!(
597 false,
598 "failed to normalize field type `{unnormalized_field_ty:?}`, ParamEnv is likely set incorrectly."
599 );
600 return false;
601 };
602
603 is_uninit_value_valid_for_ty(cx, field_ty)
604 }),
605 ty::Adt(adt, _) if adt.is_enum() => false,
608 _ => false,
610 }
611}
612
613pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(ty::Clause<'_>, Span)> {
615 let mut next_id = Some(id);
616 iter::from_fn(move || {
617 next_id.take().map(|id| {
618 let preds = tcx.predicates_of(id);
619 next_id = preds.parent;
620 preds.predicates.iter()
621 })
622 })
623 .flatten()
624}
625
626#[derive(Clone, Copy, Debug)]
628pub enum ExprFnSig<'tcx> {
629 Sig(Binder<'tcx, FnSig<'tcx>>, Option<DefId>),
630 Closure(Option<&'tcx FnDecl<'tcx>>, Binder<'tcx, FnSig<'tcx>>),
631 Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>, Option<DefId>),
632}
633impl<'tcx> ExprFnSig<'tcx> {
634 pub fn input(self, i: usize) -> Option<Binder<'tcx, Ty<'tcx>>> {
637 match self {
638 Self::Sig(sig, _) => {
639 if sig.c_variadic() {
640 sig.inputs().map_bound(|inputs| inputs.get(i).copied()).transpose()
641 } else {
642 Some(sig.input(i))
643 }
644 },
645 Self::Closure(_, sig) => Some(sig.input(0).map_bound(|ty| ty.tuple_fields()[i])),
646 Self::Trait(inputs, _, _) => Some(inputs.map_bound(|ty| ty.tuple_fields()[i])),
647 }
648 }
649
650 pub fn input_with_hir(self, i: usize) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> {
654 match self {
655 Self::Sig(sig, _) => {
656 if sig.c_variadic() {
657 sig.inputs()
658 .map_bound(|inputs| inputs.get(i).copied())
659 .transpose()
660 .map(|arg| (None, arg))
661 } else {
662 Some((None, sig.input(i)))
663 }
664 },
665 Self::Closure(decl, sig) => Some((
666 decl.and_then(|decl| decl.inputs.get(i)),
667 sig.input(0).map_bound(|ty| ty.tuple_fields()[i]),
668 )),
669 Self::Trait(inputs, _, _) => Some((None, inputs.map_bound(|ty| ty.tuple_fields()[i]))),
670 }
671 }
672
673 pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
676 match self {
677 Self::Sig(sig, _) | Self::Closure(_, sig) => Some(sig.output()),
678 Self::Trait(_, output, _) => output,
679 }
680 }
681
682 pub fn predicates_id(&self) -> Option<DefId> {
683 if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self {
684 id
685 } else {
686 None
687 }
688 }
689}
690
691pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
693 if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = expr.res(cx) {
694 Some(ExprFnSig::Sig(
695 cx.tcx.fn_sig(id).instantiate_identity().skip_norm_wip(),
696 Some(id),
697 ))
698 } else {
699 ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs())
700 }
701}
702
703pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'tcx>> {
705 if let Some(boxed_ty) = ty.boxed_ty() {
706 return ty_sig(cx, boxed_ty);
707 }
708 match *ty.kind() {
709 ty::Closure(id, subs) => {
710 let decl = id
711 .as_local()
712 .and_then(|id| cx.tcx.hir_fn_decl_by_hir_id(cx.tcx.local_def_id_to_hir_id(id)));
713 Some(ExprFnSig::Closure(decl, subs.as_closure().sig()))
714 },
715 ty::FnDef(id, subs) => Some(ExprFnSig::Sig(
716 cx.tcx.fn_sig(id).instantiate(cx.tcx, subs).skip_norm_wip(),
717 Some(id),
718 )),
719 ty::Alias(_, AliasTy {
720 kind: ty::Opaque { def_id },
721 args,
722 ..
723 }) => sig_from_bounds(
724 cx,
725 ty,
726 cx.tcx
727 .item_self_bounds(def_id)
728 .iter_instantiated(cx.tcx, args)
729 .map(Unnormalized::skip_norm_wip),
730 cx.tcx.opt_parent(def_id),
731 ),
732 ty::FnPtr(sig_tys, hdr) => Some(ExprFnSig::Sig(sig_tys.with(hdr), None)),
733 ty::Dynamic(bounds, _) => {
734 let lang_items = cx.tcx.lang_items();
735 match bounds.principal() {
736 Some(bound)
737 if Some(bound.def_id()) == lang_items.fn_trait()
738 || Some(bound.def_id()) == lang_items.fn_once_trait()
739 || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
740 {
741 let output = bounds
742 .projection_bounds()
743 .find(|p| lang_items.fn_once_output().is_some_and(|id| id == p.item_def_id()))
744 .map(|p| p.map_bound(|p| p.term.expect_type()));
745 Some(ExprFnSig::Trait(bound.map_bound(|b| b.args.type_at(0)), output, None))
746 },
747 _ => None,
748 }
749 },
750 ty::Alias(_, alias) if let Some(proj) = alias.try_to_projection() => match cx
751 .tcx
752 .try_normalize_erasing_regions(cx.typing_env(), Unnormalized::new_wip(ty))
753 {
754 Ok(normalized_ty) if normalized_ty != ty => ty_sig(cx, normalized_ty),
755 _ => sig_for_projection(cx, proj).or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)),
756 },
757 ty::Param(_) => sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None),
758 _ => None,
759 }
760}
761
762fn sig_from_bounds<'tcx>(
763 cx: &LateContext<'tcx>,
764 ty: Ty<'tcx>,
765 predicates: impl IntoIterator<Item = ty::Clause<'tcx>>,
766 predicates_id: Option<DefId>,
767) -> Option<ExprFnSig<'tcx>> {
768 let mut inputs = None;
769 let mut output = None;
770 let lang_items = cx.tcx.lang_items();
771
772 for pred in predicates {
773 match pred.kind().skip_binder() {
774 ty::ClauseKind::Trait(p)
775 if (lang_items.fn_trait() == Some(p.def_id())
776 || lang_items.fn_mut_trait() == Some(p.def_id())
777 || lang_items.fn_once_trait() == Some(p.def_id()))
778 && p.self_ty() == ty =>
779 {
780 let i = pred.kind().rebind(p.trait_ref.args.type_at(1));
781 if inputs.is_some_and(|inputs| i != inputs) {
782 return None;
784 }
785 inputs = Some(i);
786 },
787 ty::ClauseKind::Projection(p)
788 if Some(p.projection_term.expect_projection_def_id()) == lang_items.fn_once_output()
789 && p.projection_term.self_ty() == ty =>
790 {
791 if output.is_some() {
792 return None;
794 }
795 output = Some(pred.kind().rebind(p.term.expect_type()));
796 },
797 _ => (),
798 }
799 }
800
801 inputs.map(|ty| ExprFnSig::Trait(ty, output, predicates_id))
802}
803
804fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: ProjectionAliasTy<'tcx>) -> Option<ExprFnSig<'tcx>> {
805 let mut inputs = None;
806 let mut output = None;
807 let lang_items = cx.tcx.lang_items();
808
809 for (pred, _) in cx
810 .tcx
811 .explicit_item_bounds(ty.kind)
812 .iter_instantiated_copied(cx.tcx, ty.args)
813 .map(Unnormalized::skip_norm_wip)
814 {
815 match pred.kind().skip_binder() {
816 ty::ClauseKind::Trait(p)
817 if (lang_items.fn_trait() == Some(p.def_id())
818 || lang_items.fn_mut_trait() == Some(p.def_id())
819 || lang_items.fn_once_trait() == Some(p.def_id())) =>
820 {
821 let i = pred.kind().rebind(p.trait_ref.args.type_at(1));
822
823 if inputs.is_some_and(|inputs| inputs != i) {
824 return None;
826 }
827 inputs = Some(i);
828 },
829 ty::ClauseKind::Projection(p)
830 if Some(p.projection_term.expect_projection_def_id()) == lang_items.fn_once_output() =>
831 {
832 if output.is_some() {
833 return None;
835 }
836 output = pred.kind().rebind(p.term.as_type()).transpose();
837 },
838 _ => (),
839 }
840 }
841
842 inputs.map(|ty| ExprFnSig::Trait(ty, output, None))
843}
844
845#[derive(Clone, Copy)]
846pub enum EnumValue {
847 Unsigned(u128),
848 Signed(i128),
849}
850impl core::ops::Add<u32> for EnumValue {
851 type Output = Self;
852 fn add(self, n: u32) -> Self::Output {
853 match self {
854 Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
855 Self::Signed(x) => Self::Signed(x + i128::from(n)),
856 }
857 }
858}
859
860pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
862 if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
863 match tcx.type_of(id).instantiate_identity().skip_norm_wip().kind() {
864 ty::Int(_) => Some(EnumValue::Signed(value.to_int(value.size()))),
865 ty::Uint(_) => Some(EnumValue::Unsigned(value.to_uint(value.size()))),
866 _ => None,
867 }
868 } else {
869 None
870 }
871}
872
873pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: AdtDef<'_>, i: VariantIdx) -> EnumValue {
875 let variant = &adt.variant(i);
876 match variant.discr {
877 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
878 VariantDiscr::Relative(x) => match adt.variant((i.as_usize() - x as usize).into()).discr {
879 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
880 VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
881 },
882 }
883}
884
885pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
888 if let ty::Adt(adt, _) = ty.kind()
889 && let &[krate, .., name] = &*cx.get_def_path(adt.did())
890 && let sym::libc | sym::core | sym::std = krate
891 && name == sym::c_void
892 {
893 true
894 } else {
895 false
896 }
897}
898
899pub fn for_each_top_level_late_bound_region<'cx, B>(
900 ty: Ty<'cx>,
901 f: impl FnMut(BoundRegion<'cx>) -> ControlFlow<B>,
902) -> ControlFlow<B> {
903 struct V<F> {
904 index: u32,
905 f: F,
906 }
907 impl<'tcx, B, F: FnMut(BoundRegion<'tcx>) -> ControlFlow<B>> TypeVisitor<TyCtxt<'tcx>> for V<F> {
908 type Result = ControlFlow<B>;
909 fn visit_region(&mut self, r: Region<'tcx>) -> Self::Result {
910 if let RegionKind::ReBound(BoundVarIndexKind::Bound(idx), bound) = r.kind()
911 && idx.as_u32() == self.index
912 {
913 (self.f)(bound)
914 } else {
915 ControlFlow::Continue(())
916 }
917 }
918 fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(&mut self, t: &Binder<'tcx, T>) -> Self::Result {
919 self.index += 1;
920 let res = t.super_visit_with(self);
921 self.index -= 1;
922 res
923 }
924 }
925 ty.visit_with(&mut V { index: 0, f })
926}
927
928pub struct AdtVariantInfo {
929 pub ind: usize,
930 pub size: u64,
931
932 pub fields_size: Vec<(usize, u64)>,
934}
935
936impl AdtVariantInfo {
937 pub fn new<'tcx>(cx: &LateContext<'tcx>, adt: AdtDef<'tcx>, subst: GenericArgsRef<'tcx>) -> Vec<Self> {
939 let mut variants_size = adt
940 .variants()
941 .iter()
942 .enumerate()
943 .map(|(i, variant)| {
944 let mut fields_size = variant
945 .fields
946 .iter()
947 .enumerate()
948 .map(|(i, f)| (i, approx_ty_size(cx, f.ty(cx.tcx, subst).skip_norm_wip())))
949 .collect::<Vec<_>>();
950 fields_size.sort_by_key(|(_, a_size)| *a_size);
951
952 Self {
953 ind: i,
954 size: fields_size.iter().map(|(_, size)| size).sum(),
955 fields_size,
956 }
957 })
958 .collect::<Vec<_>>();
959 variants_size.sort_by_key(|b| std::cmp::Reverse(b.size));
960 variants_size
961 }
962}
963
964pub fn adt_and_variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option<(AdtDef<'tcx>, &'tcx VariantDef)> {
966 match res {
967 Res::Def(DefKind::Struct, id) => {
968 let adt = cx.tcx.adt_def(id);
969 Some((adt, adt.non_enum_variant()))
970 },
971 Res::Def(DefKind::Variant, id) => {
972 let adt = cx.tcx.adt_def(cx.tcx.parent(id));
973 Some((adt, adt.variant_with_id(id)))
974 },
975 Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => {
976 let adt = cx.tcx.adt_def(cx.tcx.parent(id));
977 Some((adt, adt.non_enum_variant()))
978 },
979 Res::Def(DefKind::Ctor(CtorOf::Variant, _), id) => {
980 let var_id = cx.tcx.parent(id);
981 let adt = cx.tcx.adt_def(cx.tcx.parent(var_id));
982 Some((adt, adt.variant_with_id(var_id)))
983 },
984 Res::SelfCtor(id) => {
985 let adt = cx
986 .tcx
987 .type_of(id)
988 .instantiate_identity()
989 .skip_norm_wip()
990 .ty_adt_def()
991 .unwrap();
992 Some((adt, adt.non_enum_variant()))
993 },
994 _ => None,
995 }
996}
997
998pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 {
1001 use rustc_middle::ty::layout::LayoutOf;
1002 match (cx.layout_of(ty).map(|layout| layout.size.bytes()), ty.kind()) {
1003 (Ok(size), _) => size,
1004 (Err(_), ty::Tuple(list)) => list.iter().map(|t| approx_ty_size(cx, t)).sum(),
1005 (Err(_), ty::Array(t, n)) => n.try_to_target_usize(cx.tcx).unwrap_or_default() * approx_ty_size(cx, *t),
1006 (Err(_), ty::Adt(def, subst)) if def.is_struct() => def
1007 .variants()
1008 .iter()
1009 .map(|v| {
1010 v.fields
1011 .iter()
1012 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst).skip_norm_wip()))
1013 .sum::<u64>()
1014 })
1015 .sum(),
1016 (Err(_), ty::Adt(def, subst)) if def.is_enum() => def
1017 .variants()
1018 .iter()
1019 .map(|v| {
1020 v.fields
1021 .iter()
1022 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst).skip_norm_wip()))
1023 .sum::<u64>()
1024 })
1025 .max()
1026 .unwrap_or_default(),
1027 (Err(_), ty::Adt(def, subst)) if def.is_union() => def
1028 .variants()
1029 .iter()
1030 .map(|v| {
1031 v.fields
1032 .iter()
1033 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst).skip_norm_wip()))
1034 .max()
1035 .unwrap_or_default()
1036 })
1037 .max()
1038 .unwrap_or_default(),
1039 (Err(_), _) => 0,
1040 }
1041}
1042
1043#[cfg(debug_assertions)]
1044fn assert_generic_args_match<'tcx>(tcx: TyCtxt<'tcx>, did: DefId, args: &[GenericArg<'tcx>]) {
1046 use itertools::Itertools;
1047 let g = tcx.generics_of(did);
1048 let parent = g.parent.map(|did| tcx.generics_of(did));
1049 let count = g.parent_count + g.own_params.len();
1050 let params = parent
1051 .map_or([].as_slice(), |p| p.own_params.as_slice())
1052 .iter()
1053 .chain(&g.own_params)
1054 .map(|x| &x.kind);
1055
1056 assert!(
1057 count == args.len(),
1058 "wrong number of arguments for `{did:?}`: expected `{count}`, found {}\n\
1059 note: the expected arguments are: `[{}]`\n\
1060 the given arguments are: `{args:#?}`",
1061 args.len(),
1062 params.clone().map(ty::GenericParamDefKind::descr).format(", "),
1063 );
1064
1065 if let Some((idx, (param, arg))) =
1066 params
1067 .clone()
1068 .zip(args.iter().map(|&x| x.kind()))
1069 .enumerate()
1070 .find(|(_, (param, arg))| match (param, arg) {
1071 (ty::GenericParamDefKind::Lifetime, GenericArgKind::Lifetime(_))
1072 | (ty::GenericParamDefKind::Type { .. }, GenericArgKind::Type(_))
1073 | (ty::GenericParamDefKind::Const { .. }, GenericArgKind::Const(_)) => false,
1074 (
1075 ty::GenericParamDefKind::Lifetime
1076 | ty::GenericParamDefKind::Type { .. }
1077 | ty::GenericParamDefKind::Const { .. },
1078 _,
1079 ) => true,
1080 })
1081 {
1082 panic!(
1083 "incorrect argument for `{did:?}` at index `{idx}`: expected a {}, found `{arg:?}`\n\
1084 note: the expected arguments are `[{}]`\n\
1085 the given arguments are `{args:#?}`",
1086 param.descr(),
1087 params.clone().map(ty::GenericParamDefKind::descr).format(", "),
1088 );
1089 }
1090}
1091
1092pub fn is_never_like(ty: Ty<'_>) -> bool {
1094 ty.is_never() || (ty.is_enum() && ty.ty_adt_def().is_some_and(|def| def.variants().is_empty()))
1095}
1096
1097pub fn make_projection<'tcx>(
1105 tcx: TyCtxt<'tcx>,
1106 container_id: DefId,
1107 assoc_ty: Symbol,
1108 args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1109) -> Option<AliasTy<'tcx>> {
1110 fn helper<'tcx>(
1111 tcx: TyCtxt<'tcx>,
1112 container_id: DefId,
1113 assoc_ty: Symbol,
1114 args: GenericArgsRef<'tcx>,
1115 ) -> Option<AliasTy<'tcx>> {
1116 let Some(assoc_item) = tcx.associated_items(container_id).find_by_ident_and_kind(
1117 tcx,
1118 Ident::with_dummy_span(assoc_ty),
1119 AssocTag::Type,
1120 container_id,
1121 ) else {
1122 debug_assert!(false, "type `{assoc_ty}` not found in `{container_id:?}`");
1123 return None;
1124 };
1125 #[cfg(debug_assertions)]
1126 assert_generic_args_match(tcx, assoc_item.def_id, args);
1127
1128 let kind = if let DefKind::Impl { of_trait: false } = tcx.def_kind(tcx.parent(assoc_item.def_id)) {
1129 ty::AliasTyKind::Inherent {
1130 def_id: assoc_item.def_id,
1131 }
1132 } else {
1133 ty::AliasTyKind::Projection {
1134 def_id: assoc_item.def_id,
1135 }
1136 };
1137
1138 Some(AliasTy::new_from_args(tcx, kind, args))
1139 }
1140 helper(
1141 tcx,
1142 container_id,
1143 assoc_ty,
1144 tcx.mk_args_from_iter(args.into_iter().map(Into::into)),
1145 )
1146}
1147
1148pub fn make_normalized_projection<'tcx>(
1155 tcx: TyCtxt<'tcx>,
1156 typing_env: ty::TypingEnv<'tcx>,
1157 container_id: DefId,
1158 assoc_ty: Symbol,
1159 args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1160) -> Option<Ty<'tcx>> {
1161 fn helper<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1162 #[cfg(debug_assertions)]
1163 if let Some((i, arg)) = ty
1164 .args
1165 .iter()
1166 .enumerate()
1167 .find(|(_, arg)| arg.has_escaping_bound_vars())
1168 {
1169 debug_assert!(
1170 false,
1171 "args contain late-bound region at index `{i}` which can't be normalized.\n\
1172 use `TyCtxt::instantiate_bound_regions_with_erased`\n\
1173 note: arg is `{arg:#?}`",
1174 );
1175 return None;
1176 }
1177 match tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(Ty::new_alias(tcx, ty::IsRigid::No, ty))) {
1178 Ok(ty) => Some(ty),
1179 Err(e) => {
1180 debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1181 None
1182 },
1183 }
1184 }
1185 helper(tcx, typing_env, make_projection(tcx, container_id, assoc_ty, args)?)
1186}
1187
1188#[derive(Default, Debug)]
1191pub struct InteriorMut<'tcx> {
1192 ignored_def_ids: FxHashSet<DefId>,
1193 ignore_pointers: bool,
1194 tys: FxHashMap<Ty<'tcx>, Option<&'tcx ty::List<Ty<'tcx>>>>,
1195}
1196
1197impl<'tcx> InteriorMut<'tcx> {
1198 pub fn new(tcx: TyCtxt<'tcx>, ignore_interior_mutability: &[String]) -> Self {
1199 let ignored_def_ids = ignore_interior_mutability
1200 .iter()
1201 .flat_map(|ignored_ty| lookup_path_str(tcx, PathNS::Type, ignored_ty))
1202 .collect();
1203
1204 Self {
1205 ignored_def_ids,
1206 ..Self::default()
1207 }
1208 }
1209
1210 pub fn without_pointers(tcx: TyCtxt<'tcx>, ignore_interior_mutability: &[String]) -> Self {
1211 Self {
1212 ignore_pointers: true,
1213 ..Self::new(tcx, ignore_interior_mutability)
1214 }
1215 }
1216
1217 pub fn interior_mut_ty_chain(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<&'tcx ty::List<Ty<'tcx>>> {
1222 self.interior_mut_ty_chain_inner(cx, ty, 0)
1223 }
1224
1225 fn interior_mut_ty_chain_inner(
1226 &mut self,
1227 cx: &LateContext<'tcx>,
1228 ty: Ty<'tcx>,
1229 depth: usize,
1230 ) -> Option<&'tcx ty::List<Ty<'tcx>>> {
1231 if !cx.tcx.recursion_limit().value_within_limit(depth) {
1232 return None;
1233 }
1234
1235 match self.tys.entry(ty) {
1236 Entry::Occupied(o) => return *o.get(),
1237 Entry::Vacant(v) => v.insert(None),
1239 };
1240 let depth = depth + 1;
1241
1242 let chain = match *ty.kind() {
1243 ty::RawPtr(inner_ty, _) if !self.ignore_pointers => self.interior_mut_ty_chain_inner(cx, inner_ty, depth),
1244 ty::Ref(_, inner_ty, _) | ty::Slice(inner_ty) => self.interior_mut_ty_chain_inner(cx, inner_ty, depth),
1245 ty::Array(inner_ty, size) if size.try_to_target_usize(cx.tcx) != Some(0) => {
1246 self.interior_mut_ty_chain_inner(cx, inner_ty, depth)
1247 },
1248 ty::Tuple(fields) => fields
1249 .iter()
1250 .find_map(|ty| self.interior_mut_ty_chain_inner(cx, ty, depth)),
1251 ty::Adt(def, _) if def.is_unsafe_cell() => Some(ty::List::empty()),
1252 ty::Adt(def, args) => {
1253 let is_std_collection = matches!(
1254 cx.tcx.get_diagnostic_name(def.did()),
1255 Some(
1256 sym::LinkedList
1257 | sym::Vec
1258 | sym::VecDeque
1259 | sym::BTreeMap
1260 | sym::BTreeSet
1261 | sym::HashMap
1262 | sym::HashSet
1263 | sym::Arc
1264 | sym::Rc
1265 )
1266 );
1267
1268 if is_std_collection || def.is_box() {
1269 args.types()
1271 .find_map(|ty| self.interior_mut_ty_chain_inner(cx, ty, depth))
1272 } else if self.ignored_def_ids.contains(&def.did()) || def.is_phantom_data() {
1273 None
1274 } else {
1275 def.all_fields()
1276 .find_map(|f| self.interior_mut_ty_chain_inner(cx, f.ty(cx.tcx, args).skip_norm_wip(), depth))
1277 }
1278 },
1279 ty::Alias(_, AliasTy {
1280 kind: ty::Projection { .. },
1281 ..
1282 }) => match cx
1283 .tcx
1284 .try_normalize_erasing_regions(cx.typing_env(), Unnormalized::new_wip(ty))
1285 {
1286 Ok(normalized_ty) if ty != normalized_ty => self.interior_mut_ty_chain_inner(cx, normalized_ty, depth),
1287 _ => None,
1288 },
1289 _ => None,
1290 };
1291
1292 chain.map(|chain| {
1293 let list = cx.tcx.mk_type_list_from_iter(chain.iter().chain([ty]));
1294 self.tys.insert(ty, Some(list));
1295 list
1296 })
1297 }
1298
1299 pub fn is_interior_mut_ty(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1302 self.interior_mut_ty_chain(cx, ty).is_some()
1303 }
1304}
1305
1306pub fn make_normalized_projection_with_regions<'tcx>(
1307 tcx: TyCtxt<'tcx>,
1308 typing_env: ty::TypingEnv<'tcx>,
1309 container_id: DefId,
1310 assoc_ty: Symbol,
1311 args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1312) -> Option<Ty<'tcx>> {
1313 fn helper<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1314 #[cfg(debug_assertions)]
1315 if let Some((i, arg)) = ty
1316 .args
1317 .iter()
1318 .enumerate()
1319 .find(|(_, arg)| arg.has_escaping_bound_vars())
1320 {
1321 debug_assert!(
1322 false,
1323 "args contain late-bound region at index `{i}` which can't be normalized.\n\
1324 use `TyCtxt::instantiate_bound_regions_with_erased`\n\
1325 note: arg is `{arg:#?}`",
1326 );
1327 return None;
1328 }
1329 let cause = ObligationCause::dummy();
1330 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
1331 match infcx.at(&cause, param_env).query_normalize(Ty::new_alias(tcx, ty::IsRigid::No, ty)) {
1332 Ok(ty) => Some(ty.value),
1333 Err(e) => {
1334 debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1335 None
1336 },
1337 }
1338 }
1339 helper(tcx, typing_env, make_projection(tcx, container_id, assoc_ty, args)?)
1340}
1341
1342pub fn normalize_with_regions<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1343 let cause = ObligationCause::dummy();
1344 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
1345 infcx
1346 .at(&cause, param_env)
1347 .query_normalize(ty)
1348 .map_or(ty, |ty| ty.value)
1349}
1350
1351pub fn is_manually_drop(ty: Ty<'_>) -> bool {
1353 ty.ty_adt_def().is_some_and(AdtDef::is_manually_drop)
1354}
1355
1356pub fn deref_chain<'cx, 'tcx>(cx: &'cx LateContext<'tcx>, ty: Ty<'tcx>) -> impl Iterator<Item = Ty<'tcx>> + 'cx {
1358 iter::successors(Some(ty), |&ty| {
1359 if let Some(deref_did) = cx.tcx.lang_items().deref_trait()
1360 && implements_trait(cx, ty, deref_did, &[])
1361 {
1362 make_normalized_projection(cx.tcx, cx.typing_env(), deref_did, sym::Target, [ty])
1363 } else {
1364 None
1365 }
1366 })
1367}
1368
1369pub fn get_adt_inherent_method<'a>(cx: &'a LateContext<'_>, ty: Ty<'_>, method_name: Symbol) -> Option<&'a AssocItem> {
1374 let ty_did = ty.ty_adt_def().map(AdtDef::did)?;
1375 cx.tcx.inherent_impls(ty_did).iter().find_map(|&did| {
1376 cx.tcx
1377 .associated_items(did)
1378 .filter_by_name_unhygienic(method_name)
1379 .next()
1380 .filter(|item| item.tag() == AssocTag::Fn)
1381 })
1382}
1383
1384pub fn get_field_by_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
1386 match *ty.kind() {
1387 ty::Adt(def, args) if def.is_union() || def.is_struct() => def
1388 .non_enum_variant()
1389 .fields
1390 .iter()
1391 .find(|f| f.name == name)
1392 .map(|f| f.ty(tcx, args).skip_norm_wip()),
1393 ty::Tuple(args) => name.as_str().parse::<usize>().ok().and_then(|i| args.get(i).copied()),
1394 _ => None,
1395 }
1396}
1397
1398pub fn get_field_def_id_by_name(ty: Ty<'_>, name: Symbol) -> Option<DefId> {
1399 let ty::Adt(adt_def, ..) = ty.kind() else { return None };
1400 adt_def
1401 .all_fields()
1402 .find_map(|field| if field.name == name { Some(field.did) } else { None })
1403}
1404
1405pub fn option_arg_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1407 match *ty.kind() {
1408 ty::Adt(adt, args)
1409 if let [arg] = &**args
1410 && let Some(arg) = arg.as_type()
1411 && adt.is_diag_item(cx, sym::Option) =>
1412 {
1413 Some(arg)
1414 },
1415 _ => None,
1416 }
1417}
1418
1419pub fn option_or_result_arg_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1421 match ty.kind() {
1422 ty::Adt(adt, args) if matches!(adt.opt_diag_name(cx), Some(sym::Option | sym::Result)) => Some(args.type_at(0)),
1423 _ => None,
1424 }
1425}
1426
1427pub fn has_non_owning_mutable_access<'tcx>(cx: &LateContext<'tcx>, iter_ty: Ty<'tcx>) -> bool {
1432 fn normalize_ty<'tcx>(cx: &LateContext<'tcx>, ty: Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
1433 cx.tcx
1434 .try_normalize_erasing_regions(cx.typing_env(), ty)
1435 .unwrap_or(ty.skip_norm_wip())
1436 }
1437
1438 fn has_non_owning_mutable_access_inner<'tcx>(
1443 cx: &LateContext<'tcx>,
1444 phantoms: &mut FxHashSet<Ty<'tcx>>,
1445 ty: Ty<'tcx>,
1446 ) -> bool {
1447 match ty.kind() {
1448 ty::Adt(adt_def, args) if adt_def.is_phantom_data() => {
1449 phantoms.insert(ty)
1450 && args
1451 .types()
1452 .any(|arg_ty| has_non_owning_mutable_access_inner(cx, phantoms, arg_ty))
1453 },
1454 ty::Adt(adt_def, args) => adt_def.all_fields().any(|field| {
1455 has_non_owning_mutable_access_inner(cx, phantoms, normalize_ty(cx, field.ty(cx.tcx, args)))
1456 }),
1457 ty::Array(elem_ty, _) | ty::Slice(elem_ty) => has_non_owning_mutable_access_inner(cx, phantoms, *elem_ty),
1458 ty::RawPtr(pointee_ty, mutability) | ty::Ref(_, pointee_ty, mutability) => {
1459 mutability.is_mut() || !pointee_ty.is_freeze(cx.tcx, cx.typing_env())
1460 },
1461 ty::Closure(_, closure_args) => {
1462 matches!(closure_args.types().next_back(),
1463 Some(captures) if has_non_owning_mutable_access_inner(cx, phantoms, captures))
1464 },
1465 ty::Tuple(tuple_args) => tuple_args
1466 .iter()
1467 .any(|arg_ty| has_non_owning_mutable_access_inner(cx, phantoms, arg_ty)),
1468 _ => false,
1469 }
1470 }
1471
1472 let mut phantoms = FxHashSet::default();
1473 has_non_owning_mutable_access_inner(cx, &mut phantoms, iter_ty)
1474}
1475
1476pub fn is_slice_like<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1478 ty.is_slice() || ty.is_array() || ty.is_diag_item(cx, sym::Vec)
1479}
1480
1481pub fn get_field_idx_by_name(ty: Ty<'_>, name: Symbol) -> Option<usize> {
1482 match *ty.kind() {
1483 ty::Adt(def, _) if def.is_union() || def.is_struct() => {
1484 def.non_enum_variant().fields.iter().position(|f| f.name == name)
1485 },
1486 ty::Tuple(_) => name.as_str().parse::<usize>().ok(),
1487 _ => None,
1488 }
1489}
1490
1491pub fn adjust_derefs_manually_drop<'tcx>(adjustments: &'tcx [Adjustment<'tcx>], mut ty: Ty<'tcx>) -> bool {
1493 adjustments.iter().any(|a| {
1494 let ty = mem::replace(&mut ty, a.target);
1495 matches!(a.kind, Adjust::Deref(DerefAdjustKind::Overloaded(op)) if op.mutbl == Mutability::Mut)
1496 && is_manually_drop(ty)
1497 })
1498}