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