]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/object_safety.rs
Rollup merge of #90626 - rusticstuff:be-more-accepting, r=jyn514
[rust.git] / compiler / rustc_trait_selection / src / traits / object_safety.rs
1 //! "Object safety" refers to the ability for a trait to be converted
2 //! to an object. In general, traits may only be converted to an
3 //! object if all of their methods meet certain criteria. In particular,
4 //! they must:
5 //!
6 //!   - have a suitable receiver from which we can extract a vtable and coerce to a "thin" version
7 //!     that doesn't contain the vtable;
8 //!   - not reference the erased type `Self` except for in this receiver;
9 //!   - not have generic type parameters.
10
11 use super::elaborate_predicates;
12
13 use crate::infer::TyCtxtInferExt;
14 use crate::traits::const_evaluatable::{self, AbstractConst};
15 use crate::traits::query::evaluate_obligation::InferCtxtExt;
16 use crate::traits::{self, Obligation, ObligationCause};
17 use rustc_errors::FatalError;
18 use rustc_hir as hir;
19 use rustc_hir::def_id::DefId;
20 use rustc_middle::ty::subst::{GenericArg, InternalSubsts, Subst};
21 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitor, WithConstness};
22 use rustc_middle::ty::{Predicate, ToPredicate};
23 use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY;
24 use rustc_span::symbol::Symbol;
25 use rustc_span::{MultiSpan, Span};
26 use smallvec::SmallVec;
27
28 use std::array;
29 use std::iter;
30 use std::ops::ControlFlow;
31
32 pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation};
33
34 /// Returns the object safety violations that affect
35 /// astconv -- currently, `Self` in supertraits. This is needed
36 /// because `object_safety_violations` can't be used during
37 /// type collection.
38 pub fn astconv_object_safety_violations(
39     tcx: TyCtxt<'_>,
40     trait_def_id: DefId,
41 ) -> Vec<ObjectSafetyViolation> {
42     debug_assert!(tcx.generics_of(trait_def_id).has_self);
43     let violations = traits::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(ObjectSafetyViolation::SupertraitSelf)
47         .collect();
48
49     debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
50
51     violations
52 }
53
54 fn object_safety_violations(
55     tcx: TyCtxt<'tcx>,
56     trait_def_id: DefId,
57 ) -> &'tcx [ObjectSafetyViolation] {
58     debug_assert!(tcx.generics_of(trait_def_id).has_self);
59     debug!("object_safety_violations: {:?}", trait_def_id);
60
61     tcx.arena.alloc_from_iter(
62         traits::supertrait_def_ids(tcx, trait_def_id)
63             .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id)),
64     )
65 }
66
67 /// We say a method is *vtable safe* if it can be invoked on a trait
68 /// object. Note that object-safe traits can have some
69 /// non-vtable-safe methods, so long as they require `Self: Sized` or
70 /// otherwise ensure that they cannot be used when `Self = Trait`.
71 pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
72     debug_assert!(tcx.generics_of(trait_def_id).has_self);
73     debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
74     // Any method that has a `Self: Sized` bound cannot be called.
75     if generics_require_sized_self(tcx, method.def_id) {
76         return false;
77     }
78
79     match virtual_call_violation_for_method(tcx, trait_def_id, method) {
80         None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
81         Some(_) => false,
82     }
83 }
84
85 fn object_safety_violations_for_trait(
86     tcx: TyCtxt<'_>,
87     trait_def_id: DefId,
88 ) -> Vec<ObjectSafetyViolation> {
89     // Check methods for violations.
90     let mut violations: Vec<_> = tcx
91         .associated_items(trait_def_id)
92         .in_definition_order()
93         .filter(|item| item.kind == ty::AssocKind::Fn)
94         .filter_map(|item| {
95             object_safety_violation_for_method(tcx, trait_def_id, &item)
96                 .map(|(code, span)| ObjectSafetyViolation::Method(item.ident.name, code, span))
97         })
98         .filter(|violation| {
99             if let ObjectSafetyViolation::Method(
100                 _,
101                 MethodViolationCode::WhereClauseReferencesSelf,
102                 span,
103             ) = violation
104             {
105                 lint_object_unsafe_trait(tcx, *span, trait_def_id, violation);
106                 false
107             } else {
108                 true
109             }
110         })
111         .collect();
112
113     // Check the trait itself.
114     if trait_has_sized_self(tcx, trait_def_id) {
115         // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
116         let spans = get_sized_bounds(tcx, trait_def_id);
117         violations.push(ObjectSafetyViolation::SizedSelf(spans));
118     }
119     let spans = predicates_reference_self(tcx, trait_def_id, false);
120     if !spans.is_empty() {
121         violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
122     }
123     let spans = bounds_reference_self(tcx, trait_def_id);
124     if !spans.is_empty() {
125         violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
126     }
127
128     violations.extend(
129         tcx.associated_items(trait_def_id)
130             .in_definition_order()
131             .filter(|item| item.kind == ty::AssocKind::Const)
132             .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span)),
133     );
134
135     violations.extend(
136         tcx.associated_items(trait_def_id)
137             .in_definition_order()
138             .filter(|item| item.kind == ty::AssocKind::Type)
139             .filter(|item| !tcx.generics_of(item.def_id).params.is_empty())
140             .map(|item| ObjectSafetyViolation::GAT(item.ident.name, item.ident.span)),
141     );
142
143     debug!(
144         "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
145         trait_def_id, violations
146     );
147
148     violations
149 }
150
151 /// Lint object-unsafe trait.
152 fn lint_object_unsafe_trait(
153     tcx: TyCtxt<'_>,
154     span: Span,
155     trait_def_id: DefId,
156     violation: &ObjectSafetyViolation,
157 ) {
158     // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
159     // It's also hard to get a use site span, so we use the method definition span.
160     tcx.struct_span_lint_hir(WHERE_CLAUSES_OBJECT_SAFETY, hir::CRATE_HIR_ID, span, |lint| {
161         let mut err = lint.build(&format!(
162             "the trait `{}` cannot be made into an object",
163             tcx.def_path_str(trait_def_id)
164         ));
165         let node = tcx.hir().get_if_local(trait_def_id);
166         let mut spans = MultiSpan::from_span(span);
167         if let Some(hir::Node::Item(item)) = node {
168             spans.push_span_label(
169                 item.ident.span,
170                 "this trait cannot be made into an object...".into(),
171             );
172             spans.push_span_label(span, format!("...because {}", violation.error_msg()));
173         } else {
174             spans.push_span_label(
175                 span,
176                 format!(
177                     "the trait cannot be made into an object because {}",
178                     violation.error_msg()
179                 ),
180             );
181         };
182         err.span_note(
183             spans,
184             "for a trait to be \"object safe\" it needs to allow building a vtable to allow the \
185              call to be resolvable dynamically; for more information visit \
186              <https://doc.rust-lang.org/reference/items/traits.html#object-safety>",
187         );
188         if node.is_some() {
189             // Only provide the help if its a local trait, otherwise it's not
190             violation.solution(&mut err);
191         }
192         err.emit();
193     });
194 }
195
196 fn sized_trait_bound_spans<'tcx>(
197     tcx: TyCtxt<'tcx>,
198     bounds: hir::GenericBounds<'tcx>,
199 ) -> impl 'tcx + Iterator<Item = Span> {
200     bounds.iter().filter_map(move |b| match b {
201         hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
202             if trait_has_sized_self(
203                 tcx,
204                 trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
205             ) =>
206         {
207             // Fetch spans for supertraits that are `Sized`: `trait T: Super`
208             Some(trait_ref.span)
209         }
210         _ => None,
211     })
212 }
213
214 fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
215     tcx.hir()
216         .get_if_local(trait_def_id)
217         .and_then(|node| match node {
218             hir::Node::Item(hir::Item {
219                 kind: hir::ItemKind::Trait(.., generics, bounds, _),
220                 ..
221             }) => Some(
222                 generics
223                     .where_clause
224                     .predicates
225                     .iter()
226                     .filter_map(|pred| {
227                         match pred {
228                             hir::WherePredicate::BoundPredicate(pred)
229                                 if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
230                             {
231                                 // Fetch spans for trait bounds that are Sized:
232                                 // `trait T where Self: Pred`
233                                 Some(sized_trait_bound_spans(tcx, pred.bounds))
234                             }
235                             _ => None,
236                         }
237                     })
238                     .flatten()
239                     // Fetch spans for supertraits that are `Sized`: `trait T: Super`.
240                     .chain(sized_trait_bound_spans(tcx, bounds))
241                     .collect::<SmallVec<[Span; 1]>>(),
242             ),
243             _ => None,
244         })
245         .unwrap_or_else(SmallVec::new)
246 }
247
248 fn predicates_reference_self(
249     tcx: TyCtxt<'_>,
250     trait_def_id: DefId,
251     supertraits_only: bool,
252 ) -> SmallVec<[Span; 1]> {
253     let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
254     let predicates = if supertraits_only {
255         tcx.super_predicates_of(trait_def_id)
256     } else {
257         tcx.predicates_of(trait_def_id)
258     };
259     predicates
260         .predicates
261         .iter()
262         .map(|&(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp))
263         .filter_map(|predicate| predicate_references_self(tcx, predicate))
264         .collect()
265 }
266
267 fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
268     tcx.associated_items(trait_def_id)
269         .in_definition_order()
270         .filter(|item| item.kind == ty::AssocKind::Type)
271         .flat_map(|item| tcx.explicit_item_bounds(item.def_id))
272         .filter_map(|pred_span| predicate_references_self(tcx, *pred_span))
273         .collect()
274 }
275
276 fn predicate_references_self(
277     tcx: TyCtxt<'tcx>,
278     (predicate, sp): (ty::Predicate<'tcx>, Span),
279 ) -> Option<Span> {
280     let self_ty = tcx.types.self_param;
281     let has_self_ty = |arg: &GenericArg<'tcx>| arg.walk(tcx).any(|arg| arg == self_ty.into());
282     match predicate.kind().skip_binder() {
283         ty::PredicateKind::Trait(ref data) => {
284             // In the case of a trait predicate, we can skip the "self" type.
285             if data.trait_ref.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
286         }
287         ty::PredicateKind::Projection(ref data) => {
288             // And similarly for projections. This should be redundant with
289             // the previous check because any projection should have a
290             // matching `Trait` predicate with the same inputs, but we do
291             // the check to be safe.
292             //
293             // It's also won't be redundant if we allow type-generic associated
294             // types for trait objects.
295             //
296             // Note that we *do* allow projection *outputs* to contain
297             // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
298             // we just require the user to specify *both* outputs
299             // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
300             //
301             // This is ALT2 in issue #56288, see that for discussion of the
302             // possible alternatives.
303             if data.projection_ty.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
304         }
305         ty::PredicateKind::WellFormed(..)
306         | ty::PredicateKind::ObjectSafe(..)
307         | ty::PredicateKind::TypeOutlives(..)
308         | ty::PredicateKind::RegionOutlives(..)
309         | ty::PredicateKind::ClosureKind(..)
310         | ty::PredicateKind::Subtype(..)
311         | ty::PredicateKind::Coerce(..)
312         | ty::PredicateKind::ConstEvaluatable(..)
313         | ty::PredicateKind::ConstEquate(..)
314         | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
315     }
316 }
317
318 fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
319     generics_require_sized_self(tcx, trait_def_id)
320 }
321
322 fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
323     let sized_def_id = match tcx.lang_items().sized_trait() {
324         Some(def_id) => def_id,
325         None => {
326             return false; /* No Sized trait, can't require it! */
327         }
328     };
329
330     // Search for a predicate like `Self : Sized` amongst the trait bounds.
331     let predicates = tcx.predicates_of(def_id);
332     let predicates = predicates.instantiate_identity(tcx).predicates;
333     elaborate_predicates(tcx, predicates.into_iter()).any(|obligation| {
334         match obligation.predicate.kind().skip_binder() {
335             ty::PredicateKind::Trait(ref trait_pred) => {
336                 trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
337             }
338             ty::PredicateKind::Projection(..)
339             | ty::PredicateKind::Subtype(..)
340             | ty::PredicateKind::Coerce(..)
341             | ty::PredicateKind::RegionOutlives(..)
342             | ty::PredicateKind::WellFormed(..)
343             | ty::PredicateKind::ObjectSafe(..)
344             | ty::PredicateKind::ClosureKind(..)
345             | ty::PredicateKind::TypeOutlives(..)
346             | ty::PredicateKind::ConstEvaluatable(..)
347             | ty::PredicateKind::ConstEquate(..)
348             | ty::PredicateKind::TypeWellFormedFromEnv(..) => false,
349         }
350     })
351 }
352
353 /// Returns `Some(_)` if this method makes the containing trait not object safe.
354 fn object_safety_violation_for_method(
355     tcx: TyCtxt<'_>,
356     trait_def_id: DefId,
357     method: &ty::AssocItem,
358 ) -> Option<(MethodViolationCode, Span)> {
359     debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
360     // Any method that has a `Self : Sized` requisite is otherwise
361     // exempt from the regulations.
362     if generics_require_sized_self(tcx, method.def_id) {
363         return None;
364     }
365
366     let violation = virtual_call_violation_for_method(tcx, trait_def_id, method);
367     // Get an accurate span depending on the violation.
368     violation.map(|v| {
369         let node = tcx.hir().get_if_local(method.def_id);
370         let span = match (v, node) {
371             (MethodViolationCode::ReferencesSelfInput(arg), Some(node)) => node
372                 .fn_decl()
373                 .and_then(|decl| decl.inputs.get(arg + 1))
374                 .map_or(method.ident.span, |arg| arg.span),
375             (MethodViolationCode::UndispatchableReceiver, Some(node)) => node
376                 .fn_decl()
377                 .and_then(|decl| decl.inputs.get(0))
378                 .map_or(method.ident.span, |arg| arg.span),
379             (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
380                 node.fn_decl().map_or(method.ident.span, |decl| decl.output.span())
381             }
382             _ => method.ident.span,
383         };
384         (v, span)
385     })
386 }
387
388 /// Returns `Some(_)` if this method cannot be called on a trait
389 /// object; this does not necessarily imply that the enclosing trait
390 /// is not object safe, because the method might have a where clause
391 /// `Self:Sized`.
392 fn virtual_call_violation_for_method<'tcx>(
393     tcx: TyCtxt<'tcx>,
394     trait_def_id: DefId,
395     method: &ty::AssocItem,
396 ) -> Option<MethodViolationCode> {
397     let sig = tcx.fn_sig(method.def_id);
398
399     // The method's first parameter must be named `self`
400     if !method.fn_has_self_parameter {
401         // We'll attempt to provide a structured suggestion for `Self: Sized`.
402         let sugg =
403             tcx.hir().get_if_local(method.def_id).as_ref().and_then(|node| node.generics()).map(
404                 |generics| match generics.where_clause.predicates {
405                     [] => (" where Self: Sized", generics.where_clause.span),
406                     [.., pred] => (", Self: Sized", pred.span().shrink_to_hi()),
407                 },
408             );
409         // Get the span pointing at where the `self` receiver should be.
410         let sm = tcx.sess.source_map();
411         let self_span = method.ident.span.to(tcx
412             .hir()
413             .span_if_local(method.def_id)
414             .unwrap_or_else(|| sm.next_point(method.ident.span))
415             .shrink_to_hi());
416         let self_span = sm.span_through_char(self_span, '(').shrink_to_hi();
417         return Some(MethodViolationCode::StaticMethod(
418             sugg,
419             self_span,
420             !sig.inputs().skip_binder().is_empty(),
421         ));
422     }
423
424     for (i, &input_ty) in sig.skip_binder().inputs()[1..].iter().enumerate() {
425         if contains_illegal_self_type_reference(tcx, trait_def_id, sig.rebind(input_ty)) {
426             return Some(MethodViolationCode::ReferencesSelfInput(i));
427         }
428     }
429     if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output()) {
430         return Some(MethodViolationCode::ReferencesSelfOutput);
431     }
432
433     // We can't monomorphize things like `fn foo<A>(...)`.
434     let own_counts = tcx.generics_of(method.def_id).own_counts();
435     if own_counts.types + own_counts.consts != 0 {
436         return Some(MethodViolationCode::Generic);
437     }
438
439     if tcx
440         .predicates_of(method.def_id)
441         .predicates
442         .iter()
443         // A trait object can't claim to live more than the concrete type,
444         // so outlives predicates will always hold.
445         .cloned()
446         .filter(|(p, _)| p.to_opt_type_outlives().is_none())
447         .any(|pred| contains_illegal_self_type_reference(tcx, trait_def_id, pred))
448     {
449         return Some(MethodViolationCode::WhereClauseReferencesSelf);
450     }
451
452     let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
453
454     // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
455     // However, this is already considered object-safe. We allow it as a special case here.
456     // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
457     // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
458     if receiver_ty != tcx.types.self_param {
459         if !receiver_is_dispatchable(tcx, method, receiver_ty) {
460             return Some(MethodViolationCode::UndispatchableReceiver);
461         } else {
462             // Do sanity check to make sure the receiver actually has the layout of a pointer.
463
464             use rustc_target::abi::Abi;
465
466             let param_env = tcx.param_env(method.def_id);
467
468             let abi_of_ty = |ty: Ty<'tcx>| -> Option<Abi> {
469                 match tcx.layout_of(param_env.and(ty)) {
470                     Ok(layout) => Some(layout.abi),
471                     Err(err) => {
472                         // #78372
473                         tcx.sess.delay_span_bug(
474                             tcx.def_span(method.def_id),
475                             &format!("error: {}\n while computing layout for type {:?}", err, ty),
476                         );
477                         None
478                     }
479                 }
480             };
481
482             // e.g., `Rc<()>`
483             let unit_receiver_ty =
484                 receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
485
486             match abi_of_ty(unit_receiver_ty) {
487                 Some(Abi::Scalar(..)) => (),
488                 abi => {
489                     tcx.sess.delay_span_bug(
490                         tcx.def_span(method.def_id),
491                         &format!(
492                             "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
493                             abi
494                         ),
495                     );
496                 }
497             }
498
499             let trait_object_ty =
500                 object_ty_for_trait(tcx, trait_def_id, tcx.mk_region(ty::ReStatic));
501
502             // e.g., `Rc<dyn Trait>`
503             let trait_object_receiver =
504                 receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
505
506             match abi_of_ty(trait_object_receiver) {
507                 Some(Abi::ScalarPair(..)) => (),
508                 abi => {
509                     tcx.sess.delay_span_bug(
510                         tcx.def_span(method.def_id),
511                         &format!(
512                             "receiver when `Self = {}` should have a ScalarPair ABI; found {:?}",
513                             trait_object_ty, abi
514                         ),
515                     );
516                 }
517             }
518         }
519     }
520
521     None
522 }
523
524 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
525 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
526 fn receiver_for_self_ty<'tcx>(
527     tcx: TyCtxt<'tcx>,
528     receiver_ty: Ty<'tcx>,
529     self_ty: Ty<'tcx>,
530     method_def_id: DefId,
531 ) -> Ty<'tcx> {
532     debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
533     let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
534         if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
535     });
536
537     let result = receiver_ty.subst(tcx, substs);
538     debug!(
539         "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
540         receiver_ty, self_ty, method_def_id, result
541     );
542     result
543 }
544
545 /// Creates the object type for the current trait. For example,
546 /// if the current trait is `Deref`, then this will be
547 /// `dyn Deref<Target = Self::Target> + 'static`.
548 fn object_ty_for_trait<'tcx>(
549     tcx: TyCtxt<'tcx>,
550     trait_def_id: DefId,
551     lifetime: ty::Region<'tcx>,
552 ) -> Ty<'tcx> {
553     debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
554
555     let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
556
557     let trait_predicate = trait_ref.map_bound(|trait_ref| {
558         ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref))
559     });
560
561     let mut associated_types = traits::supertraits(tcx, trait_ref)
562         .flat_map(|super_trait_ref| {
563             tcx.associated_items(super_trait_ref.def_id())
564                 .in_definition_order()
565                 .map(move |item| (super_trait_ref, item))
566         })
567         .filter(|(_, item)| item.kind == ty::AssocKind::Type)
568         .collect::<Vec<_>>();
569
570     // existential predicates need to be in a specific order
571     associated_types.sort_by_cached_key(|(_, item)| tcx.def_path_hash(item.def_id));
572
573     let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
574         // We *can* get bound lifetimes here in cases like
575         // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
576         super_trait_ref.map_bound(|super_trait_ref| {
577             ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
578                 ty: tcx.mk_projection(item.def_id, super_trait_ref.substs),
579                 item_def_id: item.def_id,
580                 substs: super_trait_ref.substs,
581             })
582         })
583     });
584
585     let existential_predicates = tcx
586         .mk_poly_existential_predicates(iter::once(trait_predicate).chain(projection_predicates));
587
588     let object_ty = tcx.mk_dynamic(existential_predicates, lifetime);
589
590     debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
591
592     object_ty
593 }
594
595 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
596 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
597 /// in the following way:
598 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
599 /// - require the following bound:
600 ///
601 ///   ```
602 ///   Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
603 ///   ```
604 ///
605 ///   where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
606 ///   (substitution notation).
607 ///
608 /// Some examples of receiver types and their required obligation:
609 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
610 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
611 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
612 ///
613 /// The only case where the receiver is not dispatchable, but is still a valid receiver
614 /// type (just not object-safe), is when there is more than one level of pointer indirection.
615 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
616 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
617 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
618 /// contained by the trait object, because the object that needs to be coerced is behind
619 /// a pointer.
620 ///
621 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
622 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
623 /// is stabilized, see tracking issue <https://github.com/rust-lang/rust/issues/43561>).
624 /// Instead, we fudge a little by introducing a new type parameter `U` such that
625 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
626 /// Written as a chalk-style query:
627 ///
628 ///     forall (U: Trait + ?Sized) {
629 ///         if (Self: Unsize<U>) {
630 ///             Receiver: DispatchFromDyn<Receiver[Self => U]>
631 ///         }
632 ///     }
633 ///
634 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
635 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
636 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
637 //
638 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
639 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
640 // `self: Wrapper<Self>`.
641 #[allow(dead_code)]
642 fn receiver_is_dispatchable<'tcx>(
643     tcx: TyCtxt<'tcx>,
644     method: &ty::AssocItem,
645     receiver_ty: Ty<'tcx>,
646 ) -> bool {
647     debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
648
649     let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
650     let (Some(unsize_did), Some(dispatch_from_dyn_did)) = traits else {
651         debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
652         return false;
653     };
654
655     // the type `U` in the query
656     // use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
657     // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
658     // replace this with `dyn Trait`
659     let unsized_self_ty: Ty<'tcx> =
660         tcx.mk_ty_param(u32::MAX, Symbol::intern("RustaceansAreAwesome"));
661
662     // `Receiver[Self => U]`
663     let unsized_receiver_ty =
664         receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
665
666     // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
667     // `U: ?Sized` is already implied here
668     let param_env = {
669         let param_env = tcx.param_env(method.def_id);
670
671         // Self: Unsize<U>
672         let unsize_predicate = ty::Binder::dummy(ty::TraitRef {
673             def_id: unsize_did,
674             substs: tcx.mk_substs_trait(tcx.types.self_param, &[unsized_self_ty.into()]),
675         })
676         .without_const()
677         .to_predicate(tcx);
678
679         // U: Trait<Arg1, ..., ArgN>
680         let trait_predicate = {
681             let substs =
682                 InternalSubsts::for_item(tcx, method.container.assert_trait(), |param, _| {
683                     if param.index == 0 {
684                         unsized_self_ty.into()
685                     } else {
686                         tcx.mk_param_from_def(param)
687                     }
688                 });
689
690             ty::Binder::dummy(ty::TraitRef { def_id: unsize_did, substs })
691                 .without_const()
692                 .to_predicate(tcx)
693         };
694
695         let caller_bounds: Vec<Predicate<'tcx>> = param_env
696             .caller_bounds()
697             .iter()
698             .chain(array::IntoIter::new([unsize_predicate, trait_predicate]))
699             .collect();
700
701         ty::ParamEnv::new(tcx.intern_predicates(&caller_bounds), param_env.reveal())
702     };
703
704     // Receiver: DispatchFromDyn<Receiver[Self => U]>
705     let obligation = {
706         let predicate = ty::Binder::dummy(ty::TraitRef {
707             def_id: dispatch_from_dyn_did,
708             substs: tcx.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
709         })
710         .without_const()
711         .to_predicate(tcx);
712
713         Obligation::new(ObligationCause::dummy(), param_env, predicate)
714     };
715
716     tcx.infer_ctxt().enter(|ref infcx| {
717         // the receiver is dispatchable iff the obligation holds
718         infcx.predicate_must_hold_modulo_regions(&obligation)
719     })
720 }
721
722 fn contains_illegal_self_type_reference<'tcx, T: TypeFoldable<'tcx>>(
723     tcx: TyCtxt<'tcx>,
724     trait_def_id: DefId,
725     value: T,
726 ) -> bool {
727     // This is somewhat subtle. In general, we want to forbid
728     // references to `Self` in the argument and return types,
729     // since the value of `Self` is erased. However, there is one
730     // exception: it is ok to reference `Self` in order to access
731     // an associated type of the current trait, since we retain
732     // the value of those associated types in the object type
733     // itself.
734     //
735     // ```rust
736     // trait SuperTrait {
737     //     type X;
738     // }
739     //
740     // trait Trait : SuperTrait {
741     //     type Y;
742     //     fn foo(&self, x: Self) // bad
743     //     fn foo(&self) -> Self // bad
744     //     fn foo(&self) -> Option<Self> // bad
745     //     fn foo(&self) -> Self::Y // OK, desugars to next example
746     //     fn foo(&self) -> <Self as Trait>::Y // OK
747     //     fn foo(&self) -> Self::X // OK, desugars to next example
748     //     fn foo(&self) -> <Self as SuperTrait>::X // OK
749     // }
750     // ```
751     //
752     // However, it is not as simple as allowing `Self` in a projected
753     // type, because there are illegal ways to use `Self` as well:
754     //
755     // ```rust
756     // trait Trait : SuperTrait {
757     //     ...
758     //     fn foo(&self) -> <Self as SomeOtherTrait>::X;
759     // }
760     // ```
761     //
762     // Here we will not have the type of `X` recorded in the
763     // object type, and we cannot resolve `Self as SomeOtherTrait`
764     // without knowing what `Self` is.
765
766     struct IllegalSelfTypeVisitor<'tcx> {
767         tcx: TyCtxt<'tcx>,
768         trait_def_id: DefId,
769         supertraits: Option<Vec<DefId>>,
770     }
771
772     impl<'tcx> TypeVisitor<'tcx> for IllegalSelfTypeVisitor<'tcx> {
773         type BreakTy = ();
774         fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
775             Some(self.tcx)
776         }
777
778         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
779             match t.kind() {
780                 ty::Param(_) => {
781                     if t == self.tcx.types.self_param {
782                         ControlFlow::BREAK
783                     } else {
784                         ControlFlow::CONTINUE
785                     }
786                 }
787                 ty::Projection(ref data) => {
788                     // This is a projected type `<Foo as SomeTrait>::X`.
789
790                     // Compute supertraits of current trait lazily.
791                     if self.supertraits.is_none() {
792                         let trait_ref = ty::TraitRef::identity(self.tcx, self.trait_def_id);
793                         self.supertraits = Some(
794                             traits::supertraits(self.tcx, trait_ref).map(|t| t.def_id()).collect(),
795                         );
796                     }
797
798                     // Determine whether the trait reference `Foo as
799                     // SomeTrait` is in fact a supertrait of the
800                     // current trait. In that case, this type is
801                     // legal, because the type `X` will be specified
802                     // in the object type.  Note that we can just use
803                     // direct equality here because all of these types
804                     // are part of the formal parameter listing, and
805                     // hence there should be no inference variables.
806                     let is_supertrait_of_current_trait = self
807                         .supertraits
808                         .as_ref()
809                         .unwrap()
810                         .contains(&data.trait_ref(self.tcx).def_id);
811
812                     if is_supertrait_of_current_trait {
813                         ControlFlow::CONTINUE // do not walk contained types, do not report error, do collect $200
814                     } else {
815                         t.super_visit_with(self) // DO walk contained types, POSSIBLY reporting an error
816                     }
817                 }
818                 _ => t.super_visit_with(self), // walk contained types, if any
819             }
820         }
821
822         fn visit_unevaluated_const(
823             &mut self,
824             uv: ty::Unevaluated<'tcx>,
825         ) -> ControlFlow<Self::BreakTy> {
826             // Constants can only influence object safety if they reference `Self`.
827             // This is only possible for unevaluated constants, so we walk these here.
828             //
829             // If `AbstractConst::new` returned an error we already failed compilation
830             // so we don't have to emit an additional error here.
831             //
832             // We currently recurse into abstract consts here but do not recurse in
833             // `is_const_evaluatable`. This means that the object safety check is more
834             // liberal than the const eval check.
835             //
836             // This shouldn't really matter though as we can't really use any
837             // constants which are not considered const evaluatable.
838             use rustc_middle::thir::abstract_const::Node;
839             if let Ok(Some(ct)) = AbstractConst::new(self.tcx, uv.shrink()) {
840                 const_evaluatable::walk_abstract_const(self.tcx, ct, |node| {
841                     match node.root(self.tcx) {
842                         Node::Leaf(leaf) => self.visit_const(leaf),
843                         Node::Cast(_, _, ty) => self.visit_ty(ty),
844                         Node::Binop(..) | Node::UnaryOp(..) | Node::FunctionCall(_, _) => {
845                             ControlFlow::CONTINUE
846                         }
847                     }
848                 })
849             } else {
850                 ControlFlow::CONTINUE
851             }
852         }
853     }
854
855     value
856         .visit_with(&mut IllegalSelfTypeVisitor { tcx, trait_def_id, supertraits: None })
857         .is_break()
858 }
859
860 pub fn provide(providers: &mut ty::query::Providers) {
861     *providers = ty::query::Providers { object_safety_violations, ..*providers };
862 }