1//! "Dyn-compatibility"[^1] refers to the ability for a trait to be converted
2//! to a trait object. In general, traits may only be converted to a trait
3//! object if certain criteria are met.
4//!
5//! [^1]: Formerly known as "object safety".
67use std::ops::ControlFlow;
89use rustc_errors::FatalError;
10use rustc_hir::attrs::AttributeKind;
11use rustc_hir::def_id::DefId;
12use rustc_hir::{selfas hir, LangItem, find_attr};
13use rustc_middle::query::Providers;
14use rustc_middle::ty::{
15self, EarlyBinder, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
16TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Upcast,
17elaborate,
18};
19use rustc_span::{DUMMY_SP, Span};
20use smallvec::SmallVec;
21use tracing::{debug, instrument};
2223use super::elaborate;
24use crate::infer::TyCtxtInferExt;
25pub use crate::traits::DynCompatibilityViolation;
26use crate::traits::query::evaluate_obligation::InferCtxtExt;
27use crate::traits::{
28AssocConstViolation, MethodViolation, Obligation, ObligationCause,
29normalize_param_env_or_error, util,
30};
3132/// Returns the dyn-compatibility violations that affect HIR ty lowering.
33///
34/// Currently that is `Self` in supertraits. This is needed
35/// because `dyn_compatibility_violations` can't be used during
36/// type collection, as type collection is needed for `dyn_compatibility_violations` itself.
37x;#[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> {
42debug_assert!(tcx.generics_of(trait_def_id).has_self);
43 elaborate::supertrait_def_ids(tcx, trait_def_id)
44 .map(|def_id| predicates_reference_self(tcx, def_id, true))
45 .filter(|spans| !spans.is_empty())
46 .map(DynCompatibilityViolation::SupertraitSelf)
47 .collect()
48}
4950fn dyn_compatibility_violations(
51 tcx: TyCtxt<'_>,
52 trait_def_id: DefId,
53) -> &'_ [DynCompatibilityViolation] {
54if 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 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("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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("dyn_compatibility_violations: {0:?}",
trait_def_id) as &dyn Value))])
});
} else { ; }
};debug!("dyn_compatibility_violations: {:?}", trait_def_id);
56tcx.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}
6162fn is_dyn_compatible(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
63tcx.dyn_compatibility_violations(trait_def_id).is_empty()
64}
6566/// We say a method is *vtable safe* if it can be invoked on a trait
67/// object. Note that dyn-compatible traits can have some
68/// non-vtable-safe methods, so long as they require `Self: Sized` or
69/// otherwise ensure that they cannot be used when `Self = Trait`.
70pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: ty::AssocItem) -> bool {
71if 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 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("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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("is_vtable_safe_method({0:?}, {1:?})",
trait_def_id, method) as &dyn Value))])
});
} else { ; }
};debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
73// Any method that has a `Self: Sized` bound cannot be called.
74if tcx.generics_require_sized_self(method.def_id) {
75return false;
76 }
7778virtual_call_violations_for_method(tcx, trait_def_id, method).is_empty()
79}
8081x;#[instrument(level = "debug", skip(tcx), ret)]82fn dyn_compatibility_violations_for_trait(
83 tcx: TyCtxt<'_>,
84 trait_def_id: DefId,
85) -> Vec<DynCompatibilityViolation> {
86// Check assoc items for violations.
87let 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();
9293// Check the trait itself.
94if trait_has_sized_self(tcx, trait_def_id) {
95// We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
96let 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 }
101102let spans = predicates_reference_self(tcx, trait_def_id, false);
103if !spans.is_empty() {
104 violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
105 }
106let spans = bounds_reference_self(tcx, trait_def_id);
107if !spans.is_empty() {
108 violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
109 }
110let spans = super_predicates_have_non_lifetime_binders(tcx, trait_def_id);
111if !spans.is_empty() {
112 violations.push(DynCompatibilityViolation::SupertraitNonLifetimeBinder(spans));
113 }
114let spans = super_predicates_are_unconditionally_const(tcx, trait_def_id);
115if !spans.is_empty() {
116 violations.push(DynCompatibilityViolation::SupertraitConst(spans));
117 }
118119 violations
120}
121122fn sized_trait_bound_spans<'tcx>(
123 tcx: TyCtxt<'tcx>,
124 bounds: hir::GenericBounds<'tcx>,
125) -> impl 'tcx + Iterator<Item = Span> {
126bounds.iter().filter_map(move |b| match b {
127 hir::GenericBound::Trait(trait_ref)
128if trait_has_sized_self(
129tcx,
130trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
131 ) =>
132 {
133// Fetch spans for supertraits that are `Sized`: `trait T: Super`
134Some(trait_ref.span)
135 }
136_ => None,
137 })
138}
139140fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
141tcx.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(
147generics148 .predicates
149 .iter()
150 .filter_map(|pred| {
151match pred.kind {
152 hir::WherePredicateKind::BoundPredicate(pred)
153if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
154 {
155// Fetch spans for trait bounds that are Sized:
156 // `trait T where Self: Pred`
157Some(sized_trait_bound_spans(tcx, pred.bounds))
158 }
159_ => None,
160 }
161 })
162 .flatten()
163// Fetch spans for supertraits that are `Sized`: `trait T: Super`.
164.chain(sized_trait_bound_spans(tcx, bounds))
165 .collect::<SmallVec<[Span; 1]>>(),
166 ),
167_ => None,
168 })
169 .unwrap_or_else(SmallVec::new)
170}
171172fn predicates_reference_self(
173 tcx: TyCtxt<'_>,
174 trait_def_id: DefId,
175 supertraits_only: bool,
176) -> SmallVec<[Span; 1]> {
177let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id));
178let predicates = if supertraits_only {
179tcx.explicit_super_predicates_of(trait_def_id).skip_binder()
180 } else {
181tcx.predicates_of(trait_def_id).predicates
182 };
183predicates184 .iter()
185 .map(|&(predicate, sp)| (predicate.instantiate_supertrait(tcx, trait_ref), sp))
186 .filter_map(|(clause, sp)| {
187// Super predicates cannot allow self projections, since they're
188 // impossible to make into existential bounds without eager resolution
189 // or something.
190 // e.g. `trait A: B<Item = Self::Assoc>`.
191predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::No)
192 })
193 .collect()
194}
195196fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
197tcx.associated_items(trait_def_id)
198 .in_definition_order()
199// We're only looking at associated type bounds
200.filter(|item| item.is_type())
201// Ignore GATs with `Self: Sized`
202.filter(|item| !tcx.generics_require_sized_self(item.def_id))
203 .flat_map(|item| tcx.explicit_item_bounds(item.def_id).iter_identity_copied())
204 .filter_map(|(clause, sp)| {
205// Item bounds *can* have self projections, since they never get
206 // their self type erased.
207predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::Yes)
208 })
209 .collect()
210}
211212fn predicate_references_self<'tcx>(
213 tcx: TyCtxt<'tcx>,
214 trait_def_id: DefId,
215 predicate: ty::Clause<'tcx>,
216 sp: Span,
217 allow_self_projections: AllowSelfProjections,
218) -> Option<Span> {
219match predicate.kind().skip_binder() {
220 ty::ClauseKind::Trait(ref data) => {
221// In the case of a trait predicate, we can skip the "self" type.
222data.trait_ref.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp)
223 }
224 ty::ClauseKind::Projection(ref data) => {
225// And similarly for projections. This should be redundant with
226 // the previous check because any projection should have a
227 // matching `Trait` predicate with the same inputs, but we do
228 // the check to be safe.
229 //
230 // It's also won't be redundant if we allow type-generic associated
231 // types for trait objects.
232 //
233 // Note that we *do* allow projection *outputs* to contain
234 // `Self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
235 // we just require the user to specify *both* outputs
236 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
237 //
238 // This is ALT2 in issue #56288, see that for discussion of the
239 // possible alternatives.
240data.projection_term.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp)
241 }
242 ty::ClauseKind::ConstArgHasType(_ct, ty) => contains_illegal_self_type_reference(tcx, trait_def_id, ty, allow_self_projections).then_some(sp),
243244 ty::ClauseKind::WellFormed(..)
245 | ty::ClauseKind::TypeOutlives(..)
246 | ty::ClauseKind::RegionOutlives(..)
247// FIXME(generic_const_exprs): this can mention `Self`
248| ty::ClauseKind::ConstEvaluatable(..)
249 | ty::ClauseKind::HostEffect(..)
250 | ty::ClauseKind::UnstableFeature(_)
251 => None,
252 }
253}
254255fn super_predicates_have_non_lifetime_binders(
256 tcx: TyCtxt<'_>,
257 trait_def_id: DefId,
258) -> SmallVec<[Span; 1]> {
259tcx.explicit_super_predicates_of(trait_def_id)
260 .iter_identity_copied()
261 .filter_map(|(pred, span)| pred.has_non_region_bound_vars().then_some(span))
262 .collect()
263}
264265/// Checks for `const Trait` supertraits. We're okay with `[const] Trait`,
266/// supertraits since for a non-const instantiation of that trait, the
267/// conditionally-const supertrait is also not required to be const.
268fn super_predicates_are_unconditionally_const(
269 tcx: TyCtxt<'_>,
270 trait_def_id: DefId,
271) -> SmallVec<[Span; 1]> {
272tcx.explicit_super_predicates_of(trait_def_id)
273 .iter_identity_copied()
274 .filter_map(|(pred, span)| {
275if let ty::ClauseKind::HostEffect(_) = pred.kind().skip_binder() {
276Some(span)
277 } else {
278None279 }
280 })
281 .collect()
282}
283284fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
285tcx.generics_require_sized_self(trait_def_id)
286}
287288fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
289let Some(sized_def_id) = tcx.lang_items().sized_trait() else {
290return false; /* No Sized trait, can't require it! */
291};
292293// Search for a predicate like `Self: Sized` amongst the trait bounds.
294let predicates = tcx.predicates_of(def_id);
295let predicates = predicates.instantiate_identity(tcx).predicates;
296elaborate(tcx, predicates).any(|pred| match pred.kind().skip_binder() {
297 ty::ClauseKind::Trait(ref trait_pred) => {
298trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
299 }
300 ty::ClauseKind::RegionOutlives(_)
301 | ty::ClauseKind::TypeOutlives(_)
302 | ty::ClauseKind::Projection(_)
303 | ty::ClauseKind::ConstArgHasType(_, _)
304 | ty::ClauseKind::WellFormed(_)
305 | ty::ClauseKind::ConstEvaluatable(_)
306 | ty::ClauseKind::UnstableFeature(_)
307 | ty::ClauseKind::HostEffect(..) => false,
308 })
309}
310311x;#[instrument(level = "debug", skip(tcx), ret)]312pub fn dyn_compatibility_violations_for_assoc_item(
313 tcx: TyCtxt<'_>,
314 trait_def_id: DefId,
315 item: ty::AssocItem,
316) -> Vec<DynCompatibilityViolation> {
317// Any item that has a `Self: Sized` requisite is otherwise exempt from the regulations.
318if tcx.generics_require_sized_self(item.def_id) {
319return Vec::new();
320 }
321322let span = || item.ident(tcx).span;
323324match item.kind {
325 ty::AssocKind::Const { name } => {
326// We will permit type associated consts if they are explicitly mentioned in the
327 // trait object type. We can't check this here, as here we only check if it is
328 // guaranteed to not be possible.
329330let mut errors = Vec::new();
331332if tcx.features().min_generic_const_args() {
333if !tcx.generics_of(item.def_id).is_own_empty() {
334 errors.push(AssocConstViolation::Generic);
335 } else if !find_attr!(tcx.get_all_attrs(item.def_id), AttributeKind::TypeConst(_)) {
336 errors.push(AssocConstViolation::NonType);
337 }
338339let ty = ty::Binder::dummy(tcx.type_of(item.def_id).instantiate_identity());
340if contains_illegal_self_type_reference(
341 tcx,
342 trait_def_id,
343 ty,
344 AllowSelfProjections::Yes,
345 ) {
346 errors.push(AssocConstViolation::TypeReferencesSelf);
347 }
348 } else {
349 errors.push(AssocConstViolation::FeatureNotEnabled);
350 }
351352 errors
353 .into_iter()
354 .map(|error| DynCompatibilityViolation::AssocConst(name, error, span()))
355 .collect()
356 }
357 ty::AssocKind::Fn { name, .. } => {
358 virtual_call_violations_for_method(tcx, trait_def_id, item)
359 .into_iter()
360 .map(|v| {
361let node = tcx.hir_get_if_local(item.def_id);
362// Get an accurate span depending on the violation.
363let span = match (&v, node) {
364 (MethodViolation::ReferencesSelfInput(Some(span)), _) => *span,
365 (MethodViolation::UndispatchableReceiver(Some(span)), _) => *span,
366 (MethodViolation::ReferencesImplTraitInTrait(span), _) => *span,
367 (MethodViolation::ReferencesSelfOutput, Some(node)) => {
368 node.fn_decl().map_or(item.ident(tcx).span, |decl| decl.output.span())
369 }
370_ => span(),
371 };
372373 DynCompatibilityViolation::Method(name, v, span)
374 })
375 .collect()
376 }
377 ty::AssocKind::Type { data } => {
378if !tcx.generics_of(item.def_id).is_own_empty()
379 && let ty::AssocTypeData::Normal(name) = data
380 {
381vec![DynCompatibilityViolation::GenericAssocTy(name, span())]
382 } else {
383// We will permit associated types if they are explicitly mentioned in the trait
384 // object type. We can't check this here, as here we only check if it is
385 // guaranteed to not be possible.
386Vec::new()
387 }
388 }
389 }
390}
391392/// Returns `Some(_)` if this method cannot be called on a trait
393/// object; this does not necessarily imply that the enclosing trait
394/// is dyn-incompatible, because the method might have a where clause
395/// `Self: Sized`.
396fn virtual_call_violations_for_method<'tcx>(
397 tcx: TyCtxt<'tcx>,
398 trait_def_id: DefId,
399 method: ty::AssocItem,
400) -> Vec<MethodViolation> {
401let sig = tcx.fn_sig(method.def_id).instantiate_identity();
402403// The method's first parameter must be named `self`
404if !method.is_method() {
405let sugg = if let Some(hir::Node::TraitItem(hir::TraitItem {
406 generics,
407 kind: hir::TraitItemKind::Fn(sig, _),
408 ..
409 })) = tcx.hir_get_if_local(method.def_id).as_ref()
410 {
411let sm = tcx.sess.source_map();
412Some((
413 (
414::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 { ", " }),
415sm.span_through_char(sig.span, '(').shrink_to_hi(),
416 ),
417 (
418::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()),
419generics.tail_span_for_predicate_suggestion(),
420 ),
421 ))
422 } else {
423None424 };
425426// Not having `self` parameter messes up the later checks,
427 // so we need to return instead of pushing
428return <[_]>::into_vec(::alloc::boxed::box_new([MethodViolation::StaticMethod(sugg)]))vec![MethodViolation::StaticMethod(sugg)];
429 }
430431let mut errors = Vec::new();
432433for (i, &input_ty) in sig.skip_binder().inputs().iter().enumerate().skip(1) {
434if contains_illegal_self_type_reference(
435 tcx,
436 trait_def_id,
437 sig.rebind(input_ty),
438 AllowSelfProjections::Yes,
439 ) {
440let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
441 kind: hir::TraitItemKind::Fn(sig, _),
442 ..
443 })) = tcx.hir_get_if_local(method.def_id).as_ref()
444 {
445Some(sig.decl.inputs[i].span)
446 } else {
447None
448};
449 errors.push(MethodViolation::ReferencesSelfInput(span));
450 }
451 }
452if contains_illegal_self_type_reference(
453tcx,
454trait_def_id,
455sig.output(),
456 AllowSelfProjections::Yes,
457 ) {
458errors.push(MethodViolation::ReferencesSelfOutput);
459 }
460if let Some(error) = contains_illegal_impl_trait_in_trait(tcx, method.def_id, sig.output()) {
461errors.push(error);
462 }
463if sig.skip_binder().c_variadic {
464errors.push(MethodViolation::CVariadic);
465 }
466467// We can't monomorphize things like `fn foo<A>(...)`.
468let own_counts = tcx.generics_of(method.def_id).own_counts();
469if own_counts.types > 0 || own_counts.consts > 0 {
470errors.push(MethodViolation::Generic);
471 }
472473let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
474475// `self: Self` can't be dispatched on.
476 // However, this is considered dyn compatible. We allow it as a special case here.
477 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
478 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
479if receiver_ty != tcx.types.self_param {
480if !receiver_is_dispatchable(tcx, method, receiver_ty) {
481let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
482 kind: hir::TraitItemKind::Fn(sig, _),
483 ..
484 })) = tcx.hir_get_if_local(method.def_id).as_ref()
485 {
486Some(sig.decl.inputs[0].span)
487 } else {
488None489 };
490errors.push(MethodViolation::UndispatchableReceiver(span));
491 } else {
492// We confirm that the `receiver_is_dispatchable` is accurate later,
493 // see `check_receiver_correct`. It should be kept in sync with this code.
494}
495 }
496497// NOTE: This check happens last, because it results in a lint, and not a
498 // hard error.
499if tcx.predicates_of(method.def_id).predicates.iter().any(|&(pred, _span)| {
500// dyn Trait is okay:
501 //
502 // trait Trait {
503 // fn f(&self) where Self: 'static;
504 // }
505 //
506 // because a trait object can't claim to live longer than the concrete
507 // type. If the lifetime bound holds on dyn Trait then it's guaranteed
508 // to hold as well on the concrete type.
509if pred.as_type_outlives_clause().is_some() {
510return false;
511 }
512513// dyn Trait is okay:
514 //
515 // auto trait AutoTrait {}
516 //
517 // trait Trait {
518 // fn f(&self) where Self: AutoTrait;
519 // }
520 //
521 // because `impl AutoTrait for dyn Trait` is disallowed by coherence.
522 // Traits with a default impl are implemented for a trait object if and
523 // only if the autotrait is one of the trait object's trait bounds, like
524 // in `dyn Trait + AutoTrait`. This guarantees that trait objects only
525 // implement auto traits if the underlying type does as well.
526if let ty::ClauseKind::Trait(ty::TraitPredicate {
527 trait_ref: pred_trait_ref,
528 polarity: ty::PredicatePolarity::Positive,
529 }) = pred.kind().skip_binder()
530 && pred_trait_ref.self_ty() == tcx.types.self_param
531 && tcx.trait_is_auto(pred_trait_ref.def_id)
532 {
533// Consider bounds like `Self: Bound<Self>`. Auto traits are not
534 // allowed to have generic parameters so `auto trait Bound<T> {}`
535 // would already have reported an error at the definition of the
536 // auto trait.
537if pred_trait_ref.args.len() != 1 {
538if !tcx.dcx().has_errors().is_some() {
{
::core::panicking::panic_fmt(format_args!("auto traits cannot have generic parameters"));
}
};assert!(
539 tcx.dcx().has_errors().is_some(),
540"auto traits cannot have generic parameters"
541);
542 }
543return false;
544 }
545546contains_illegal_self_type_reference(tcx, trait_def_id, pred, AllowSelfProjections::Yes)
547 }) {
548errors.push(MethodViolation::WhereClauseReferencesSelf);
549 }
550551errors552}
553554/// Performs a type instantiation to produce the version of `receiver_ty` when `Self = self_ty`.
555/// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
556fn receiver_for_self_ty<'tcx>(
557 tcx: TyCtxt<'tcx>,
558 receiver_ty: Ty<'tcx>,
559 self_ty: Ty<'tcx>,
560 method_def_id: DefId,
561) -> Ty<'tcx> {
562{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:562",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(562u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("receiver_for_self_ty({0:?}, {1:?}, {2:?})",
receiver_ty, self_ty, method_def_id) as &dyn Value))])
});
} else { ; }
};debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
563let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
564if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
565 });
566567let result = EarlyBinder::bind(receiver_ty).instantiate(tcx, args);
568{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:568",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(568u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::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 Value))])
});
} else { ; }
};debug!(
569"receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
570 receiver_ty, self_ty, method_def_id, result
571 );
572result573}
574575/// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
576/// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
577/// in the following way:
578/// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
579/// - require the following bound:
580///
581/// ```ignore (not-rust)
582/// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
583/// ```
584///
585/// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
586/// (instantiation notation).
587///
588/// Some examples of receiver types and their required obligation:
589/// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
590/// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
591/// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
592///
593/// The only case where the receiver is not dispatchable, but is still a valid receiver
594/// type (just not dyn compatible), is when there is more than one level of pointer indirection.
595/// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
596/// is no way, or at least no inexpensive way, to coerce the receiver from the version where
597/// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
598/// contained by the trait object, because the object that needs to be coerced is behind
599/// a pointer.
600///
601/// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result in
602/// a new check that `Trait` is dyn-compatible, creating a cycle.
603/// Instead, we emulate a placeholder by introducing a new type parameter `U` such that
604/// `Self: Unsize<U>` and `U: Trait + MetaSized`, and use `U` in place of `dyn Trait`.
605///
606/// Written as a chalk-style query:
607/// ```ignore (not-rust)
608/// forall (U: Trait + MetaSized) {
609/// if (Self: Unsize<U>) {
610/// Receiver: DispatchFromDyn<Receiver[Self => U]>
611/// }
612/// }
613/// ```
614/// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
615/// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
616/// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
617//
618// FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
619// fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
620// `self: Wrapper<Self>`.
621fn receiver_is_dispatchable<'tcx>(
622 tcx: TyCtxt<'tcx>,
623 method: ty::AssocItem,
624 receiver_ty: Ty<'tcx>,
625) -> bool {
626{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:626",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(626u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("receiver_is_dispatchable: method = {0:?}, receiver_ty = {1:?}",
method, receiver_ty) as &dyn Value))])
});
} else { ; }
};debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
627628let (Some(unsize_did), Some(dispatch_from_dyn_did)) =
629 (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait())
630else {
631{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:631",
"rustc_trait_selection::traits::dyn_compatibility",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
::tracing_core::__macro_support::Option::Some(631u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("receiver_is_dispatchable: Missing `Unsize` or `DispatchFromDyn` traits")
as &dyn Value))])
});
} else { ; }
};debug!("receiver_is_dispatchable: Missing `Unsize` or `DispatchFromDyn` traits");
632return false;
633 };
634635// the type `U` in the query
636 // use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
637let unsized_self_ty: Ty<'tcx> =
638Ty::new_param(tcx, u32::MAX, rustc_span::sym::RustaceansAreAwesome);
639640// `Receiver[Self => U]`
641let unsized_receiver_ty =
642receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
643644// create a modified param env, with `Self: Unsize<U>` and `U: Trait` (and all of
645 // its supertraits) added to caller bounds. `U: MetaSized` is already implied here.
646let param_env = {
647// N.B. We generally want to emulate the construction of the `unnormalized_param_env`
648 // in the param-env query here. The fact that we don't just start with the clauses
649 // in the param-env of the method is because those are already normalized, and mixing
650 // normalized and unnormalized copies of predicates in `normalize_param_env_or_error`
651 // will cause ambiguity that the user can't really avoid.
652 //
653 // We leave out certain complexities of the param-env query here. Specifically, we:
654 // 1. Do not add `[const]` bounds since there are no `dyn const Trait`s.
655 // 2. Do not add RPITIT self projection bounds for defaulted methods, since we
656 // are not constructing a param-env for "inside" of the body of the defaulted
657 // method, so we don't really care about projecting to a specific RPIT type,
658 // and because RPITITs are not dyn compatible (yet).
659let mut predicates = tcx.predicates_of(method.def_id).instantiate_identity(tcx).predicates;
660661// Self: Unsize<U>
662let unsize_predicate =
663 ty::TraitRef::new(tcx, unsize_did, [tcx.types.self_param, unsized_self_ty]);
664predicates.push(unsize_predicate.upcast(tcx));
665666// U: Trait<Arg1, ..., ArgN>
667let trait_def_id = method.trait_container(tcx).unwrap();
668let args = GenericArgs::for_item(tcx, trait_def_id, |param, _| {
669if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) }
670 });
671let trait_predicate = ty::TraitRef::new_from_args(tcx, trait_def_id, args);
672predicates.push(trait_predicate.upcast(tcx));
673674let meta_sized_predicate = {
675let meta_sized_did = tcx.require_lang_item(LangItem::MetaSized, DUMMY_SP);
676 ty::TraitRef::new(tcx, meta_sized_did, [unsized_self_ty]).upcast(tcx)
677 };
678predicates.push(meta_sized_predicate);
679680normalize_param_env_or_error(
681tcx,
682 ty::ParamEnv::new(tcx.mk_clauses(&predicates)),
683ObligationCause::dummy_with_span(tcx.def_span(method.def_id)),
684 )
685 };
686687// Receiver: DispatchFromDyn<Receiver[Self => U]>
688let obligation = {
689let predicate =
690 ty::TraitRef::new(tcx, dispatch_from_dyn_did, [receiver_ty, unsized_receiver_ty]);
691692Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate)
693 };
694695let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
696// the receiver is dispatchable iff the obligation holds
697infcx.predicate_must_hold_modulo_regions(&obligation)
698}
699700#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllowSelfProjections { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AllowSelfProjections {
#[inline]
fn clone(&self) -> AllowSelfProjections { *self }
}Clone)]
701enum AllowSelfProjections {
702 Yes,
703 No,
704}
705706/// Check if the given value contains illegal `Self` references.
707///
708/// This is somewhat subtle. In general, we want to forbid references to `Self` in the
709/// argument and return types, since the value of `Self` is erased.
710///
711/// However, there is one exception: It is ok to reference `Self` in order to access an
712/// associated type of the current trait, since we retain the value of those associated
713/// types in the trait object type itself.
714///
715/// The same thing holds for associated consts under feature `min_generic_const_args`.
716///
717/// ```rust,ignore (example)
718/// trait SuperTrait {
719/// type X;
720/// }
721///
722/// trait Trait : SuperTrait {
723/// type Y;
724/// fn foo(&self, x: Self) // bad
725/// fn foo(&self) -> Self // bad
726/// fn foo(&self) -> Option<Self> // bad
727/// fn foo(&self) -> Self::Y // OK, desugars to next example
728/// fn foo(&self) -> <Self as Trait>::Y // OK
729/// fn foo(&self) -> Self::X // OK, desugars to next example
730/// fn foo(&self) -> <Self as SuperTrait>::X // OK
731/// }
732/// ```
733///
734/// However, it is not as simple as allowing `Self` in a projected
735/// type, because there are illegal ways to use `Self` as well:
736///
737/// ```rust,ignore (example)
738/// trait Trait : SuperTrait {
739/// ...
740/// fn foo(&self) -> <Self as SomeOtherTrait>::X;
741/// }
742/// ```
743///
744/// Here we will not have the type of `X` recorded in the
745/// object type, and we cannot resolve `Self as SomeOtherTrait`
746/// without knowing what `Self` is.
747fn contains_illegal_self_type_reference<'tcx, T: TypeVisitable<TyCtxt<'tcx>>>(
748 tcx: TyCtxt<'tcx>,
749 trait_def_id: DefId,
750 value: T,
751 allow_self_projections: AllowSelfProjections,
752) -> bool {
753value754 .visit_with(&mut IllegalSelfTypeVisitor {
755tcx,
756trait_def_id,
757 supertraits: None,
758allow_self_projections,
759 })
760 .is_break()
761}
762763struct IllegalSelfTypeVisitor<'tcx> {
764 tcx: TyCtxt<'tcx>,
765 trait_def_id: DefId,
766 supertraits: Option<Vec<ty::TraitRef<'tcx>>>,
767 allow_self_projections: AllowSelfProjections,
768}
769770impl<'tcx> IllegalSelfTypeVisitor<'tcx> {
771fn is_supertrait_of_current_trait(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
772// Compute supertraits of current trait lazily.
773let supertraits = self.supertraits.get_or_insert_with(|| {
774 util::supertraits(
775self.tcx,
776 ty::Binder::dummy(ty::TraitRef::identity(self.tcx, self.trait_def_id)),
777 )
778 .map(|trait_ref| {
779self.tcx.erase_and_anonymize_regions(
780self.tcx.instantiate_bound_regions_with_erased(trait_ref),
781 )
782 })
783 .collect()
784 });
785786// Determine whether the given trait ref is in fact a supertrait of the current trait.
787 // In that case, any derived projections are legal, because the term will be specified
788 // in the trait object type.
789 // Note that we can just use direct equality here because all of these types are part of
790 // the formal parameter listing, and hence there should be no inference variables.
791let trait_ref = trait_ref792 .fold_with(&mut EraseEscapingBoundRegions { tcx: self.tcx, binder: ty::INNERMOST });
793supertraits.contains(&trait_ref)
794 }
795}
796797impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalSelfTypeVisitor<'tcx> {
798type Result = ControlFlow<()>;
799800fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
801match ty.kind() {
802 ty::Param(_) => {
803if ty == self.tcx.types.self_param {
804 ControlFlow::Break(())
805 } else {
806 ControlFlow::Continue(())
807 }
808 }
809 ty::Alias(ty::Projection, proj) if self.tcx.is_impl_trait_in_trait(proj.def_id) => {
810// We'll deny these later in their own pass
811ControlFlow::Continue(())
812 }
813 ty::Alias(ty::Projection, proj) => {
814match self.allow_self_projections {
815 AllowSelfProjections::Yes => {
816// Only walk contained types if the parent trait is not a supertrait.
817if self.is_supertrait_of_current_trait(proj.trait_ref(self.tcx)) {
818 ControlFlow::Continue(())
819 } else {
820ty.super_visit_with(self)
821 }
822 }
823 AllowSelfProjections::No => ty.super_visit_with(self),
824 }
825 }
826_ => ty.super_visit_with(self),
827 }
828 }
829830fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
831let ct = self.tcx.expand_abstract_consts(ct);
832833match ct.kind() {
834 ty::ConstKind::Unevaluated(proj) if self.tcx.features().min_generic_const_args() => {
835match self.allow_self_projections {
836 AllowSelfProjections::Yes => {
837let trait_def_id = self.tcx.parent(proj.def);
838let trait_ref = ty::TraitRef::from_assoc(self.tcx, trait_def_id, proj.args);
839840// Only walk contained consts if the parent trait is not a supertrait.
841if self.is_supertrait_of_current_trait(trait_ref) {
842 ControlFlow::Continue(())
843 } else {
844ct.super_visit_with(self)
845 }
846 }
847 AllowSelfProjections::No => ct.super_visit_with(self),
848 }
849 }
850_ => ct.super_visit_with(self),
851 }
852 }
853}
854855struct EraseEscapingBoundRegions<'tcx> {
856 tcx: TyCtxt<'tcx>,
857 binder: ty::DebruijnIndex,
858}
859860impl<'tcx> TypeFolder<TyCtxt<'tcx>> for EraseEscapingBoundRegions<'tcx> {
861fn cx(&self) -> TyCtxt<'tcx> {
862self.tcx
863 }
864865fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
866where
867T: TypeFoldable<TyCtxt<'tcx>>,
868 {
869self.binder.shift_in(1);
870let result = t.super_fold_with(self);
871self.binder.shift_out(1);
872result873 }
874875fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
876if let ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), _) = r.kind()
877 && debruijn < self.binder
878 {
879r880 } else {
881self.tcx.lifetimes.re_erased
882 }
883 }
884}
885886fn contains_illegal_impl_trait_in_trait<'tcx>(
887 tcx: TyCtxt<'tcx>,
888 fn_def_id: DefId,
889 ty: ty::Binder<'tcx, Ty<'tcx>>,
890) -> Option<MethodViolation> {
891let ty = tcx.liberate_late_bound_regions(fn_def_id, ty);
892893if tcx.asyncness(fn_def_id).is_async() {
894// Rendering the error as a separate `async-specific` message is better.
895Some(MethodViolation::AsyncFn)
896 } else {
897ty.visit_with(&mut IllegalRpititVisitor { tcx, allowed: None }).break_value()
898 }
899}
900901struct IllegalRpititVisitor<'tcx> {
902 tcx: TyCtxt<'tcx>,
903 allowed: Option<ty::AliasTy<'tcx>>,
904}
905906impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalRpititVisitor<'tcx> {
907type Result = ControlFlow<MethodViolation>;
908909fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
910if let ty::Alias(ty::Projection, proj) = *ty.kind()
911 && Some(proj) != self.allowed
912 && self.tcx.is_impl_trait_in_trait(proj.def_id)
913 {
914 ControlFlow::Break(MethodViolation::ReferencesImplTraitInTrait(
915self.tcx.def_span(proj.def_id),
916 ))
917 } else {
918ty.super_visit_with(self)
919 }
920 }
921}
922923pub(crate) fn provide(providers: &mut Providers) {
924*providers = Providers {
925dyn_compatibility_violations,
926is_dyn_compatible,
927generics_require_sized_self,
928 ..*providers929 };
930}