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