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