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, 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;
33use std::{iter, mem};
34
35use crate::paths::{PathNS, lookup_path_str};
36use crate::res::{MaybeDef, MaybeQPath};
37use crate::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.all_fields().any(|f| !is_copy(cx, f.ty(cx.tcx, subs))),
70 _ => true,
71 }
72}
73
74pub fn contains_adt_constructor<'tcx>(ty: Ty<'tcx>, adt: AdtDef<'tcx>) -> bool {
77 ty.walk().any(|inner| match inner.kind() {
78 GenericArgKind::Type(inner_ty) => inner_ty.ty_adt_def() == Some(adt),
79 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
80 })
81}
82
83pub fn contains_ty_adt_constructor_opaque<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, needle: Ty<'tcx>) -> bool {
89 fn contains_ty_adt_constructor_opaque_inner<'tcx>(
90 cx: &LateContext<'tcx>,
91 ty: Ty<'tcx>,
92 needle: Ty<'tcx>,
93 seen: &mut FxHashSet<DefId>,
94 ) -> bool {
95 ty.walk().any(|inner| match inner.kind() {
96 GenericArgKind::Type(inner_ty) => {
97 if inner_ty == needle {
98 return true;
99 }
100
101 if inner_ty.ty_adt_def() == needle.ty_adt_def() {
102 return true;
103 }
104
105 if let ty::Alias(ty::Opaque, AliasTy { def_id, .. }) = *inner_ty.kind() {
106 if !seen.insert(def_id) {
107 return false;
108 }
109
110 for (predicate, _span) in cx.tcx.explicit_item_self_bounds(def_id).iter_identity_copied() {
111 match predicate.kind().skip_binder() {
112 ty::ClauseKind::Trait(trait_predicate)
115 if trait_predicate
116 .trait_ref
117 .args
118 .types()
119 .skip(1) .any(|ty| contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen)) =>
121 {
122 return true;
123 },
124 ty::ClauseKind::Projection(projection_predicate) => {
127 if let ty::TermKind::Ty(ty) = projection_predicate.term.kind()
128 && contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen)
129 {
130 return true;
131 }
132 },
133 _ => (),
134 }
135 }
136 }
137
138 false
139 },
140 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
141 })
142 }
143
144 let mut seen = FxHashSet::default();
147 contains_ty_adt_constructor_opaque_inner(cx, ty, needle, &mut seen)
148}
149
150pub fn get_iterator_item_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
153 cx.tcx
154 .get_diagnostic_item(sym::Iterator)
155 .and_then(|iter_did| cx.get_associated_type(ty, iter_did, sym::Item))
156}
157
158pub fn should_call_clone_as_function(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
164 matches!(
165 ty.opt_diag_name(cx),
166 Some(sym::Arc | sym::ArcWeak | sym::Rc | sym::RcWeak)
167 )
168}
169
170pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<Symbol> {
172 let into_iter_collections: &[Symbol] = &[
176 sym::Vec,
177 sym::Option,
178 sym::Result,
179 sym::BTreeMap,
180 sym::BTreeSet,
181 sym::VecDeque,
182 sym::LinkedList,
183 sym::BinaryHeap,
184 sym::HashSet,
185 sym::HashMap,
186 sym::PathBuf,
187 sym::Path,
188 sym::Receiver,
189 ];
190
191 let ty_to_check = match probably_ref_ty.kind() {
192 ty::Ref(_, ty_to_check, _) => *ty_to_check,
193 _ => probably_ref_ty,
194 };
195
196 let def_id = match ty_to_check.kind() {
197 ty::Array(..) => return Some(sym::array),
198 ty::Slice(..) => return Some(sym::slice),
199 ty::Adt(adt, _) => adt.did(),
200 _ => return None,
201 };
202
203 for &name in into_iter_collections {
204 if cx.tcx.is_diagnostic_item(name, def_id) {
205 return Some(cx.tcx.item_name(def_id));
206 }
207 }
208 None
209}
210
211pub fn implements_trait<'tcx>(
218 cx: &LateContext<'tcx>,
219 ty: Ty<'tcx>,
220 trait_id: DefId,
221 args: &[GenericArg<'tcx>],
222) -> bool {
223 implements_trait_with_env_from_iter(
224 cx.tcx,
225 cx.typing_env(),
226 ty,
227 trait_id,
228 None,
229 args.iter().map(|&x| Some(x)),
230 )
231}
232
233pub fn implements_trait_with_env<'tcx>(
238 tcx: TyCtxt<'tcx>,
239 typing_env: ty::TypingEnv<'tcx>,
240 ty: Ty<'tcx>,
241 trait_id: DefId,
242 callee_id: Option<DefId>,
243 args: &[GenericArg<'tcx>],
244) -> bool {
245 implements_trait_with_env_from_iter(tcx, typing_env, ty, trait_id, callee_id, args.iter().map(|&x| Some(x)))
246}
247
248pub fn implements_trait_with_env_from_iter<'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: impl IntoIterator<Item = impl Into<Option<GenericArg<'tcx>>>>,
256) -> bool {
257 assert!(!ty.has_infer());
259
260 if let Some(callee_id) = callee_id {
264 let _ = tcx.hir_body_owner_kind(callee_id);
265 }
266
267 let ty = tcx.erase_and_anonymize_regions(ty);
268 if ty.has_escaping_bound_vars() {
269 return false;
270 }
271
272 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
273 let args = args
274 .into_iter()
275 .map(|arg| arg.into().unwrap_or_else(|| infcx.next_ty_var(DUMMY_SP).into()))
276 .collect::<Vec<_>>();
277
278 let trait_ref = TraitRef::new(tcx, trait_id, [GenericArg::from(ty)].into_iter().chain(args));
279
280 debug_assert_matches!(
281 tcx.def_kind(trait_id),
282 DefKind::Trait | DefKind::TraitAlias,
283 "`DefId` must belong to a trait or trait alias"
284 );
285 #[cfg(debug_assertions)]
286 assert_generic_args_match(tcx, trait_id, trait_ref.args);
287
288 let obligation = Obligation {
289 cause: ObligationCause::dummy(),
290 param_env,
291 recursion_depth: 0,
292 predicate: trait_ref.upcast(tcx),
293 };
294 infcx
295 .evaluate_obligation(&obligation)
296 .is_ok_and(EvaluationResult::must_apply_modulo_regions)
297}
298
299pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
301 match ty.ty_adt_def() {
302 Some(def) => def.has_dtor(cx.tcx),
303 None => false,
304 }
305}
306
307pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
311 match ty.kind() {
312 ty::Adt(adt, args) => match cx.tcx.get_diagnostic_name(adt.did()) {
313 Some(sym::Result) if args.type_at(1).is_privately_uninhabited(cx.tcx, cx.typing_env()) => {
314 is_must_use_ty(cx, args.type_at(0))
315 },
316 Some(sym::ControlFlow) if args.type_at(0).is_privately_uninhabited(cx.tcx, cx.typing_env()) => {
317 is_must_use_ty(cx, args.type_at(1))
318 },
319 _ => find_attr!(cx.tcx, adt.did(), MustUse { .. }),
320 },
321 ty::Foreign(did) => find_attr!(cx.tcx, *did, MustUse { .. }),
322 ty::Slice(ty) | ty::Array(ty, _) | ty::RawPtr(ty, _) | ty::Ref(_, ty, _) => {
323 is_must_use_ty(cx, *ty)
326 },
327 ty::Tuple(args) => args.iter().any(|ty| is_must_use_ty(cx, ty)),
328 ty::Alias(ty::Opaque, AliasTy { def_id, .. }) => {
329 for (predicate, _) in cx.tcx.explicit_item_self_bounds(*def_id).skip_binder() {
330 if let ty::ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder()
331 && find_attr!(cx.tcx, trait_predicate.trait_ref.def_id, MustUse { .. })
332 {
333 return true;
334 }
335 }
336 false
337 },
338 ty::Dynamic(binder, _) => {
339 for predicate in *binder {
340 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder()
341 && find_attr!(cx.tcx, trait_ref.def_id, MustUse { .. })
342 {
343 return true;
344 }
345 }
346 false
347 },
348 _ => false,
349 }
350}
351
352pub fn is_non_aggregate_primitive_type(ty: Ty<'_>) -> bool {
358 matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_))
359}
360
361pub fn is_recursively_primitive_type(ty: Ty<'_>) -> bool {
364 match *ty.kind() {
365 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => true,
366 ty::Ref(_, inner, _) if inner.is_str() => true,
367 ty::Array(inner_type, _) | ty::Slice(inner_type) => is_recursively_primitive_type(inner_type),
368 ty::Tuple(inner_types) => inner_types.iter().all(is_recursively_primitive_type),
369 _ => false,
370 }
371}
372
373pub fn is_isize_or_usize(typ: Ty<'_>) -> bool {
375 matches!(typ.kind(), ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize))
376}
377
378pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
383 fn needs_ordered_drop_inner<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, seen: &mut FxHashSet<Ty<'tcx>>) -> bool {
384 if !seen.insert(ty) {
385 return false;
386 }
387 if !ty.has_significant_drop(cx.tcx, cx.typing_env()) {
388 false
389 }
390 else if ty.is_lang_item(cx, LangItem::OwnedBox)
392 || matches!(
393 ty.opt_diag_name(cx),
394 Some(sym::HashSet | sym::Rc | sym::Arc | sym::cstring_type | sym::RcWeak | sym::ArcWeak)
395 )
396 {
397 if let ty::Adt(_, subs) = ty.kind() {
399 subs.types().any(|ty| needs_ordered_drop_inner(cx, ty, seen))
400 } else {
401 true
402 }
403 } else if !cx
404 .tcx
405 .lang_items()
406 .drop_trait()
407 .is_some_and(|id| implements_trait(cx, ty, id, &[]))
408 {
409 match ty.kind() {
412 ty::Tuple(fields) => fields.iter().any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
413 ty::Array(ty, _) => needs_ordered_drop_inner(cx, *ty, seen),
414 ty::Adt(adt, subs) => adt
415 .all_fields()
416 .map(|f| f.ty(cx.tcx, subs))
417 .any(|ty| needs_ordered_drop_inner(cx, ty, seen)),
418 _ => true,
419 }
420 } else {
421 true
422 }
423 }
424
425 needs_ordered_drop_inner(cx, ty, &mut FxHashSet::default())
426}
427
428pub fn is_unsafe_fn<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
430 ty.is_fn() && ty.fn_sig(cx.tcx).safety().is_unsafe()
431}
432
433pub fn peel_and_count_ty_refs(mut ty: Ty<'_>) -> (Ty<'_>, usize, Option<Mutability>) {
437 let mut count = 0;
438 let mut mutbl = None;
439 while let ty::Ref(_, dest_ty, m) = ty.kind() {
440 ty = *dest_ty;
441 count += 1;
442 mutbl.replace(mutbl.map_or(*m, |mutbl: Mutability| mutbl.min(*m)));
443 }
444 (ty, count, mutbl)
445}
446
447pub fn peel_n_ty_refs(mut ty: Ty<'_>, n: usize) -> (Ty<'_>, Option<Mutability>) {
450 let mut mutbl = None;
451 for _ in 0..n {
452 if let ty::Ref(_, dest_ty, m) = ty.kind() {
453 ty = *dest_ty;
454 mutbl.replace(mutbl.map_or(*m, |mutbl: Mutability| mutbl.min(*m)));
455 } else {
456 break;
457 }
458 }
459 (ty, mutbl)
460}
461
462pub fn same_type_modulo_regions<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
474 match (&a.kind(), &b.kind()) {
475 (&ty::Adt(did_a, args_a), &ty::Adt(did_b, args_b)) => {
476 if did_a != did_b {
477 return false;
478 }
479
480 iter::zip(*args_a, *args_b).all(|(arg_a, arg_b)| match (arg_a.kind(), arg_b.kind()) {
481 (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b,
482 (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => {
483 same_type_modulo_regions(type_a, type_b)
484 },
485 _ => true,
486 })
487 },
488 _ => a == b,
489 }
490}
491
492pub fn is_uninit_value_valid_for_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
494 let typing_env = cx.typing_env().with_post_analysis_normalized(cx.tcx);
495 cx.tcx
496 .check_validity_requirement((ValidityRequirement::Uninit, typing_env.as_query_input(ty)))
497 .unwrap_or_else(|_| is_uninit_value_valid_for_ty_fallback(cx, ty))
498}
499
500fn is_uninit_value_valid_for_ty_fallback<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
502 match *ty.kind() {
503 ty::Array(component, _) => is_uninit_value_valid_for_ty(cx, component),
505 ty::Tuple(types) => types.iter().all(|ty| is_uninit_value_valid_for_ty(cx, ty)),
507 ty::Adt(adt, _) if adt.is_union() => true,
510 ty::Adt(adt, args) if adt.is_struct() => adt
514 .all_fields()
515 .all(|field| is_uninit_value_valid_for_ty(cx, field.ty(cx.tcx, args))),
516 _ => false,
518 }
519}
520
521pub fn all_predicates_of(tcx: TyCtxt<'_>, id: DefId) -> impl Iterator<Item = &(ty::Clause<'_>, Span)> {
523 let mut next_id = Some(id);
524 iter::from_fn(move || {
525 next_id.take().map(|id| {
526 let preds = tcx.predicates_of(id);
527 next_id = preds.parent;
528 preds.predicates.iter()
529 })
530 })
531 .flatten()
532}
533
534#[derive(Clone, Copy, Debug)]
536pub enum ExprFnSig<'tcx> {
537 Sig(Binder<'tcx, FnSig<'tcx>>, Option<DefId>),
538 Closure(Option<&'tcx FnDecl<'tcx>>, Binder<'tcx, FnSig<'tcx>>),
539 Trait(Binder<'tcx, Ty<'tcx>>, Option<Binder<'tcx, Ty<'tcx>>>, Option<DefId>),
540}
541impl<'tcx> ExprFnSig<'tcx> {
542 pub fn input(self, i: usize) -> Option<Binder<'tcx, Ty<'tcx>>> {
545 match self {
546 Self::Sig(sig, _) => {
547 if sig.c_variadic() {
548 sig.inputs().map_bound(|inputs| inputs.get(i).copied()).transpose()
549 } else {
550 Some(sig.input(i))
551 }
552 },
553 Self::Closure(_, sig) => Some(sig.input(0).map_bound(|ty| ty.tuple_fields()[i])),
554 Self::Trait(inputs, _, _) => Some(inputs.map_bound(|ty| ty.tuple_fields()[i])),
555 }
556 }
557
558 pub fn input_with_hir(self, i: usize) -> Option<(Option<&'tcx hir::Ty<'tcx>>, Binder<'tcx, Ty<'tcx>>)> {
562 match self {
563 Self::Sig(sig, _) => {
564 if sig.c_variadic() {
565 sig.inputs()
566 .map_bound(|inputs| inputs.get(i).copied())
567 .transpose()
568 .map(|arg| (None, arg))
569 } else {
570 Some((None, sig.input(i)))
571 }
572 },
573 Self::Closure(decl, sig) => Some((
574 decl.and_then(|decl| decl.inputs.get(i)),
575 sig.input(0).map_bound(|ty| ty.tuple_fields()[i]),
576 )),
577 Self::Trait(inputs, _, _) => Some((None, inputs.map_bound(|ty| ty.tuple_fields()[i]))),
578 }
579 }
580
581 pub fn output(self) -> Option<Binder<'tcx, Ty<'tcx>>> {
584 match self {
585 Self::Sig(sig, _) | Self::Closure(_, sig) => Some(sig.output()),
586 Self::Trait(_, output, _) => output,
587 }
588 }
589
590 pub fn predicates_id(&self) -> Option<DefId> {
591 if let ExprFnSig::Sig(_, id) | ExprFnSig::Trait(_, _, id) = *self {
592 id
593 } else {
594 None
595 }
596 }
597}
598
599pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> {
601 if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = expr.res(cx) {
602 Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).instantiate_identity(), Some(id)))
603 } else {
604 ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs())
605 }
606}
607
608pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'tcx>> {
610 if let Some(boxed_ty) = ty.boxed_ty() {
611 return ty_sig(cx, boxed_ty);
612 }
613 match *ty.kind() {
614 ty::Closure(id, subs) => {
615 let decl = id
616 .as_local()
617 .and_then(|id| cx.tcx.hir_fn_decl_by_hir_id(cx.tcx.local_def_id_to_hir_id(id)));
618 Some(ExprFnSig::Closure(decl, subs.as_closure().sig()))
619 },
620 ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).instantiate(cx.tcx, subs), Some(id))),
621 ty::Alias(ty::Opaque, AliasTy { def_id, args, .. }) => sig_from_bounds(
622 cx,
623 ty,
624 cx.tcx.item_self_bounds(def_id).iter_instantiated(cx.tcx, args),
625 cx.tcx.opt_parent(def_id),
626 ),
627 ty::FnPtr(sig_tys, hdr) => Some(ExprFnSig::Sig(sig_tys.with(hdr), None)),
628 ty::Dynamic(bounds, _) => {
629 let lang_items = cx.tcx.lang_items();
630 match bounds.principal() {
631 Some(bound)
632 if Some(bound.def_id()) == lang_items.fn_trait()
633 || Some(bound.def_id()) == lang_items.fn_once_trait()
634 || Some(bound.def_id()) == lang_items.fn_mut_trait() =>
635 {
636 let output = bounds
637 .projection_bounds()
638 .find(|p| lang_items.fn_once_output().is_some_and(|id| id == p.item_def_id()))
639 .map(|p| p.map_bound(|p| p.term.expect_type()));
640 Some(ExprFnSig::Trait(bound.map_bound(|b| b.args.type_at(0)), output, None))
641 },
642 _ => None,
643 }
644 },
645 ty::Alias(ty::Projection, proj) => match cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty) {
646 Ok(normalized_ty) if normalized_ty != ty => ty_sig(cx, normalized_ty),
647 _ => sig_for_projection(cx, proj).or_else(|| sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None)),
648 },
649 ty::Param(_) => sig_from_bounds(cx, ty, cx.param_env.caller_bounds(), None),
650 _ => None,
651 }
652}
653
654fn sig_from_bounds<'tcx>(
655 cx: &LateContext<'tcx>,
656 ty: Ty<'tcx>,
657 predicates: impl IntoIterator<Item = ty::Clause<'tcx>>,
658 predicates_id: Option<DefId>,
659) -> Option<ExprFnSig<'tcx>> {
660 let mut inputs = None;
661 let mut output = None;
662 let lang_items = cx.tcx.lang_items();
663
664 for pred in predicates {
665 match pred.kind().skip_binder() {
666 ty::ClauseKind::Trait(p)
667 if (lang_items.fn_trait() == Some(p.def_id())
668 || lang_items.fn_mut_trait() == Some(p.def_id())
669 || lang_items.fn_once_trait() == Some(p.def_id()))
670 && p.self_ty() == ty =>
671 {
672 let i = pred.kind().rebind(p.trait_ref.args.type_at(1));
673 if inputs.is_some_and(|inputs| i != inputs) {
674 return None;
676 }
677 inputs = Some(i);
678 },
679 ty::ClauseKind::Projection(p)
680 if Some(p.projection_term.def_id) == lang_items.fn_once_output()
681 && p.projection_term.self_ty() == ty =>
682 {
683 if output.is_some() {
684 return None;
686 }
687 output = Some(pred.kind().rebind(p.term.expect_type()));
688 },
689 _ => (),
690 }
691 }
692
693 inputs.map(|ty| ExprFnSig::Trait(ty, output, predicates_id))
694}
695
696fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: AliasTy<'tcx>) -> Option<ExprFnSig<'tcx>> {
697 let mut inputs = None;
698 let mut output = None;
699 let lang_items = cx.tcx.lang_items();
700
701 for (pred, _) in cx
702 .tcx
703 .explicit_item_bounds(ty.def_id)
704 .iter_instantiated_copied(cx.tcx, ty.args)
705 {
706 match pred.kind().skip_binder() {
707 ty::ClauseKind::Trait(p)
708 if (lang_items.fn_trait() == Some(p.def_id())
709 || lang_items.fn_mut_trait() == Some(p.def_id())
710 || lang_items.fn_once_trait() == Some(p.def_id())) =>
711 {
712 let i = pred.kind().rebind(p.trait_ref.args.type_at(1));
713
714 if inputs.is_some_and(|inputs| inputs != i) {
715 return None;
717 }
718 inputs = Some(i);
719 },
720 ty::ClauseKind::Projection(p) if Some(p.projection_term.def_id) == lang_items.fn_once_output() => {
721 if output.is_some() {
722 return None;
724 }
725 output = pred.kind().rebind(p.term.as_type()).transpose();
726 },
727 _ => (),
728 }
729 }
730
731 inputs.map(|ty| ExprFnSig::Trait(ty, output, None))
732}
733
734#[derive(Clone, Copy)]
735pub enum EnumValue {
736 Unsigned(u128),
737 Signed(i128),
738}
739impl core::ops::Add<u32> for EnumValue {
740 type Output = Self;
741 fn add(self, n: u32) -> Self::Output {
742 match self {
743 Self::Unsigned(x) => Self::Unsigned(x + u128::from(n)),
744 Self::Signed(x) => Self::Signed(x + i128::from(n)),
745 }
746 }
747}
748
749pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> {
751 if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) {
752 match tcx.type_of(id).instantiate_identity().kind() {
753 ty::Int(_) => Some(EnumValue::Signed(value.to_int(value.size()))),
754 ty::Uint(_) => Some(EnumValue::Unsigned(value.to_uint(value.size()))),
755 _ => None,
756 }
757 } else {
758 None
759 }
760}
761
762pub fn get_discriminant_value(tcx: TyCtxt<'_>, adt: AdtDef<'_>, i: VariantIdx) -> EnumValue {
764 let variant = &adt.variant(i);
765 match variant.discr {
766 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap(),
767 VariantDiscr::Relative(x) => match adt.variant((i.as_usize() - x as usize).into()).discr {
768 VariantDiscr::Explicit(id) => read_explicit_enum_value(tcx, id).unwrap() + x,
769 VariantDiscr::Relative(_) => EnumValue::Unsigned(x.into()),
770 },
771 }
772}
773
774pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
777 if let ty::Adt(adt, _) = ty.kind()
778 && let &[krate, .., name] = &*cx.get_def_path(adt.did())
779 && let sym::libc | sym::core | sym::std = krate
780 && name == sym::c_void
781 {
782 true
783 } else {
784 false
785 }
786}
787
788pub fn for_each_top_level_late_bound_region<'cx, B>(
789 ty: Ty<'cx>,
790 f: impl FnMut(BoundRegion<'cx>) -> ControlFlow<B>,
791) -> ControlFlow<B> {
792 struct V<F> {
793 index: u32,
794 f: F,
795 }
796 impl<'tcx, B, F: FnMut(BoundRegion<'tcx>) -> ControlFlow<B>> TypeVisitor<TyCtxt<'tcx>> for V<F> {
797 type Result = ControlFlow<B>;
798 fn visit_region(&mut self, r: Region<'tcx>) -> Self::Result {
799 if let RegionKind::ReBound(BoundVarIndexKind::Bound(idx), bound) = r.kind()
800 && idx.as_u32() == self.index
801 {
802 (self.f)(bound)
803 } else {
804 ControlFlow::Continue(())
805 }
806 }
807 fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(&mut self, t: &Binder<'tcx, T>) -> Self::Result {
808 self.index += 1;
809 let res = t.super_visit_with(self);
810 self.index -= 1;
811 res
812 }
813 }
814 ty.visit_with(&mut V { index: 0, f })
815}
816
817pub struct AdtVariantInfo {
818 pub ind: usize,
819 pub size: u64,
820
821 pub fields_size: Vec<(usize, u64)>,
823}
824
825impl AdtVariantInfo {
826 pub fn new<'tcx>(cx: &LateContext<'tcx>, adt: AdtDef<'tcx>, subst: GenericArgsRef<'tcx>) -> Vec<Self> {
828 let mut variants_size = adt
829 .variants()
830 .iter()
831 .enumerate()
832 .map(|(i, variant)| {
833 let mut fields_size = variant
834 .fields
835 .iter()
836 .enumerate()
837 .map(|(i, f)| (i, approx_ty_size(cx, f.ty(cx.tcx, subst))))
838 .collect::<Vec<_>>();
839 fields_size.sort_by_key(|(_, a_size)| *a_size);
840
841 Self {
842 ind: i,
843 size: fields_size.iter().map(|(_, size)| size).sum(),
844 fields_size,
845 }
846 })
847 .collect::<Vec<_>>();
848 variants_size.sort_by_key(|b| std::cmp::Reverse(b.size));
849 variants_size
850 }
851}
852
853pub fn adt_and_variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option<(AdtDef<'tcx>, &'tcx VariantDef)> {
855 match res {
856 Res::Def(DefKind::Struct, id) => {
857 let adt = cx.tcx.adt_def(id);
858 Some((adt, adt.non_enum_variant()))
859 },
860 Res::Def(DefKind::Variant, id) => {
861 let adt = cx.tcx.adt_def(cx.tcx.parent(id));
862 Some((adt, adt.variant_with_id(id)))
863 },
864 Res::Def(DefKind::Ctor(CtorOf::Struct, _), id) => {
865 let adt = cx.tcx.adt_def(cx.tcx.parent(id));
866 Some((adt, adt.non_enum_variant()))
867 },
868 Res::Def(DefKind::Ctor(CtorOf::Variant, _), id) => {
869 let var_id = cx.tcx.parent(id);
870 let adt = cx.tcx.adt_def(cx.tcx.parent(var_id));
871 Some((adt, adt.variant_with_id(var_id)))
872 },
873 Res::SelfCtor(id) => {
874 let adt = cx.tcx.type_of(id).instantiate_identity().ty_adt_def().unwrap();
875 Some((adt, adt.non_enum_variant()))
876 },
877 _ => None,
878 }
879}
880
881pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 {
884 use rustc_middle::ty::layout::LayoutOf;
885 match (cx.layout_of(ty).map(|layout| layout.size.bytes()), ty.kind()) {
886 (Ok(size), _) => size,
887 (Err(_), ty::Tuple(list)) => list.iter().map(|t| approx_ty_size(cx, t)).sum(),
888 (Err(_), ty::Array(t, n)) => n.try_to_target_usize(cx.tcx).unwrap_or_default() * approx_ty_size(cx, *t),
889 (Err(_), ty::Adt(def, subst)) if def.is_struct() => def
890 .variants()
891 .iter()
892 .map(|v| {
893 v.fields
894 .iter()
895 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
896 .sum::<u64>()
897 })
898 .sum(),
899 (Err(_), ty::Adt(def, subst)) if def.is_enum() => def
900 .variants()
901 .iter()
902 .map(|v| {
903 v.fields
904 .iter()
905 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
906 .sum::<u64>()
907 })
908 .max()
909 .unwrap_or_default(),
910 (Err(_), ty::Adt(def, subst)) if def.is_union() => def
911 .variants()
912 .iter()
913 .map(|v| {
914 v.fields
915 .iter()
916 .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst)))
917 .max()
918 .unwrap_or_default()
919 })
920 .max()
921 .unwrap_or_default(),
922 (Err(_), _) => 0,
923 }
924}
925
926#[cfg(debug_assertions)]
927fn assert_generic_args_match<'tcx>(tcx: TyCtxt<'tcx>, did: DefId, args: &[GenericArg<'tcx>]) {
929 use itertools::Itertools;
930 let g = tcx.generics_of(did);
931 let parent = g.parent.map(|did| tcx.generics_of(did));
932 let count = g.parent_count + g.own_params.len();
933 let params = parent
934 .map_or([].as_slice(), |p| p.own_params.as_slice())
935 .iter()
936 .chain(&g.own_params)
937 .map(|x| &x.kind);
938
939 assert!(
940 count == args.len(),
941 "wrong number of arguments for `{did:?}`: expected `{count}`, found {}\n\
942 note: the expected arguments are: `[{}]`\n\
943 the given arguments are: `{args:#?}`",
944 args.len(),
945 params.clone().map(ty::GenericParamDefKind::descr).format(", "),
946 );
947
948 if let Some((idx, (param, arg))) =
949 params
950 .clone()
951 .zip(args.iter().map(|&x| x.kind()))
952 .enumerate()
953 .find(|(_, (param, arg))| match (param, arg) {
954 (ty::GenericParamDefKind::Lifetime, GenericArgKind::Lifetime(_))
955 | (ty::GenericParamDefKind::Type { .. }, GenericArgKind::Type(_))
956 | (ty::GenericParamDefKind::Const { .. }, GenericArgKind::Const(_)) => false,
957 (
958 ty::GenericParamDefKind::Lifetime
959 | ty::GenericParamDefKind::Type { .. }
960 | ty::GenericParamDefKind::Const { .. },
961 _,
962 ) => true,
963 })
964 {
965 panic!(
966 "incorrect argument for `{did:?}` at index `{idx}`: expected a {}, found `{arg:?}`\n\
967 note: the expected arguments are `[{}]`\n\
968 the given arguments are `{args:#?}`",
969 param.descr(),
970 params.clone().map(ty::GenericParamDefKind::descr).format(", "),
971 );
972 }
973}
974
975pub fn is_never_like(ty: Ty<'_>) -> bool {
977 ty.is_never() || (ty.is_enum() && ty.ty_adt_def().is_some_and(|def| def.variants().is_empty()))
978}
979
980pub fn make_projection<'tcx>(
988 tcx: TyCtxt<'tcx>,
989 container_id: DefId,
990 assoc_ty: Symbol,
991 args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
992) -> Option<AliasTy<'tcx>> {
993 fn helper<'tcx>(
994 tcx: TyCtxt<'tcx>,
995 container_id: DefId,
996 assoc_ty: Symbol,
997 args: GenericArgsRef<'tcx>,
998 ) -> Option<AliasTy<'tcx>> {
999 let Some(assoc_item) = tcx.associated_items(container_id).find_by_ident_and_kind(
1000 tcx,
1001 Ident::with_dummy_span(assoc_ty),
1002 AssocTag::Type,
1003 container_id,
1004 ) else {
1005 debug_assert!(false, "type `{assoc_ty}` not found in `{container_id:?}`");
1006 return None;
1007 };
1008 #[cfg(debug_assertions)]
1009 assert_generic_args_match(tcx, assoc_item.def_id, args);
1010
1011 Some(AliasTy::new_from_args(tcx, assoc_item.def_id, args))
1012 }
1013 helper(
1014 tcx,
1015 container_id,
1016 assoc_ty,
1017 tcx.mk_args_from_iter(args.into_iter().map(Into::into)),
1018 )
1019}
1020
1021pub fn make_normalized_projection<'tcx>(
1028 tcx: TyCtxt<'tcx>,
1029 typing_env: ty::TypingEnv<'tcx>,
1030 container_id: DefId,
1031 assoc_ty: Symbol,
1032 args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1033) -> Option<Ty<'tcx>> {
1034 fn helper<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1035 #[cfg(debug_assertions)]
1036 if let Some((i, arg)) = ty
1037 .args
1038 .iter()
1039 .enumerate()
1040 .find(|(_, arg)| arg.has_escaping_bound_vars())
1041 {
1042 debug_assert!(
1043 false,
1044 "args contain late-bound region at index `{i}` which can't be normalized.\n\
1045 use `TyCtxt::instantiate_bound_regions_with_erased`\n\
1046 note: arg is `{arg:#?}`",
1047 );
1048 return None;
1049 }
1050 match tcx.try_normalize_erasing_regions(typing_env, Ty::new_projection_from_args(tcx, ty.def_id, ty.args)) {
1051 Ok(ty) => Some(ty),
1052 Err(e) => {
1053 debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1054 None
1055 },
1056 }
1057 }
1058 helper(tcx, typing_env, make_projection(tcx, container_id, assoc_ty, args)?)
1059}
1060
1061#[derive(Default, Debug)]
1064pub struct InteriorMut<'tcx> {
1065 ignored_def_ids: FxHashSet<DefId>,
1066 ignore_pointers: bool,
1067 tys: FxHashMap<Ty<'tcx>, Option<&'tcx ty::List<Ty<'tcx>>>>,
1068}
1069
1070impl<'tcx> InteriorMut<'tcx> {
1071 pub fn new(tcx: TyCtxt<'tcx>, ignore_interior_mutability: &[String]) -> Self {
1072 let ignored_def_ids = ignore_interior_mutability
1073 .iter()
1074 .flat_map(|ignored_ty| lookup_path_str(tcx, PathNS::Type, ignored_ty))
1075 .collect();
1076
1077 Self {
1078 ignored_def_ids,
1079 ..Self::default()
1080 }
1081 }
1082
1083 pub fn without_pointers(tcx: TyCtxt<'tcx>, ignore_interior_mutability: &[String]) -> Self {
1084 Self {
1085 ignore_pointers: true,
1086 ..Self::new(tcx, ignore_interior_mutability)
1087 }
1088 }
1089
1090 pub fn interior_mut_ty_chain(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<&'tcx ty::List<Ty<'tcx>>> {
1095 self.interior_mut_ty_chain_inner(cx, ty, 0)
1096 }
1097
1098 fn interior_mut_ty_chain_inner(
1099 &mut self,
1100 cx: &LateContext<'tcx>,
1101 ty: Ty<'tcx>,
1102 depth: usize,
1103 ) -> Option<&'tcx ty::List<Ty<'tcx>>> {
1104 if !cx.tcx.recursion_limit().value_within_limit(depth) {
1105 return None;
1106 }
1107
1108 match self.tys.entry(ty) {
1109 Entry::Occupied(o) => return *o.get(),
1110 Entry::Vacant(v) => v.insert(None),
1112 };
1113 let depth = depth + 1;
1114
1115 let chain = match *ty.kind() {
1116 ty::RawPtr(inner_ty, _) if !self.ignore_pointers => self.interior_mut_ty_chain_inner(cx, inner_ty, depth),
1117 ty::Ref(_, inner_ty, _) | ty::Slice(inner_ty) => self.interior_mut_ty_chain_inner(cx, inner_ty, depth),
1118 ty::Array(inner_ty, size) if size.try_to_target_usize(cx.tcx) != Some(0) => {
1119 self.interior_mut_ty_chain_inner(cx, inner_ty, depth)
1120 },
1121 ty::Tuple(fields) => fields
1122 .iter()
1123 .find_map(|ty| self.interior_mut_ty_chain_inner(cx, ty, depth)),
1124 ty::Adt(def, _) if def.is_unsafe_cell() => Some(ty::List::empty()),
1125 ty::Adt(def, args) => {
1126 let is_std_collection = matches!(
1127 cx.tcx.get_diagnostic_name(def.did()),
1128 Some(
1129 sym::LinkedList
1130 | sym::Vec
1131 | sym::VecDeque
1132 | sym::BTreeMap
1133 | sym::BTreeSet
1134 | sym::HashMap
1135 | sym::HashSet
1136 | sym::Arc
1137 | sym::Rc
1138 )
1139 );
1140
1141 if is_std_collection || def.is_box() {
1142 args.types()
1144 .find_map(|ty| self.interior_mut_ty_chain_inner(cx, ty, depth))
1145 } else if self.ignored_def_ids.contains(&def.did()) || def.is_phantom_data() {
1146 None
1147 } else {
1148 def.all_fields()
1149 .find_map(|f| self.interior_mut_ty_chain_inner(cx, f.ty(cx.tcx, args), depth))
1150 }
1151 },
1152 ty::Alias(ty::Projection, _) => match cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty) {
1153 Ok(normalized_ty) if ty != normalized_ty => self.interior_mut_ty_chain_inner(cx, normalized_ty, depth),
1154 _ => None,
1155 },
1156 _ => None,
1157 };
1158
1159 chain.map(|chain| {
1160 let list = cx.tcx.mk_type_list_from_iter(chain.iter().chain([ty]));
1161 self.tys.insert(ty, Some(list));
1162 list
1163 })
1164 }
1165
1166 pub fn is_interior_mut_ty(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1169 self.interior_mut_ty_chain(cx, ty).is_some()
1170 }
1171}
1172
1173pub fn make_normalized_projection_with_regions<'tcx>(
1174 tcx: TyCtxt<'tcx>,
1175 typing_env: ty::TypingEnv<'tcx>,
1176 container_id: DefId,
1177 assoc_ty: Symbol,
1178 args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>,
1179) -> Option<Ty<'tcx>> {
1180 fn helper<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> {
1181 #[cfg(debug_assertions)]
1182 if let Some((i, arg)) = ty
1183 .args
1184 .iter()
1185 .enumerate()
1186 .find(|(_, arg)| arg.has_escaping_bound_vars())
1187 {
1188 debug_assert!(
1189 false,
1190 "args contain late-bound region at index `{i}` which can't be normalized.\n\
1191 use `TyCtxt::instantiate_bound_regions_with_erased`\n\
1192 note: arg is `{arg:#?}`",
1193 );
1194 return None;
1195 }
1196 let cause = ObligationCause::dummy();
1197 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
1198 match infcx
1199 .at(&cause, param_env)
1200 .query_normalize(Ty::new_projection_from_args(tcx, ty.def_id, ty.args))
1201 {
1202 Ok(ty) => Some(ty.value),
1203 Err(e) => {
1204 debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}");
1205 None
1206 },
1207 }
1208 }
1209 helper(tcx, typing_env, make_projection(tcx, container_id, assoc_ty, args)?)
1210}
1211
1212pub fn normalize_with_regions<'tcx>(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1213 let cause = ObligationCause::dummy();
1214 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
1215 infcx
1216 .at(&cause, param_env)
1217 .query_normalize(ty)
1218 .map_or(ty, |ty| ty.value)
1219}
1220
1221pub fn is_manually_drop(ty: Ty<'_>) -> bool {
1223 ty.ty_adt_def().is_some_and(AdtDef::is_manually_drop)
1224}
1225
1226pub fn deref_chain<'cx, 'tcx>(cx: &'cx LateContext<'tcx>, ty: Ty<'tcx>) -> impl Iterator<Item = Ty<'tcx>> + 'cx {
1228 iter::successors(Some(ty), |&ty| {
1229 if let Some(deref_did) = cx.tcx.lang_items().deref_trait()
1230 && implements_trait(cx, ty, deref_did, &[])
1231 {
1232 make_normalized_projection(cx.tcx, cx.typing_env(), deref_did, sym::Target, [ty])
1233 } else {
1234 None
1235 }
1236 })
1237}
1238
1239pub fn get_adt_inherent_method<'a>(cx: &'a LateContext<'_>, ty: Ty<'_>, method_name: Symbol) -> Option<&'a AssocItem> {
1244 if let Some(ty_did) = ty.ty_adt_def().map(AdtDef::did) {
1245 cx.tcx.inherent_impls(ty_did).iter().find_map(|&did| {
1246 cx.tcx
1247 .associated_items(did)
1248 .filter_by_name_unhygienic(method_name)
1249 .next()
1250 .filter(|item| item.tag() == AssocTag::Fn)
1251 })
1252 } else {
1253 None
1254 }
1255}
1256
1257pub fn get_field_by_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
1259 match *ty.kind() {
1260 ty::Adt(def, args) if def.is_union() || def.is_struct() => def
1261 .non_enum_variant()
1262 .fields
1263 .iter()
1264 .find(|f| f.name == name)
1265 .map(|f| f.ty(tcx, args)),
1266 ty::Tuple(args) => name.as_str().parse::<usize>().ok().and_then(|i| args.get(i).copied()),
1267 _ => None,
1268 }
1269}
1270
1271pub fn get_field_def_id_by_name(ty: Ty<'_>, name: Symbol) -> Option<DefId> {
1272 let ty::Adt(adt_def, ..) = ty.kind() else { return None };
1273 adt_def
1274 .all_fields()
1275 .find_map(|field| if field.name == name { Some(field.did) } else { None })
1276}
1277
1278pub fn option_arg_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1280 match *ty.kind() {
1281 ty::Adt(adt, args)
1282 if let [arg] = &**args
1283 && let Some(arg) = arg.as_type()
1284 && adt.is_diag_item(cx, sym::Option) =>
1285 {
1286 Some(arg)
1287 },
1288 _ => None,
1289 }
1290}
1291
1292pub fn has_non_owning_mutable_access<'tcx>(cx: &LateContext<'tcx>, iter_ty: Ty<'tcx>) -> bool {
1297 fn normalize_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
1298 cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty).unwrap_or(ty)
1299 }
1300
1301 fn has_non_owning_mutable_access_inner<'tcx>(
1306 cx: &LateContext<'tcx>,
1307 phantoms: &mut FxHashSet<Ty<'tcx>>,
1308 ty: Ty<'tcx>,
1309 ) -> bool {
1310 match ty.kind() {
1311 ty::Adt(adt_def, args) if adt_def.is_phantom_data() => {
1312 phantoms.insert(ty)
1313 && args
1314 .types()
1315 .any(|arg_ty| has_non_owning_mutable_access_inner(cx, phantoms, arg_ty))
1316 },
1317 ty::Adt(adt_def, args) => adt_def.all_fields().any(|field| {
1318 has_non_owning_mutable_access_inner(cx, phantoms, normalize_ty(cx, field.ty(cx.tcx, args)))
1319 }),
1320 ty::Array(elem_ty, _) | ty::Slice(elem_ty) => has_non_owning_mutable_access_inner(cx, phantoms, *elem_ty),
1321 ty::RawPtr(pointee_ty, mutability) | ty::Ref(_, pointee_ty, mutability) => {
1322 mutability.is_mut() || !pointee_ty.is_freeze(cx.tcx, cx.typing_env())
1323 },
1324 ty::Closure(_, closure_args) => {
1325 matches!(closure_args.types().next_back(),
1326 Some(captures) if has_non_owning_mutable_access_inner(cx, phantoms, captures))
1327 },
1328 ty::Tuple(tuple_args) => tuple_args
1329 .iter()
1330 .any(|arg_ty| has_non_owning_mutable_access_inner(cx, phantoms, arg_ty)),
1331 _ => false,
1332 }
1333 }
1334
1335 let mut phantoms = FxHashSet::default();
1336 has_non_owning_mutable_access_inner(cx, &mut phantoms, iter_ty)
1337}
1338
1339pub fn is_slice_like<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1341 ty.is_slice() || ty.is_array() || ty.is_diag_item(cx, sym::Vec)
1342}
1343
1344pub fn get_field_idx_by_name(ty: Ty<'_>, name: Symbol) -> Option<usize> {
1345 match *ty.kind() {
1346 ty::Adt(def, _) if def.is_union() || def.is_struct() => {
1347 def.non_enum_variant().fields.iter().position(|f| f.name == name)
1348 },
1349 ty::Tuple(_) => name.as_str().parse::<usize>().ok(),
1350 _ => None,
1351 }
1352}
1353
1354pub fn adjust_derefs_manually_drop<'tcx>(adjustments: &'tcx [Adjustment<'tcx>], mut ty: Ty<'tcx>) -> bool {
1356 adjustments.iter().any(|a| {
1357 let ty = mem::replace(&mut ty, a.target);
1358 matches!(a.kind, Adjust::Deref(DerefAdjustKind::Overloaded(op)) if op.mutbl == Mutability::Mut)
1359 && is_manually_drop(ty)
1360 })
1361}