1use std::ops::ControlFlow;
8
9use rustc_errors::FatalError;
10use rustc_hir as hir;
11use rustc_hir::def_id::DefId;
12use rustc_middle::query::Providers;
13use rustc_middle::ty::{
14 self, EarlyBinder, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
15 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Upcast,
16};
17use rustc_span::Span;
18use rustc_type_ir::elaborate;
19use smallvec::SmallVec;
20use tracing::{debug, instrument};
21
22use super::elaborate;
23use crate::infer::TyCtxtInferExt;
24pub use crate::traits::DynCompatibilityViolation;
25use crate::traits::query::evaluate_obligation::InferCtxtExt;
26use crate::traits::{
27 MethodViolationCode, Obligation, ObligationCause, normalize_param_env_or_error, util,
28};
29
30#[instrument(level = "debug", skip(tcx), ret)]
36pub fn hir_ty_lowering_dyn_compatibility_violations(
37 tcx: TyCtxt<'_>,
38 trait_def_id: DefId,
39) -> Vec<DynCompatibilityViolation> {
40 debug_assert!(tcx.generics_of(trait_def_id).has_self);
41 elaborate::supertrait_def_ids(tcx, trait_def_id)
42 .map(|def_id| predicates_reference_self(tcx, def_id, true))
43 .filter(|spans| !spans.is_empty())
44 .map(DynCompatibilityViolation::SupertraitSelf)
45 .collect()
46}
47
48fn dyn_compatibility_violations(
49 tcx: TyCtxt<'_>,
50 trait_def_id: DefId,
51) -> &'_ [DynCompatibilityViolation] {
52 debug_assert!(tcx.generics_of(trait_def_id).has_self);
53 debug!("dyn_compatibility_violations: {:?}", trait_def_id);
54 tcx.arena.alloc_from_iter(
55 elaborate::supertrait_def_ids(tcx, trait_def_id)
56 .flat_map(|def_id| dyn_compatibility_violations_for_trait(tcx, def_id)),
57 )
58}
59
60fn is_dyn_compatible(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
61 tcx.dyn_compatibility_violations(trait_def_id).is_empty()
62}
63
64pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: ty::AssocItem) -> bool {
69 debug_assert!(tcx.generics_of(trait_def_id).has_self);
70 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
71 if tcx.generics_require_sized_self(method.def_id) {
73 return false;
74 }
75
76 virtual_call_violations_for_method(tcx, trait_def_id, method).is_empty()
77}
78
79#[instrument(level = "debug", skip(tcx), ret)]
80fn dyn_compatibility_violations_for_trait(
81 tcx: TyCtxt<'_>,
82 trait_def_id: DefId,
83) -> Vec<DynCompatibilityViolation> {
84 let mut violations: Vec<_> = tcx
86 .associated_items(trait_def_id)
87 .in_definition_order()
88 .flat_map(|&item| dyn_compatibility_violations_for_assoc_item(tcx, trait_def_id, item))
89 .collect();
90
91 if trait_has_sized_self(tcx, trait_def_id) {
93 let spans = get_sized_bounds(tcx, trait_def_id);
95 violations.push(DynCompatibilityViolation::SizedSelf(spans));
96 }
97 let spans = predicates_reference_self(tcx, trait_def_id, false);
98 if !spans.is_empty() {
99 violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
100 }
101 let spans = bounds_reference_self(tcx, trait_def_id);
102 if !spans.is_empty() {
103 violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
104 }
105 let spans = super_predicates_have_non_lifetime_binders(tcx, trait_def_id);
106 if !spans.is_empty() {
107 violations.push(DynCompatibilityViolation::SupertraitNonLifetimeBinder(spans));
108 }
109
110 violations
111}
112
113fn sized_trait_bound_spans<'tcx>(
114 tcx: TyCtxt<'tcx>,
115 bounds: hir::GenericBounds<'tcx>,
116) -> impl 'tcx + Iterator<Item = Span> {
117 bounds.iter().filter_map(move |b| match b {
118 hir::GenericBound::Trait(trait_ref)
119 if trait_has_sized_self(
120 tcx,
121 trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
122 ) =>
123 {
124 Some(trait_ref.span)
126 }
127 _ => None,
128 })
129}
130
131fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
132 tcx.hir_get_if_local(trait_def_id)
133 .and_then(|node| match node {
134 hir::Node::Item(hir::Item {
135 kind: hir::ItemKind::Trait(.., generics, bounds, _),
136 ..
137 }) => Some(
138 generics
139 .predicates
140 .iter()
141 .filter_map(|pred| {
142 match pred.kind {
143 hir::WherePredicateKind::BoundPredicate(pred)
144 if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
145 {
146 Some(sized_trait_bound_spans(tcx, pred.bounds))
149 }
150 _ => None,
151 }
152 })
153 .flatten()
154 .chain(sized_trait_bound_spans(tcx, bounds))
156 .collect::<SmallVec<[Span; 1]>>(),
157 ),
158 _ => None,
159 })
160 .unwrap_or_else(SmallVec::new)
161}
162
163fn predicates_reference_self(
164 tcx: TyCtxt<'_>,
165 trait_def_id: DefId,
166 supertraits_only: bool,
167) -> SmallVec<[Span; 1]> {
168 let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id));
169 let predicates = if supertraits_only {
170 tcx.explicit_super_predicates_of(trait_def_id).skip_binder()
171 } else {
172 tcx.predicates_of(trait_def_id).predicates
173 };
174 predicates
175 .iter()
176 .map(|&(predicate, sp)| (predicate.instantiate_supertrait(tcx, trait_ref), sp))
177 .filter_map(|(clause, sp)| {
178 predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::No)
183 })
184 .collect()
185}
186
187fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
188 tcx.associated_items(trait_def_id)
189 .in_definition_order()
190 .filter(|item| item.kind == ty::AssocKind::Type)
192 .filter(|item| !tcx.generics_require_sized_self(item.def_id))
194 .flat_map(|item| tcx.explicit_item_bounds(item.def_id).iter_identity_copied())
195 .filter_map(|(clause, sp)| {
196 predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::Yes)
199 })
200 .collect()
201}
202
203fn predicate_references_self<'tcx>(
204 tcx: TyCtxt<'tcx>,
205 trait_def_id: DefId,
206 predicate: ty::Clause<'tcx>,
207 sp: Span,
208 allow_self_projections: AllowSelfProjections,
209) -> Option<Span> {
210 match predicate.kind().skip_binder() {
211 ty::ClauseKind::Trait(ref data) => {
212 data.trait_ref.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp)
214 }
215 ty::ClauseKind::Projection(ref data) => {
216 data.projection_term.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp)
232 }
233 ty::ClauseKind::ConstArgHasType(_ct, ty) => contains_illegal_self_type_reference(tcx, trait_def_id, ty, allow_self_projections).then_some(sp),
234
235 ty::ClauseKind::WellFormed(..)
236 | ty::ClauseKind::TypeOutlives(..)
237 | ty::ClauseKind::RegionOutlives(..)
238 | ty::ClauseKind::ConstEvaluatable(..)
240 | ty::ClauseKind::HostEffect(..)
241 => None,
242 }
243}
244
245fn super_predicates_have_non_lifetime_binders(
246 tcx: TyCtxt<'_>,
247 trait_def_id: DefId,
248) -> SmallVec<[Span; 1]> {
249 if !tcx.features().non_lifetime_binders() {
251 return SmallVec::new();
252 }
253 tcx.explicit_super_predicates_of(trait_def_id)
254 .iter_identity_copied()
255 .filter_map(|(pred, span)| pred.has_non_region_bound_vars().then_some(span))
256 .collect()
257}
258
259fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
260 tcx.generics_require_sized_self(trait_def_id)
261}
262
263fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
264 let Some(sized_def_id) = tcx.lang_items().sized_trait() else {
265 return false; };
267
268 let predicates = tcx.predicates_of(def_id);
270 let predicates = predicates.instantiate_identity(tcx).predicates;
271 elaborate(tcx, predicates).any(|pred| match pred.kind().skip_binder() {
272 ty::ClauseKind::Trait(ref trait_pred) => {
273 trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
274 }
275 ty::ClauseKind::RegionOutlives(_)
276 | ty::ClauseKind::TypeOutlives(_)
277 | ty::ClauseKind::Projection(_)
278 | ty::ClauseKind::ConstArgHasType(_, _)
279 | ty::ClauseKind::WellFormed(_)
280 | ty::ClauseKind::ConstEvaluatable(_)
281 | ty::ClauseKind::HostEffect(..) => false,
282 })
283}
284
285#[instrument(level = "debug", skip(tcx), ret)]
287pub fn dyn_compatibility_violations_for_assoc_item(
288 tcx: TyCtxt<'_>,
289 trait_def_id: DefId,
290 item: ty::AssocItem,
291) -> Vec<DynCompatibilityViolation> {
292 if tcx.generics_require_sized_self(item.def_id) {
295 return Vec::new();
296 }
297
298 match item.kind {
299 ty::AssocKind::Const => {
302 vec![DynCompatibilityViolation::AssocConst(item.name, item.ident(tcx).span)]
303 }
304 ty::AssocKind::Fn => virtual_call_violations_for_method(tcx, trait_def_id, item)
305 .into_iter()
306 .map(|v| {
307 let node = tcx.hir_get_if_local(item.def_id);
308 let span = match (&v, node) {
310 (MethodViolationCode::ReferencesSelfInput(Some(span)), _) => *span,
311 (MethodViolationCode::UndispatchableReceiver(Some(span)), _) => *span,
312 (MethodViolationCode::ReferencesImplTraitInTrait(span), _) => *span,
313 (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
314 node.fn_decl().map_or(item.ident(tcx).span, |decl| decl.output.span())
315 }
316 _ => item.ident(tcx).span,
317 };
318
319 DynCompatibilityViolation::Method(item.name, v, span)
320 })
321 .collect(),
322 ty::AssocKind::Type => {
324 if !tcx.generics_of(item.def_id).is_own_empty() && !item.is_impl_trait_in_trait() {
325 vec![DynCompatibilityViolation::GAT(item.name, item.ident(tcx).span)]
326 } else {
327 Vec::new()
330 }
331 }
332 }
333}
334
335fn virtual_call_violations_for_method<'tcx>(
340 tcx: TyCtxt<'tcx>,
341 trait_def_id: DefId,
342 method: ty::AssocItem,
343) -> Vec<MethodViolationCode> {
344 let sig = tcx.fn_sig(method.def_id).instantiate_identity();
345
346 if !method.fn_has_self_parameter {
348 let sugg = if let Some(hir::Node::TraitItem(hir::TraitItem {
349 generics,
350 kind: hir::TraitItemKind::Fn(sig, _),
351 ..
352 })) = tcx.hir_get_if_local(method.def_id).as_ref()
353 {
354 let sm = tcx.sess.source_map();
355 Some((
356 (
357 format!("&self{}", if sig.decl.inputs.is_empty() { "" } else { ", " }),
358 sm.span_through_char(sig.span, '(').shrink_to_hi(),
359 ),
360 (
361 format!("{} Self: Sized", generics.add_where_or_trailing_comma()),
362 generics.tail_span_for_predicate_suggestion(),
363 ),
364 ))
365 } else {
366 None
367 };
368
369 return vec![MethodViolationCode::StaticMethod(sugg)];
372 }
373
374 let mut errors = Vec::new();
375
376 for (i, &input_ty) in sig.skip_binder().inputs().iter().enumerate().skip(1) {
377 if contains_illegal_self_type_reference(
378 tcx,
379 trait_def_id,
380 sig.rebind(input_ty),
381 AllowSelfProjections::Yes,
382 ) {
383 let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
384 kind: hir::TraitItemKind::Fn(sig, _),
385 ..
386 })) = tcx.hir_get_if_local(method.def_id).as_ref()
387 {
388 Some(sig.decl.inputs[i].span)
389 } else {
390 None
391 };
392 errors.push(MethodViolationCode::ReferencesSelfInput(span));
393 }
394 }
395 if contains_illegal_self_type_reference(
396 tcx,
397 trait_def_id,
398 sig.output(),
399 AllowSelfProjections::Yes,
400 ) {
401 errors.push(MethodViolationCode::ReferencesSelfOutput);
402 }
403 if let Some(code) = contains_illegal_impl_trait_in_trait(tcx, method.def_id, sig.output()) {
404 errors.push(code);
405 }
406
407 let own_counts = tcx.generics_of(method.def_id).own_counts();
409 if own_counts.types > 0 || own_counts.consts > 0 {
410 errors.push(MethodViolationCode::Generic);
411 }
412
413 let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
414
415 if receiver_ty != tcx.types.self_param {
420 if !receiver_is_dispatchable(tcx, method, receiver_ty) {
421 let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
422 kind: hir::TraitItemKind::Fn(sig, _),
423 ..
424 })) = tcx.hir_get_if_local(method.def_id).as_ref()
425 {
426 Some(sig.decl.inputs[0].span)
427 } else {
428 None
429 };
430 errors.push(MethodViolationCode::UndispatchableReceiver(span));
431 } else {
432 }
435 }
436
437 if tcx.predicates_of(method.def_id).predicates.iter().any(|&(pred, _span)| {
440 if pred.as_type_outlives_clause().is_some() {
450 return false;
451 }
452
453 if let ty::ClauseKind::Trait(ty::TraitPredicate {
467 trait_ref: pred_trait_ref,
468 polarity: ty::PredicatePolarity::Positive,
469 }) = pred.kind().skip_binder()
470 && pred_trait_ref.self_ty() == tcx.types.self_param
471 && tcx.trait_is_auto(pred_trait_ref.def_id)
472 {
473 if pred_trait_ref.args.len() != 1 {
478 assert!(
479 tcx.dcx().has_errors().is_some(),
480 "auto traits cannot have generic parameters"
481 );
482 }
483 return false;
484 }
485
486 contains_illegal_self_type_reference(tcx, trait_def_id, pred, AllowSelfProjections::Yes)
487 }) {
488 errors.push(MethodViolationCode::WhereClauseReferencesSelf);
489 }
490
491 errors
492}
493
494fn receiver_for_self_ty<'tcx>(
497 tcx: TyCtxt<'tcx>,
498 receiver_ty: Ty<'tcx>,
499 self_ty: Ty<'tcx>,
500 method_def_id: DefId,
501) -> Ty<'tcx> {
502 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
503 let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
504 if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
505 });
506
507 let result = EarlyBinder::bind(receiver_ty).instantiate(tcx, args);
508 debug!(
509 "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
510 receiver_ty, self_ty, method_def_id, result
511 );
512 result
513}
514
515fn receiver_is_dispatchable<'tcx>(
562 tcx: TyCtxt<'tcx>,
563 method: ty::AssocItem,
564 receiver_ty: Ty<'tcx>,
565) -> bool {
566 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
567
568 let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
569 let (Some(unsize_did), Some(dispatch_from_dyn_did)) = traits else {
570 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
571 return false;
572 };
573
574 let unsized_self_ty: Ty<'tcx> =
577 Ty::new_param(tcx, u32::MAX, rustc_span::sym::RustaceansAreAwesome);
578
579 let unsized_receiver_ty =
581 receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
582
583 let param_env = {
586 let param_env = tcx.param_env(method.def_id);
587
588 let unsize_predicate =
590 ty::TraitRef::new(tcx, unsize_did, [tcx.types.self_param, unsized_self_ty]).upcast(tcx);
591
592 let trait_predicate = {
594 let trait_def_id = method.trait_container(tcx).unwrap();
595 let args = GenericArgs::for_item(tcx, trait_def_id, |param, _| {
596 if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) }
597 });
598
599 ty::TraitRef::new_from_args(tcx, trait_def_id, args).upcast(tcx)
600 };
601
602 normalize_param_env_or_error(
603 tcx,
604 ty::ParamEnv::new(tcx.mk_clauses_from_iter(
605 param_env.caller_bounds().iter().chain([unsize_predicate, trait_predicate]),
606 )),
607 ObligationCause::dummy_with_span(tcx.def_span(method.def_id)),
608 )
609 };
610
611 let obligation = {
613 let predicate =
614 ty::TraitRef::new(tcx, dispatch_from_dyn_did, [receiver_ty, unsized_receiver_ty]);
615
616 Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate)
617 };
618
619 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
620 infcx.predicate_must_hold_modulo_regions(&obligation)
622}
623
624#[derive(Copy, Clone)]
625enum AllowSelfProjections {
626 Yes,
627 No,
628}
629
630fn contains_illegal_self_type_reference<'tcx, T: TypeVisitable<TyCtxt<'tcx>>>(
669 tcx: TyCtxt<'tcx>,
670 trait_def_id: DefId,
671 value: T,
672 allow_self_projections: AllowSelfProjections,
673) -> bool {
674 value
675 .visit_with(&mut IllegalSelfTypeVisitor {
676 tcx,
677 trait_def_id,
678 supertraits: None,
679 allow_self_projections,
680 })
681 .is_break()
682}
683
684struct IllegalSelfTypeVisitor<'tcx> {
685 tcx: TyCtxt<'tcx>,
686 trait_def_id: DefId,
687 supertraits: Option<Vec<ty::TraitRef<'tcx>>>,
688 allow_self_projections: AllowSelfProjections,
689}
690
691impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalSelfTypeVisitor<'tcx> {
692 type Result = ControlFlow<()>;
693
694 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
695 match t.kind() {
696 ty::Param(_) => {
697 if t == self.tcx.types.self_param {
698 ControlFlow::Break(())
699 } else {
700 ControlFlow::Continue(())
701 }
702 }
703 ty::Alias(ty::Projection, data) if self.tcx.is_impl_trait_in_trait(data.def_id) => {
704 ControlFlow::Continue(())
706 }
707 ty::Alias(ty::Projection, data) => {
708 match self.allow_self_projections {
709 AllowSelfProjections::Yes => {
710 if self.supertraits.is_none() {
714 self.supertraits = Some(
715 util::supertraits(
716 self.tcx,
717 ty::Binder::dummy(ty::TraitRef::identity(
718 self.tcx,
719 self.trait_def_id,
720 )),
721 )
722 .map(|trait_ref| {
723 self.tcx.erase_regions(
724 self.tcx.instantiate_bound_regions_with_erased(trait_ref),
725 )
726 })
727 .collect(),
728 );
729 }
730
731 let is_supertrait_of_current_trait =
740 self.supertraits.as_ref().unwrap().contains(
741 &data.trait_ref(self.tcx).fold_with(
742 &mut EraseEscapingBoundRegions {
743 tcx: self.tcx,
744 binder: ty::INNERMOST,
745 },
746 ),
747 );
748
749 if is_supertrait_of_current_trait {
751 ControlFlow::Continue(())
752 } else {
753 t.super_visit_with(self) }
755 }
756 AllowSelfProjections::No => t.super_visit_with(self),
757 }
758 }
759 _ => t.super_visit_with(self),
760 }
761 }
762
763 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
764 self.tcx.expand_abstract_consts(ct).super_visit_with(self)
767 }
768}
769
770struct EraseEscapingBoundRegions<'tcx> {
771 tcx: TyCtxt<'tcx>,
772 binder: ty::DebruijnIndex,
773}
774
775impl<'tcx> TypeFolder<TyCtxt<'tcx>> for EraseEscapingBoundRegions<'tcx> {
776 fn cx(&self) -> TyCtxt<'tcx> {
777 self.tcx
778 }
779
780 fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
781 where
782 T: TypeFoldable<TyCtxt<'tcx>>,
783 {
784 self.binder.shift_in(1);
785 let result = t.super_fold_with(self);
786 self.binder.shift_out(1);
787 result
788 }
789
790 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
791 if let ty::ReBound(debruijn, _) = *r
792 && debruijn < self.binder
793 {
794 r
795 } else {
796 self.tcx.lifetimes.re_erased
797 }
798 }
799}
800
801fn contains_illegal_impl_trait_in_trait<'tcx>(
802 tcx: TyCtxt<'tcx>,
803 fn_def_id: DefId,
804 ty: ty::Binder<'tcx, Ty<'tcx>>,
805) -> Option<MethodViolationCode> {
806 let ty = tcx.liberate_late_bound_regions(fn_def_id, ty);
807
808 if tcx.asyncness(fn_def_id).is_async() {
809 Some(MethodViolationCode::AsyncFn)
811 } else {
812 ty.visit_with(&mut IllegalRpititVisitor { tcx, allowed: None }).break_value()
813 }
814}
815
816struct IllegalRpititVisitor<'tcx> {
817 tcx: TyCtxt<'tcx>,
818 allowed: Option<ty::AliasTy<'tcx>>,
819}
820
821impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalRpititVisitor<'tcx> {
822 type Result = ControlFlow<MethodViolationCode>;
823
824 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
825 if let ty::Alias(ty::Projection, proj) = *ty.kind()
826 && Some(proj) != self.allowed
827 && self.tcx.is_impl_trait_in_trait(proj.def_id)
828 {
829 ControlFlow::Break(MethodViolationCode::ReferencesImplTraitInTrait(
830 self.tcx.def_span(proj.def_id),
831 ))
832 } else {
833 ty.super_visit_with(self)
834 }
835 }
836}
837
838pub(crate) fn provide(providers: &mut Providers) {
839 *providers = Providers {
840 dyn_compatibility_violations,
841 is_dyn_compatible,
842 generics_require_sized_self,
843 ..*providers
844 };
845}