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