1use std::ops::ControlFlow;
8
9use rustc_attr_ir::lang_items::LangItem;
10use rustc_errors::FatalError;
11use rustc_hir as hir;
12use rustc_hir::def_id::DefId;
13use rustc_middle::query::Providers;
14use rustc_middle::ty::{
15 self, EarlyBinder, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
16 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
17 Upcast, elaborate,
18};
19use rustc_span::{DUMMY_SP, Span, kw, sym};
20use smallvec::SmallVec;
21use tracing::{debug, instrument};
22
23use super::elaborate;
24use crate::infer::TyCtxtInferExt;
25pub use crate::traits::DynCompatibilityViolation;
26use crate::traits::query::evaluate_obligation::InferCtxtExt;
27use crate::traits::{
28 AssocConstViolation, MethodViolation, Obligation, ObligationCause,
29 normalize_param_env_or_error, util,
30};
31
32{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() || { false }
{
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("hir_ty_lowering_dyn_compatibility_violations",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(37u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_def_id")
}> =
::tracing::__macro_support::FieldName::new("trait_def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Vec<DynCompatibilityViolation> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !tcx.generics_of(trait_def_id).has_self {
::core::panicking::panic("assertion failed: tcx.generics_of(trait_def_id).has_self")
};
};
elaborate::supertrait_def_ids(tcx,
trait_def_id).map(|def_id|
clauses_reference_self(tcx, def_id,
true)).filter(|spans|
!spans.is_empty()).map(DynCompatibilityViolation::SupertraitSelf).collect()
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:37",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(37u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
38pub fn hir_ty_lowering_dyn_compatibility_violations(
39 tcx: TyCtxt<'_>,
40 trait_def_id: DefId,
41) -> Vec<DynCompatibilityViolation> {
42 debug_assert!(tcx.generics_of(trait_def_id).has_self);
43 elaborate::supertrait_def_ids(tcx, trait_def_id)
44 .map(|def_id| clauses_reference_self(tcx, def_id, true))
45 .filter(|spans| !spans.is_empty())
46 .map(DynCompatibilityViolation::SupertraitSelf)
47 .collect()
48}
49
50fn dyn_compatibility_violations(
51 tcx: TyCtxt<'_>,
52 trait_def_id: DefId,
53) -> &'_ [DynCompatibilityViolation] {
54 if true {
if !tcx.generics_of(trait_def_id).has_self {
::core::panicking::panic("assertion failed: tcx.generics_of(trait_def_id).has_self")
};
};debug_assert!(tcx.generics_of(trait_def_id).has_self);
55 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:55",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(55u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("dyn_compatibility_violations: {0:?}",
trait_def_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("dyn_compatibility_violations: {:?}", trait_def_id);
56 tcx.arena.alloc_from_iter(
57 elaborate::supertrait_def_ids(tcx, trait_def_id)
58 .flat_map(|def_id| dyn_compatibility_violations_for_trait(tcx, def_id)),
59 )
60}
61
62fn is_dyn_compatible(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
63 tcx.dyn_compatibility_violations(trait_def_id).is_empty()
64}
65
66pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: ty::AssocItem) -> bool {
71 if true {
if !tcx.generics_of(trait_def_id).has_self {
::core::panicking::panic("assertion failed: tcx.generics_of(trait_def_id).has_self")
};
};debug_assert!(tcx.generics_of(trait_def_id).has_self);
72 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:72",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(72u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("is_vtable_safe_method({0:?}, {1:?})",
trait_def_id, method) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
73 if tcx.generics_require_sized_self(method.def_id) {
75 return false;
76 }
77
78 virtual_call_violations_for_method(tcx, trait_def_id, method).is_empty()
79}
80
81{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() || { false }
{
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("dyn_compatibility_violations_for_trait",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(81u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_def_id")
}> =
::tracing::__macro_support::FieldName::new("trait_def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Vec<DynCompatibilityViolation> = loop {};
return __tracing_attr_fake_return;
}
{
let mut violations: Vec<_> =
tcx.associated_items(trait_def_id).in_definition_order().flat_map(|&item|
dyn_compatibility_violations_for_assoc_item(tcx,
trait_def_id, item)).collect();
if trait_has_sized_self(tcx, trait_def_id) {
let spans = get_sized_bounds(tcx, trait_def_id);
violations.push(DynCompatibilityViolation::SizedSelf(spans));
} else if let Some(span) =
tcx.trait_def(trait_def_id).force_dyn_incompatible {
violations.push(DynCompatibilityViolation::ExplicitlyDynIncompatible([span].into()));
}
let spans =
clauses_reference_self(tcx, trait_def_id, false);
if !spans.is_empty() {
violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
}
let spans = bounds_reference_self(tcx, trait_def_id);
if !spans.is_empty() {
violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
}
let spans =
super_clauses_have_non_lifetime_binders(tcx, trait_def_id);
if !spans.is_empty() {
violations.push(DynCompatibilityViolation::SupertraitNonLifetimeBinder(spans));
}
let spans =
super_clauses_are_unconditionally_const(tcx, trait_def_id);
if !spans.is_empty() {
violations.push(DynCompatibilityViolation::SupertraitConst(spans));
}
violations
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:81",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(81u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
82fn dyn_compatibility_violations_for_trait(
83 tcx: TyCtxt<'_>,
84 trait_def_id: DefId,
85) -> Vec<DynCompatibilityViolation> {
86 let mut violations: Vec<_> = tcx
88 .associated_items(trait_def_id)
89 .in_definition_order()
90 .flat_map(|&item| dyn_compatibility_violations_for_assoc_item(tcx, trait_def_id, item))
91 .collect();
92
93 if trait_has_sized_self(tcx, trait_def_id) {
95 let spans = get_sized_bounds(tcx, trait_def_id);
97 violations.push(DynCompatibilityViolation::SizedSelf(spans));
98 } else if let Some(span) = tcx.trait_def(trait_def_id).force_dyn_incompatible {
99 violations.push(DynCompatibilityViolation::ExplicitlyDynIncompatible([span].into()));
100 }
101
102 let spans = clauses_reference_self(tcx, trait_def_id, false);
103 if !spans.is_empty() {
104 violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
105 }
106 let spans = bounds_reference_self(tcx, trait_def_id);
107 if !spans.is_empty() {
108 violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
109 }
110 let spans = super_clauses_have_non_lifetime_binders(tcx, trait_def_id);
111 if !spans.is_empty() {
112 violations.push(DynCompatibilityViolation::SupertraitNonLifetimeBinder(spans));
113 }
114 let spans = super_clauses_are_unconditionally_const(tcx, trait_def_id);
115 if !spans.is_empty() {
116 violations.push(DynCompatibilityViolation::SupertraitConst(spans));
117 }
118
119 violations
120}
121
122fn sized_trait_bound_spans<'tcx>(
123 tcx: TyCtxt<'tcx>,
124 bounds: hir::GenericBounds<'tcx>,
125) -> impl 'tcx + Iterator<Item = Span> {
126 bounds.iter().filter_map(move |b| match b {
127 hir::GenericBound::Trait(trait_ref)
128 if trait_has_sized_self(
129 tcx,
130 trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
131 ) =>
132 {
133 Some(trait_ref.span)
135 }
136 _ => None,
137 })
138}
139
140fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
141 tcx.hir_get_if_local(trait_def_id)
142 .and_then(|node| match node {
143 hir::Node::Item(hir::Item {
144 kind: hir::ItemKind::Trait { generics, bounds, .. },
145 ..
146 }) => Some(
147 generics
148 .predicates
149 .iter()
150 .filter_map(|pred| {
151 match pred.kind {
152 hir::WherePredicateKind::BoundPredicate(pred)
153 if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
154 {
155 Some(sized_trait_bound_spans(tcx, pred.bounds))
158 }
159 _ => None,
160 }
161 })
162 .flatten()
163 .chain(sized_trait_bound_spans(tcx, bounds))
165 .collect::<SmallVec<[Span; 1]>>(),
166 ),
167 _ => None,
168 })
169 .unwrap_or_else(SmallVec::new)
170}
171
172fn clauses_reference_self(
173 tcx: TyCtxt<'_>,
174 trait_def_id: DefId,
175 supertraits_only: bool,
176) -> SmallVec<[Span; 1]> {
177 let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id));
178 let clauses = if supertraits_only {
179 tcx.explicit_super_clauses_of(trait_def_id).skip_binder()
180 } else {
181 tcx.clauses_of(trait_def_id).clauses
182 };
183 clauses
184 .iter()
185 .map(|&(clause, sp)| (clause.instantiate_supertrait(tcx, trait_ref), sp))
186 .filter_map(|(clause, sp)| {
187 predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::No)
192 })
193 .collect()
194}
195
196fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
197 tcx.associated_items(trait_def_id)
198 .in_definition_order()
199 .filter(|item| item.is_type())
201 .filter(|item| !tcx.generics_require_sized_self(item.def_id))
203 .flat_map(|item| {
204 tcx.explicit_item_bounds(item.def_id)
205 .iter_identity_copied()
206 .map(Unnormalized::skip_norm_wip)
207 })
208 .filter_map(|(clause, sp)| {
209 predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::Yes)
212 })
213 .collect()
214}
215
216fn predicate_references_self<'tcx>(
217 tcx: TyCtxt<'tcx>,
218 trait_def_id: DefId,
219 predicate: ty::Clause<'tcx>,
220 sp: Span,
221 allow_self_projections: AllowSelfProjections,
222) -> Option<Span> {
223 match predicate.kind().skip_binder() {
224 ty::ClauseKind::Trait(ref data) => {
225 data.trait_ref.args.as_slice()[1..]
227 .iter()
228 .any(|&arg| {
229 contains_illegal_self_type_reference(
230 tcx,
231 trait_def_id,
232 arg,
233 allow_self_projections,
234 )
235 })
236 .then_some(sp)
237 }
238 ty::ClauseKind::Projection(ref data) => {
239 data.projection_term.args.as_slice()[1..]
255 .iter()
256 .any(|&arg| {
257 contains_illegal_self_type_reference(
258 tcx,
259 trait_def_id,
260 arg,
261 allow_self_projections,
262 )
263 })
264 .then_some(sp)
265 }
266 ty::ClauseKind::ConstArgHasType(_ct, ty) => {
267 contains_illegal_self_type_reference(tcx, trait_def_id, ty, allow_self_projections)
268 .then_some(sp)
269 }
270
271 ty::ClauseKind::WellFormed(..)
272 | ty::ClauseKind::TypeOutlives(..)
273 | ty::ClauseKind::RegionOutlives(..)
274 | ty::ClauseKind::HostEffect(..)
275 | ty::ClauseKind::UnstableFeature(_) => None,
276
277 ty::ClauseKind::ConstEvaluatable(..) => None,
279
280 ty::ClauseKind::CompressedTrait(..) => ::core::panicking::unreachable_default_msg()unreachable!(),
281 }
282}
283
284fn super_clauses_have_non_lifetime_binders(
285 tcx: TyCtxt<'_>,
286 trait_def_id: DefId,
287) -> SmallVec<[Span; 1]> {
288 tcx.explicit_super_clauses_of(trait_def_id)
289 .iter_identity_copied()
290 .map(Unnormalized::skip_norm_wip)
291 .filter_map(|(clause, span)| clause.has_non_region_bound_vars().then_some(span))
292 .collect()
293}
294
295fn super_clauses_are_unconditionally_const(
299 tcx: TyCtxt<'_>,
300 trait_def_id: DefId,
301) -> SmallVec<[Span; 1]> {
302 tcx.explicit_super_clauses_of(trait_def_id)
303 .iter_identity_copied()
304 .map(Unnormalized::skip_norm_wip)
305 .filter_map(|(clause, span)| {
306 if let ty::ClauseKind::HostEffect(_) = clause.kind().skip_binder() {
307 Some(span)
308 } else {
309 None
310 }
311 })
312 .collect()
313}
314
315fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
316 tcx.generics_require_sized_self(trait_def_id)
317}
318
319fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
320 let Some(sized_def_id) = tcx.lang_items().sized_trait() else {
321 return false; };
323
324 let clauses: Vec<_> = tcx
326 .clauses_of(def_id)
327 .instantiate_identity(tcx)
328 .clauses
329 .into_iter()
330 .map(Unnormalized::skip_norm_wip)
331 .collect();
332 elaborate(tcx, clauses).any(|clause| match clause.kind().skip_binder() {
333 ty::ClauseKind::Trait(ref trait_pred) => {
334 trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
335 }
336 ty::ClauseKind::RegionOutlives(_)
337 | ty::ClauseKind::TypeOutlives(_)
338 | ty::ClauseKind::Projection(_)
339 | ty::ClauseKind::ConstArgHasType(_, _)
340 | ty::ClauseKind::WellFormed(_)
341 | ty::ClauseKind::ConstEvaluatable(_)
342 | ty::ClauseKind::UnstableFeature(_)
343 | ty::ClauseKind::HostEffect(..) => false,
344 ty::ClauseKind::CompressedTrait(_) => ::core::panicking::unreachable_default_msg()unreachable!(),
345 })
346}
347
348{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() || { false }
{
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("dyn_compatibility_violations_for_assoc_item",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(348u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_def_id")
}> =
::tracing::__macro_support::FieldName::new("trait_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item")
}> =
::tracing::__macro_support::FieldName::new("item");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Vec<DynCompatibilityViolation> = loop {};
return __tracing_attr_fake_return;
}
{
if tcx.defaultness(item.def_id).is_final() {
return Vec::new();
}
if tcx.generics_require_sized_self(item.def_id) {
return Vec::new();
}
let span = || item.ident(tcx).span;
match item.kind {
ty::AssocKind::Const { data: ty::AssocConstData::Anonymous }
=> {
{
::core::panicking::panic_fmt(format_args!("anonymous associated consts shouldn\'t end up here"));
}
}
ty::AssocKind::Const { data: ty::AssocConstData::Named(name)
} => {
let mut errors = Vec::new();
if tcx.features().gca_min_const_items() {
if !tcx.generics_of(item.def_id).is_own_empty() {
errors.push(AssocConstViolation::Generic);
} else if !tcx.is_always_gca(item.def_id) &&
!tcx.features().gca_const_items() {
errors.push(AssocConstViolation::NonType);
}
let ty =
ty::Binder::dummy(tcx.type_of(item.def_id).instantiate_identity().skip_norm_wip());
if contains_illegal_self_type_reference(tcx, trait_def_id,
ty, AllowSelfProjections::Yes) {
errors.push(AssocConstViolation::TypeReferencesSelf);
}
} else {
errors.push(AssocConstViolation::FeatureNotEnabled);
}
errors.into_iter().map(|error|
DynCompatibilityViolation::AssocConst(name, error,
span())).collect()
}
ty::AssocKind::Fn { name, .. } => {
virtual_call_violations_for_method(tcx, trait_def_id,
item).into_iter().map(|v|
{
let node = tcx.hir_get_if_local(item.def_id);
let span =
match (&v, node) {
(MethodViolation::ReferencesSelfInput(Some(span)), _) =>
*span,
(MethodViolation::UndispatchableReceiver(Some((span, _))),
_) => *span,
(MethodViolation::ReferencesImplTraitInTrait(span), _) =>
*span,
(MethodViolation::ReferencesSelfOutput, Some(node)) => {
node.fn_decl().map_or(item.ident(tcx).span,
|decl| decl.output.span())
}
_ => span(),
};
DynCompatibilityViolation::Method(name, v, span)
}).collect()
}
ty::AssocKind::Type { data } => {
if !tcx.generics_of(item.def_id).is_own_empty() &&
let ty::AssocTypeData::Normal(name) = data {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[DynCompatibilityViolation::GenericAssocTy(name, span())]))
} else { Vec::new() }
}
}
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:348",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(348u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
349pub fn dyn_compatibility_violations_for_assoc_item(
350 tcx: TyCtxt<'_>,
351 trait_def_id: DefId,
352 item: ty::AssocItem,
353) -> Vec<DynCompatibilityViolation> {
354 if tcx.defaultness(item.def_id).is_final() {
356 return Vec::new();
357 }
358
359 if tcx.generics_require_sized_self(item.def_id) {
361 return Vec::new();
362 }
363
364 let span = || item.ident(tcx).span;
365
366 match item.kind {
367 ty::AssocKind::Const { data: ty::AssocConstData::Anonymous } => {
368 panic!("anonymous associated consts shouldn't end up here")
369 }
370 ty::AssocKind::Const { data: ty::AssocConstData::Named(name) } => {
371 let mut errors = Vec::new();
376
377 if tcx.features().gca_min_const_items() {
378 if !tcx.generics_of(item.def_id).is_own_empty() {
379 errors.push(AssocConstViolation::Generic);
380 } else if !tcx.is_always_gca(item.def_id) && !tcx.features().gca_const_items() {
381 errors.push(AssocConstViolation::NonType);
382 }
383
384 let ty = ty::Binder::dummy(
385 tcx.type_of(item.def_id).instantiate_identity().skip_norm_wip(),
386 );
387 if contains_illegal_self_type_reference(
388 tcx,
389 trait_def_id,
390 ty,
391 AllowSelfProjections::Yes,
392 ) {
393 errors.push(AssocConstViolation::TypeReferencesSelf);
394 }
395 } else {
396 errors.push(AssocConstViolation::FeatureNotEnabled);
397 }
398
399 errors
400 .into_iter()
401 .map(|error| DynCompatibilityViolation::AssocConst(name, error, span()))
402 .collect()
403 }
404 ty::AssocKind::Fn { name, .. } => {
405 virtual_call_violations_for_method(tcx, trait_def_id, item)
406 .into_iter()
407 .map(|v| {
408 let node = tcx.hir_get_if_local(item.def_id);
409 let span = match (&v, node) {
411 (MethodViolation::ReferencesSelfInput(Some(span)), _) => *span,
412 (MethodViolation::UndispatchableReceiver(Some((span, _))), _) => *span,
413 (MethodViolation::ReferencesImplTraitInTrait(span), _) => *span,
414 (MethodViolation::ReferencesSelfOutput, Some(node)) => {
415 node.fn_decl().map_or(item.ident(tcx).span, |decl| decl.output.span())
416 }
417 _ => span(),
418 };
419
420 DynCompatibilityViolation::Method(name, v, span)
421 })
422 .collect()
423 }
424 ty::AssocKind::Type { data } => {
425 if !tcx.generics_of(item.def_id).is_own_empty()
426 && let ty::AssocTypeData::Normal(name) = data
427 {
428 vec![DynCompatibilityViolation::GenericAssocTy(name, span())]
429 } else {
430 Vec::new()
434 }
435 }
436 }
437}
438
439fn virtual_call_violations_for_method<'tcx>(
444 tcx: TyCtxt<'tcx>,
445 trait_def_id: DefId,
446 method: ty::AssocItem,
447) -> Vec<MethodViolation> {
448 let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
449
450 if !method.is_method() {
452 let sugg = if let Some(hir::Node::TraitItem(hir::TraitItem {
453 generics,
454 kind: hir::TraitItemKind::Fn(sig, _),
455 ..
456 })) = tcx.hir_get_if_local(method.def_id).as_ref()
457 {
458 let sm = tcx.sess.source_map();
459 Some((
460 (
461 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&self{0}",
if sig.decl.inputs.is_empty() { "" } else { ", " }))
})format!("&self{}", if sig.decl.inputs.is_empty() { "" } else { ", " }),
462 sm.span_through_char(sig.span, '(').shrink_to_hi(),
463 ),
464 (
465 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} Self: Sized",
generics.add_where_or_trailing_comma()))
})format!("{} Self: Sized", generics.add_where_or_trailing_comma()),
466 generics.tail_span_for_predicate_suggestion(),
467 ),
468 ))
469 } else {
470 None
471 };
472
473 return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MethodViolation::StaticMethod(sugg)]))vec![MethodViolation::StaticMethod(sugg)];
476 }
477
478 let mut errors = Vec::new();
479
480 for (i, &input_ty) in sig.skip_binder().inputs().iter().enumerate().skip(1) {
481 if contains_illegal_self_type_reference(
482 tcx,
483 trait_def_id,
484 sig.rebind(input_ty),
485 AllowSelfProjections::Yes,
486 ) {
487 let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
488 kind: hir::TraitItemKind::Fn(sig, _),
489 ..
490 })) = tcx.hir_get_if_local(method.def_id).as_ref()
491 {
492 Some(sig.decl.inputs[i].span)
493 } else {
494 None
495 };
496 errors.push(MethodViolation::ReferencesSelfInput(span));
497 }
498 }
499 if contains_illegal_self_type_reference(
500 tcx,
501 trait_def_id,
502 sig.output(),
503 AllowSelfProjections::Yes,
504 ) {
505 errors.push(MethodViolation::ReferencesSelfOutput);
506 }
507 if let Some(error) = contains_illegal_impl_trait_in_trait(tcx, method.def_id, sig.output()) {
508 errors.push(error);
509 }
510 if sig.skip_binder().c_variadic() {
511 errors.push(MethodViolation::CVariadic);
512 }
513
514 let own_counts = tcx.generics_of(method.def_id).own_counts();
516 if own_counts.types > 0 || own_counts.consts > 0 {
517 errors.push(MethodViolation::Generic);
518 }
519
520 let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
521
522 if receiver_ty != tcx.types.self_param {
527 if !receiver_is_dispatchable(tcx, method, receiver_ty) {
528 let span_n_lt = if let Some(hir::Node::TraitItem(hir::TraitItem {
529 kind: hir::TraitItemKind::Fn(sig, trait_fn),
530 ..
531 })) = tcx.hir_get_if_local(method.def_id).as_ref()
532 {
533 let lt = match sig.decl.inputs[0].kind {
535 hir::TyKind::Ref(lt, ..) if lt.ident.name == kw::UnderscoreLifetime => {
536 sym::empty
537 }
538 hir::TyKind::Ref(lt, ..) => lt.ident.name,
539 _ => sym::empty,
540 };
541 match trait_fn {
543 hir::TraitFn::Required([Some(name), ..])
544 if name.span.ctxt() == sig.decl.inputs[0].span.ctxt() =>
545 {
546 Some(name.span.to(sig.decl.inputs[0].span))
547 }
548 hir::TraitFn::Provided(body_id)
549 if let body = tcx.hir_body(*body_id)
550 && let Some(p) = body.params.get(0)
551 && p.span.ctxt() == p.ty_span.ctxt() =>
552 {
553 Some(p.span.to(p.ty_span))
554 }
555 _ => None,
556 }
557 .map(|sp| (sp, lt))
558 } else {
559 None
560 };
561 errors.push(MethodViolation::UndispatchableReceiver(span_n_lt));
562 } else {
563 }
566 }
567
568 if tcx.clauses_of(method.def_id).clauses.iter().any(|&(clause, _span)| {
571 if clause.as_type_outlives_clause().is_some() {
581 return false;
582 }
583
584 if let ty::ClauseKind::Trait(ty::TraitClause {
598 trait_ref: pred_trait_ref,
599 polarity: ty::ClausePolarity::Positive,
600 }) = clause.kind().skip_binder()
601 && pred_trait_ref.self_ty() == tcx.types.self_param
602 && tcx.trait_is_auto(pred_trait_ref.def_id)
603 {
604 if pred_trait_ref.args.len() != 1 {
609 if !tcx.dcx().has_errors().is_some() {
{
::core::panicking::panic_fmt(format_args!("auto traits cannot have generic parameters"));
}
};assert!(
610 tcx.dcx().has_errors().is_some(),
611 "auto traits cannot have generic parameters"
612 );
613 }
614 return false;
615 }
616
617 contains_illegal_self_type_reference(tcx, trait_def_id, clause, AllowSelfProjections::Yes)
618 }) {
619 errors.push(MethodViolation::WhereClauseReferencesSelf);
620 }
621
622 errors
623}
624
625fn receiver_for_self_ty<'tcx>(
628 tcx: TyCtxt<'tcx>,
629 receiver_ty: Ty<'tcx>,
630 self_ty: Ty<'tcx>,
631 method_def_id: DefId,
632) -> Ty<'tcx> {
633 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:633",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(633u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_for_self_ty({0:?}, {1:?}, {2:?})",
receiver_ty, self_ty, method_def_id) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
634 let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
635 if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
636 });
637
638 let result = EarlyBinder::bind(tcx, receiver_ty).instantiate(tcx, args).skip_norm_wip();
639 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:639",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(639u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_for_self_ty({0:?}, {1:?}, {2:?}) = {3:?}",
receiver_ty, self_ty, method_def_id, result) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
640 "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
641 receiver_ty, self_ty, method_def_id, result
642 );
643 result
644}
645
646fn receiver_is_dispatchable<'tcx>(
696 tcx: TyCtxt<'tcx>,
697 method: ty::AssocItem,
698 receiver_ty: Ty<'tcx>,
699) -> bool {
700 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:700",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(700u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_is_dispatchable: method = {0:?}, receiver_ty = {1:?}",
method, receiver_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
701
702 if receiver_ty.references_error() {
703 return false;
704 }
705
706 let (Some(unsize_did), Some(dispatch_from_dyn_did)) =
707 (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait())
708 else {
709 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:709",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(709u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_is_dispatchable: Missing `Unsize` or `DispatchFromDyn` traits")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("receiver_is_dispatchable: Missing `Unsize` or `DispatchFromDyn` traits");
710 return false;
711 };
712
713 let unsized_self_ty: Ty<'tcx> =
716 Ty::new_param(tcx, u32::MAX, rustc_span::sym::RustaceansAreAwesome);
717
718 let unsized_receiver_ty =
720 receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
721
722 let param_env = {
725 let mut clauses: Vec<_> = tcx
738 .clauses_of(method.def_id)
739 .instantiate_identity(tcx)
740 .clauses
741 .into_iter()
742 .map(Unnormalized::skip_norm_wip)
743 .collect();
744
745 let unsize_predicate =
747 ty::TraitRef::new(tcx, unsize_did, [tcx.types.self_param, unsized_self_ty]);
748 clauses.push(unsize_predicate.upcast(tcx));
749
750 let trait_def_id = method.trait_container(tcx).unwrap();
752 let args = GenericArgs::for_item(tcx, trait_def_id, |param, _| {
753 if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) }
754 });
755 let trait_predicate = ty::TraitRef::new_from_args(tcx, trait_def_id, args);
756 clauses.push(trait_predicate.upcast(tcx));
757
758 clauses.extend(
763 tcx.clauses_of(trait_def_id)
764 .instantiate(tcx, args)
765 .clauses
766 .into_iter()
767 .map(Unnormalized::skip_norm_wip)
768 .filter(|clause| #[allow(non_exhaustive_omitted_patterns)] match clause.kind().skip_binder() {
ty::ClauseKind::Trait(_) => true,
_ => false,
}matches!(clause.kind().skip_binder(), ty::ClauseKind::Trait(_))),
771 );
772
773 clauses.extend(
789 tcx.clauses_of(trait_def_id)
790 .instantiate_identity(tcx)
791 .clauses
792 .into_iter()
793 .map(Unnormalized::skip_norm_wip)
794 .filter_map(|clause| -> Option<ty::Clause<'tcx>> {
795 clause
796 .as_projection_clause()
797 .filter(|proj| {
801 proj.skip_binder().projection_term.args.iter().any(|arg| {
802 arg.as_type().is_some_and(|arg| arg.contains(tcx.types.self_param))
803 })
804 })
805 .map(|proj| {
806 proj.map_bound(|proj| {
807 EarlyBinder::bind(tcx, proj).instantiate(tcx, args).skip_norm_wip()
808 })
809 .upcast(tcx)
810 })
811 }),
812 );
813
814 let meta_sized_predicate = {
815 let meta_sized_did = tcx.require_lang_item(LangItem::MetaSized, DUMMY_SP);
816 ty::TraitRef::new(tcx, meta_sized_did, [unsized_self_ty])
817 };
818 clauses.push(meta_sized_predicate.upcast(tcx));
819
820 normalize_param_env_or_error(
821 tcx,
822 clauses,
823 ObligationCause::dummy_with_span(tcx.def_span(method.def_id)),
824 )
825 };
826
827 let obligation = {
829 let predicate =
830 ty::TraitRef::new(tcx, dispatch_from_dyn_did, [receiver_ty, unsized_receiver_ty]);
831
832 Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate)
833 };
834
835 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
836 infcx.predicate_must_hold_modulo_regions(&obligation)
838}
839
840#[derive(#[automatically_derived]impl ::core::marker::Copy for AllowSelfProjections { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for AllowSelfProjections {
}
#[automatically_derived]impl ::core::clone::Clone for AllowSelfProjections {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone)]
841enum AllowSelfProjections {
842 Yes,
843 No,
844}
845
846fn contains_illegal_self_type_reference<'tcx, T: TypeVisitable<TyCtxt<'tcx>>>(
888 tcx: TyCtxt<'tcx>,
889 trait_def_id: DefId,
890 value: T,
891 allow_self_projections: AllowSelfProjections,
892) -> bool {
893 value
894 .visit_with(&mut IllegalSelfTypeVisitor {
895 tcx,
896 trait_def_id,
897 supertraits: None,
898 allow_self_projections,
899 })
900 .is_break()
901}
902
903struct IllegalSelfTypeVisitor<'tcx> {
904 tcx: TyCtxt<'tcx>,
905 trait_def_id: DefId,
906 supertraits: Option<Vec<ty::TraitRef<'tcx>>>,
907 allow_self_projections: AllowSelfProjections,
908}
909
910impl<'tcx> IllegalSelfTypeVisitor<'tcx> {
911 fn is_supertrait_of_current_trait(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
912 let supertraits = self.supertraits.get_or_insert_with(|| {
914 util::supertraits(
915 self.tcx,
916 ty::Binder::dummy(ty::TraitRef::identity(self.tcx, self.trait_def_id)),
917 )
918 .map(Unnormalized::skip_norm_wip)
919 .map(|trait_ref| {
920 self.tcx.erase_and_anonymize_regions(
921 self.tcx.instantiate_bound_regions_with_erased(trait_ref),
922 )
923 })
924 .collect()
925 });
926
927 let trait_ref = trait_ref
933 .fold_with(&mut EraseEscapingBoundRegions { tcx: self.tcx, binder: ty::INNERMOST });
934 supertraits.contains(&trait_ref)
935 }
936}
937
938impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalSelfTypeVisitor<'tcx> {
939 type Result = ControlFlow<()>;
940
941 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
942 match ty.kind() {
943 ty::Param(_) => {
944 if ty == self.tcx.types.self_param {
945 ControlFlow::Break(())
946 } else {
947 ControlFlow::Continue(())
948 }
949 }
950 ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. })
951 if self.tcx.is_impl_trait_in_trait(*def_id) =>
952 {
953 ControlFlow::Continue(())
955 }
956 ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { .. }, .. }) => {
957 match self.allow_self_projections {
958 AllowSelfProjections::Yes => {
959 if self.is_supertrait_of_current_trait(proj.trait_ref(self.tcx)) {
961 ControlFlow::Continue(())
962 } else {
963 ty.super_visit_with(self)
964 }
965 }
966 AllowSelfProjections::No => ty.super_visit_with(self),
967 }
968 }
969 _ => ty.super_visit_with(self),
970 }
971 }
972
973 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
974 let ct = self.tcx.expand_abstract_consts(ct);
975
976 match ct.kind() {
977 ty::ConstKind::Alias(
978 _,
979 ty::AliasConst { kind: ty::AliasConstKind::Projection { def_id }, args, .. },
980 ) if self.tcx.features().gca_min_const_items() => {
981 match self.allow_self_projections {
982 AllowSelfProjections::Yes => {
983 let trait_def_id = self.tcx.parent(def_id);
984 let trait_ref = ty::TraitRef::from_assoc(self.tcx, trait_def_id, args);
985
986 if self.is_supertrait_of_current_trait(trait_ref) {
988 ControlFlow::Continue(())
989 } else {
990 ct.super_visit_with(self)
991 }
992 }
993 AllowSelfProjections::No => ct.super_visit_with(self),
994 }
995 }
996 _ => ct.super_visit_with(self),
997 }
998 }
999}
1000
1001struct EraseEscapingBoundRegions<'tcx> {
1002 tcx: TyCtxt<'tcx>,
1003 binder: ty::DebruijnIndex,
1004}
1005
1006impl<'tcx> TypeFolder<TyCtxt<'tcx>> for EraseEscapingBoundRegions<'tcx> {
1007 fn cx(&self) -> TyCtxt<'tcx> {
1008 self.tcx
1009 }
1010
1011 fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
1012 where
1013 T: TypeFoldable<TyCtxt<'tcx>>,
1014 {
1015 self.binder.shift_in(1);
1016 let result = t.super_fold_with(self);
1017 self.binder.shift_out(1);
1018 result
1019 }
1020
1021 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
1022 if let ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), _) = r.kind()
1023 && debruijn < self.binder
1024 {
1025 r
1026 } else {
1027 self.tcx.lifetimes.re_erased
1028 }
1029 }
1030}
1031
1032fn contains_illegal_impl_trait_in_trait<'tcx>(
1033 tcx: TyCtxt<'tcx>,
1034 fn_def_id: DefId,
1035 ty: ty::Binder<'tcx, Ty<'tcx>>,
1036) -> Option<MethodViolation> {
1037 if !ty.has_aliases() {
1038 return None;
1040 }
1041
1042 let ty = tcx.liberate_late_bound_regions(fn_def_id, ty);
1043
1044 if tcx.asyncness(fn_def_id).is_async() {
1045 Some(MethodViolation::AsyncFn)
1047 } else {
1048 ty.visit_with(&mut IllegalRpititVisitor { tcx }).break_value()
1049 }
1050}
1051
1052struct IllegalRpititVisitor<'tcx> {
1053 tcx: TyCtxt<'tcx>,
1054}
1055
1056impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalRpititVisitor<'tcx> {
1057 type Result = ControlFlow<MethodViolation>;
1058
1059 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
1060 if let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. }) = *ty.kind()
1061 && self.tcx.is_impl_trait_in_trait(def_id)
1062 {
1063 ControlFlow::Break(MethodViolation::ReferencesImplTraitInTrait(
1064 self.tcx.def_span(def_id),
1065 ))
1066 } else {
1067 ty.super_visit_with(self)
1068 }
1069 }
1070}
1071
1072pub(crate) fn provide(providers: &mut Providers) {
1073 *providers = Providers {
1074 dyn_compatibility_violations,
1075 is_dyn_compatible,
1076 generics_require_sized_self,
1077 ..*providers
1078 };
1079}