]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/object_safety.rs
Rollup merge of #91847 - BoxyUwU:generic_arg_infer_fixme, r=lcnr
[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};
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::iter;
29 use std::ops::ControlFlow;
30
31 pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation};
32
33 /// Returns the object safety violations that affect
34 /// astconv -- currently, `Self` in supertraits. This is needed
35 /// because `object_safety_violations` can't be used during
36 /// type collection.
37 pub fn astconv_object_safety_violations(
38     tcx: TyCtxt<'_>,
39     trait_def_id: DefId,
40 ) -> Vec<ObjectSafetyViolation> {
41     debug_assert!(tcx.generics_of(trait_def_id).has_self);
42     let violations = traits::supertrait_def_ids(tcx, trait_def_id)
43         .map(|def_id| predicates_reference_self(tcx, def_id, true))
44         .filter(|spans| !spans.is_empty())
45         .map(ObjectSafetyViolation::SupertraitSelf)
46         .collect();
47
48     debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
49
50     violations
51 }
52
53 fn object_safety_violations(
54     tcx: TyCtxt<'tcx>,
55     trait_def_id: DefId,
56 ) -> &'tcx [ObjectSafetyViolation] {
57     debug_assert!(tcx.generics_of(trait_def_id).has_self);
58     debug!("object_safety_violations: {:?}", trait_def_id);
59
60     tcx.arena.alloc_from_iter(
61         traits::supertrait_def_ids(tcx, trait_def_id)
62             .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id)),
63     )
64 }
65
66 /// We say a method is *vtable safe* if it can be invoked on a trait
67 /// object. Note that object-safe 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`.
70 pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
71     debug_assert!(tcx.generics_of(trait_def_id).has_self);
72     debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
73     // Any method that has a `Self: Sized` bound cannot be called.
74     if generics_require_sized_self(tcx, method.def_id) {
75         return false;
76     }
77
78     match virtual_call_violation_for_method(tcx, trait_def_id, method) {
79         None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
80         Some(_) => false,
81     }
82 }
83
84 fn object_safety_violations_for_trait(
85     tcx: TyCtxt<'_>,
86     trait_def_id: DefId,
87 ) -> Vec<ObjectSafetyViolation> {
88     // Check methods for violations.
89     let mut violations: Vec<_> = tcx
90         .associated_items(trait_def_id)
91         .in_definition_order()
92         .filter(|item| item.kind == ty::AssocKind::Fn)
93         .filter_map(|item| {
94             object_safety_violation_for_method(tcx, trait_def_id, &item)
95                 .map(|(code, span)| ObjectSafetyViolation::Method(item.ident.name, code, span))
96         })
97         .filter(|violation| {
98             if let ObjectSafetyViolation::Method(
99                 _,
100                 MethodViolationCode::WhereClauseReferencesSelf,
101                 span,
102             ) = violation
103             {
104                 lint_object_unsafe_trait(tcx, *span, trait_def_id, violation);
105                 false
106             } else {
107                 true
108             }
109         })
110         .collect();
111
112     // Check the trait itself.
113     if trait_has_sized_self(tcx, trait_def_id) {
114         // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
115         let spans = get_sized_bounds(tcx, trait_def_id);
116         violations.push(ObjectSafetyViolation::SizedSelf(spans));
117     }
118     let spans = predicates_reference_self(tcx, trait_def_id, false);
119     if !spans.is_empty() {
120         violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
121     }
122     let spans = bounds_reference_self(tcx, trait_def_id);
123     if !spans.is_empty() {
124         violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
125     }
126
127     violations.extend(
128         tcx.associated_items(trait_def_id)
129             .in_definition_order()
130             .filter(|item| item.kind == ty::AssocKind::Const)
131             .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span)),
132     );
133
134     violations.extend(
135         tcx.associated_items(trait_def_id)
136             .in_definition_order()
137             .filter(|item| item.kind == ty::AssocKind::Type)
138             .filter(|item| !tcx.generics_of(item.def_id).params.is_empty())
139             .map(|item| ObjectSafetyViolation::GAT(item.ident.name, item.ident.span)),
140     );
141
142     debug!(
143         "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
144         trait_def_id, violations
145     );
146
147     violations
148 }
149
150 /// Lint object-unsafe trait.
151 fn lint_object_unsafe_trait(
152     tcx: TyCtxt<'_>,
153     span: Span,
154     trait_def_id: DefId,
155     violation: &ObjectSafetyViolation,
156 ) {
157     // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
158     // It's also hard to get a use site span, so we use the method definition span.
159     tcx.struct_span_lint_hir(WHERE_CLAUSES_OBJECT_SAFETY, hir::CRATE_HIR_ID, span, |lint| {
160         let mut err = lint.build(&format!(
161             "the trait `{}` cannot be made into an object",
162             tcx.def_path_str(trait_def_id)
163         ));
164         let node = tcx.hir().get_if_local(trait_def_id);
165         let mut spans = MultiSpan::from_span(span);
166         if let Some(hir::Node::Item(item)) = node {
167             spans.push_span_label(
168                 item.ident.span,
169                 "this trait cannot be made into an object...".into(),
170             );
171             spans.push_span_label(span, format!("...because {}", violation.error_msg()));
172         } else {
173             spans.push_span_label(
174                 span,
175                 format!(
176                     "the trait cannot be made into an object because {}",
177                     violation.error_msg()
178                 ),
179             );
180         };
181         err.span_note(
182             spans,
183             "for a trait to be \"object safe\" it needs to allow building a vtable to allow the \
184              call to be resolvable dynamically; for more information visit \
185              <https://doc.rust-lang.org/reference/items/traits.html#object-safety>",
186         );
187         if node.is_some() {
188             // Only provide the help if its a local trait, otherwise it's not
189             violation.solution(&mut err);
190         }
191         err.emit();
192     });
193 }
194
195 fn sized_trait_bound_spans<'tcx>(
196     tcx: TyCtxt<'tcx>,
197     bounds: hir::GenericBounds<'tcx>,
198 ) -> impl 'tcx + Iterator<Item = Span> {
199     bounds.iter().filter_map(move |b| match b {
200         hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
201             if trait_has_sized_self(
202                 tcx,
203                 trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
204             ) =>
205         {
206             // Fetch spans for supertraits that are `Sized`: `trait T: Super`
207             Some(trait_ref.span)
208         }
209         _ => None,
210     })
211 }
212
213 fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
214     tcx.hir()
215         .get_if_local(trait_def_id)
216         .and_then(|node| match node {
217             hir::Node::Item(hir::Item {
218                 kind: hir::ItemKind::Trait(.., generics, bounds, _),
219                 ..
220             }) => Some(
221                 generics
222                     .where_clause
223                     .predicates
224                     .iter()
225                     .filter_map(|pred| {
226                         match pred {
227                             hir::WherePredicate::BoundPredicate(pred)
228                                 if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
229                             {
230                                 // Fetch spans for trait bounds that are Sized:
231                                 // `trait T where Self: Pred`
232                                 Some(sized_trait_bound_spans(tcx, pred.bounds))
233                             }
234                             _ => None,
235                         }
236                     })
237                     .flatten()
238                     // Fetch spans for supertraits that are `Sized`: `trait T: Super`.
239                     .chain(sized_trait_bound_spans(tcx, bounds))
240                     .collect::<SmallVec<[Span; 1]>>(),
241             ),
242             _ => None,
243         })
244         .unwrap_or_else(SmallVec::new)
245 }
246
247 fn predicates_reference_self(
248     tcx: TyCtxt<'_>,
249     trait_def_id: DefId,
250     supertraits_only: bool,
251 ) -> SmallVec<[Span; 1]> {
252     let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
253     let predicates = if supertraits_only {
254         tcx.super_predicates_of(trait_def_id)
255     } else {
256         tcx.predicates_of(trait_def_id)
257     };
258     predicates
259         .predicates
260         .iter()
261         .map(|&(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp))
262         .filter_map(|predicate| predicate_references_self(tcx, predicate))
263         .collect()
264 }
265
266 fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
267     tcx.associated_items(trait_def_id)
268         .in_definition_order()
269         .filter(|item| item.kind == ty::AssocKind::Type)
270         .flat_map(|item| tcx.explicit_item_bounds(item.def_id))
271         .filter_map(|pred_span| predicate_references_self(tcx, *pred_span))
272         .collect()
273 }
274
275 fn predicate_references_self(
276     tcx: TyCtxt<'tcx>,
277     (predicate, sp): (ty::Predicate<'tcx>, Span),
278 ) -> Option<Span> {
279     let self_ty = tcx.types.self_param;
280     let has_self_ty = |arg: &GenericArg<'tcx>| arg.walk(tcx).any(|arg| arg == self_ty.into());
281     match predicate.kind().skip_binder() {
282         ty::PredicateKind::Trait(ref data) => {
283             // In the case of a trait predicate, we can skip the "self" type.
284             if data.trait_ref.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
285         }
286         ty::PredicateKind::Projection(ref data) => {
287             // And similarly for projections. This should be redundant with
288             // the previous check because any projection should have a
289             // matching `Trait` predicate with the same inputs, but we do
290             // the check to be safe.
291             //
292             // It's also won't be redundant if we allow type-generic associated
293             // types for trait objects.
294             //
295             // Note that we *do* allow projection *outputs* to contain
296             // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
297             // we just require the user to specify *both* outputs
298             // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
299             //
300             // This is ALT2 in issue #56288, see that for discussion of the
301             // possible alternatives.
302             if data.projection_ty.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
303         }
304         ty::PredicateKind::WellFormed(..)
305         | ty::PredicateKind::ObjectSafe(..)
306         | ty::PredicateKind::TypeOutlives(..)
307         | ty::PredicateKind::RegionOutlives(..)
308         | ty::PredicateKind::ClosureKind(..)
309         | ty::PredicateKind::Subtype(..)
310         | ty::PredicateKind::Coerce(..)
311         | ty::PredicateKind::ConstEvaluatable(..)
312         | ty::PredicateKind::ConstEquate(..)
313         | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
314     }
315 }
316
317 fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
318     generics_require_sized_self(tcx, trait_def_id)
319 }
320
321 fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
322     let sized_def_id = match tcx.lang_items().sized_trait() {
323         Some(def_id) => def_id,
324         None => {
325             return false; /* No Sized trait, can't require it! */
326         }
327     };
328
329     // Search for a predicate like `Self : Sized` amongst the trait bounds.
330     let predicates = tcx.predicates_of(def_id);
331     let predicates = predicates.instantiate_identity(tcx).predicates;
332     elaborate_predicates(tcx, predicates.into_iter()).any(|obligation| {
333         match obligation.predicate.kind().skip_binder() {
334             ty::PredicateKind::Trait(ref trait_pred) => {
335                 trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
336             }
337             ty::PredicateKind::Projection(..)
338             | ty::PredicateKind::Subtype(..)
339             | ty::PredicateKind::Coerce(..)
340             | ty::PredicateKind::RegionOutlives(..)
341             | ty::PredicateKind::WellFormed(..)
342             | ty::PredicateKind::ObjectSafe(..)
343             | ty::PredicateKind::ClosureKind(..)
344             | ty::PredicateKind::TypeOutlives(..)
345             | ty::PredicateKind::ConstEvaluatable(..)
346             | ty::PredicateKind::ConstEquate(..)
347             | ty::PredicateKind::TypeWellFormedFromEnv(..) => false,
348         }
349     })
350 }
351
352 /// Returns `Some(_)` if this method makes the containing trait not object safe.
353 fn object_safety_violation_for_method(
354     tcx: TyCtxt<'_>,
355     trait_def_id: DefId,
356     method: &ty::AssocItem,
357 ) -> Option<(MethodViolationCode, Span)> {
358     debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
359     // Any method that has a `Self : Sized` requisite is otherwise
360     // exempt from the regulations.
361     if generics_require_sized_self(tcx, method.def_id) {
362         return None;
363     }
364
365     let violation = virtual_call_violation_for_method(tcx, trait_def_id, method);
366     // Get an accurate span depending on the violation.
367     violation.map(|v| {
368         let node = tcx.hir().get_if_local(method.def_id);
369         let span = match (v, node) {
370             (MethodViolationCode::ReferencesSelfInput(arg), Some(node)) => node
371                 .fn_decl()
372                 .and_then(|decl| decl.inputs.get(arg + 1))
373                 .map_or(method.ident.span, |arg| arg.span),
374             (MethodViolationCode::UndispatchableReceiver, Some(node)) => node
375                 .fn_decl()
376                 .and_then(|decl| decl.inputs.get(0))
377                 .map_or(method.ident.span, |arg| arg.span),
378             (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
379                 node.fn_decl().map_or(method.ident.span, |decl| decl.output.span())
380             }
381             _ => method.ident.span,
382         };
383         (v, span)
384     })
385 }
386
387 /// Returns `Some(_)` if this method cannot be called on a trait
388 /// object; this does not necessarily imply that the enclosing trait
389 /// is not object safe, because the method might have a where clause
390 /// `Self:Sized`.
391 fn virtual_call_violation_for_method<'tcx>(
392     tcx: TyCtxt<'tcx>,
393     trait_def_id: DefId,
394     method: &ty::AssocItem,
395 ) -> Option<MethodViolationCode> {
396     let sig = tcx.fn_sig(method.def_id);
397
398     // The method's first parameter must be named `self`
399     if !method.fn_has_self_parameter {
400         // We'll attempt to provide a structured suggestion for `Self: Sized`.
401         let sugg =
402             tcx.hir().get_if_local(method.def_id).as_ref().and_then(|node| node.generics()).map(
403                 |generics| match generics.where_clause.predicates {
404                     [] => (" where Self: Sized", generics.where_clause.span),
405                     [.., pred] => (", Self: Sized", pred.span().shrink_to_hi()),
406                 },
407             );
408         // Get the span pointing at where the `self` receiver should be.
409         let sm = tcx.sess.source_map();
410         let self_span = method.ident.span.to(tcx
411             .hir()
412             .span_if_local(method.def_id)
413             .unwrap_or_else(|| sm.next_point(method.ident.span))
414             .shrink_to_hi());
415         let self_span = sm.span_through_char(self_span, '(').shrink_to_hi();
416         return Some(MethodViolationCode::StaticMethod(
417             sugg,
418             self_span,
419             !sig.inputs().skip_binder().is_empty(),
420         ));
421     }
422
423     for (i, &input_ty) in sig.skip_binder().inputs()[1..].iter().enumerate() {
424         if contains_illegal_self_type_reference(tcx, trait_def_id, sig.rebind(input_ty)) {
425             return Some(MethodViolationCode::ReferencesSelfInput(i));
426         }
427     }
428     if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output()) {
429         return Some(MethodViolationCode::ReferencesSelfOutput);
430     }
431
432     // We can't monomorphize things like `fn foo<A>(...)`.
433     let own_counts = tcx.generics_of(method.def_id).own_counts();
434     if own_counts.types + own_counts.consts != 0 {
435         return Some(MethodViolationCode::Generic);
436     }
437
438     if tcx
439         .predicates_of(method.def_id)
440         .predicates
441         .iter()
442         // A trait object can't claim to live more than the concrete type,
443         // so outlives predicates will always hold.
444         .cloned()
445         .filter(|(p, _)| p.to_opt_type_outlives().is_none())
446         .any(|pred| contains_illegal_self_type_reference(tcx, trait_def_id, pred))
447     {
448         return Some(MethodViolationCode::WhereClauseReferencesSelf);
449     }
450
451     let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
452
453     // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
454     // However, this is already considered object-safe. We allow it as a special case here.
455     // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
456     // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
457     if receiver_ty != tcx.types.self_param {
458         if !receiver_is_dispatchable(tcx, method, receiver_ty) {
459             return Some(MethodViolationCode::UndispatchableReceiver);
460         } else {
461             // Do sanity check to make sure the receiver actually has the layout of a pointer.
462
463             use rustc_target::abi::Abi;
464
465             let param_env = tcx.param_env(method.def_id);
466
467             let abi_of_ty = |ty: Ty<'tcx>| -> Option<Abi> {
468                 match tcx.layout_of(param_env.and(ty)) {
469                     Ok(layout) => Some(layout.abi),
470                     Err(err) => {
471                         // #78372
472                         tcx.sess.delay_span_bug(
473                             tcx.def_span(method.def_id),
474                             &format!("error: {}\n while computing layout for type {:?}", err, ty),
475                         );
476                         None
477                     }
478                 }
479             };
480
481             // e.g., `Rc<()>`
482             let unit_receiver_ty =
483                 receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
484
485             match abi_of_ty(unit_receiver_ty) {
486                 Some(Abi::Scalar(..)) => (),
487                 abi => {
488                     tcx.sess.delay_span_bug(
489                         tcx.def_span(method.def_id),
490                         &format!(
491                             "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
492                             abi
493                         ),
494                     );
495                 }
496             }
497
498             let trait_object_ty =
499                 object_ty_for_trait(tcx, trait_def_id, tcx.mk_region(ty::ReStatic));
500
501             // e.g., `Rc<dyn Trait>`
502             let trait_object_receiver =
503                 receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
504
505             match abi_of_ty(trait_object_receiver) {
506                 Some(Abi::ScalarPair(..)) => (),
507                 abi => {
508                     tcx.sess.delay_span_bug(
509                         tcx.def_span(method.def_id),
510                         &format!(
511                             "receiver when `Self = {}` should have a ScalarPair ABI; found {:?}",
512                             trait_object_ty, abi
513                         ),
514                     );
515                 }
516             }
517         }
518     }
519
520     None
521 }
522
523 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
524 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
525 fn receiver_for_self_ty<'tcx>(
526     tcx: TyCtxt<'tcx>,
527     receiver_ty: Ty<'tcx>,
528     self_ty: Ty<'tcx>,
529     method_def_id: DefId,
530 ) -> Ty<'tcx> {
531     debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
532     let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
533         if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
534     });
535
536     let result = receiver_ty.subst(tcx, substs);
537     debug!(
538         "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
539         receiver_ty, self_ty, method_def_id, result
540     );
541     result
542 }
543
544 /// Creates the object type for the current trait. For example,
545 /// if the current trait is `Deref`, then this will be
546 /// `dyn Deref<Target = Self::Target> + 'static`.
547 fn object_ty_for_trait<'tcx>(
548     tcx: TyCtxt<'tcx>,
549     trait_def_id: DefId,
550     lifetime: ty::Region<'tcx>,
551 ) -> Ty<'tcx> {
552     debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
553
554     let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
555
556     let trait_predicate = trait_ref.map_bound(|trait_ref| {
557         ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref))
558     });
559
560     let mut associated_types = traits::supertraits(tcx, trait_ref)
561         .flat_map(|super_trait_ref| {
562             tcx.associated_items(super_trait_ref.def_id())
563                 .in_definition_order()
564                 .map(move |item| (super_trait_ref, item))
565         })
566         .filter(|(_, item)| item.kind == ty::AssocKind::Type)
567         .collect::<Vec<_>>();
568
569     // existential predicates need to be in a specific order
570     associated_types.sort_by_cached_key(|(_, item)| tcx.def_path_hash(item.def_id));
571
572     let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
573         // We *can* get bound lifetimes here in cases like
574         // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
575         super_trait_ref.map_bound(|super_trait_ref| {
576             ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
577                 ty: tcx.mk_projection(item.def_id, super_trait_ref.substs),
578                 item_def_id: item.def_id,
579                 substs: super_trait_ref.substs,
580             })
581         })
582     });
583
584     let existential_predicates = tcx
585         .mk_poly_existential_predicates(iter::once(trait_predicate).chain(projection_predicates));
586
587     let object_ty = tcx.mk_dynamic(existential_predicates, lifetime);
588
589     debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
590
591     object_ty
592 }
593
594 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
595 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
596 /// in the following way:
597 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
598 /// - require the following bound:
599 ///
600 ///   ```
601 ///   Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
602 ///   ```
603 ///
604 ///   where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
605 ///   (substitution notation).
606 ///
607 /// Some examples of receiver types and their required obligation:
608 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
609 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
610 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
611 ///
612 /// The only case where the receiver is not dispatchable, but is still a valid receiver
613 /// type (just not object-safe), is when there is more than one level of pointer indirection.
614 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
615 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
616 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
617 /// contained by the trait object, because the object that needs to be coerced is behind
618 /// a pointer.
619 ///
620 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
621 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
622 /// is stabilized, see tracking issue <https://github.com/rust-lang/rust/issues/43561>).
623 /// Instead, we fudge a little by introducing a new type parameter `U` such that
624 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
625 /// Written as a chalk-style query:
626 ///
627 ///     forall (U: Trait + ?Sized) {
628 ///         if (Self: Unsize<U>) {
629 ///             Receiver: DispatchFromDyn<Receiver[Self => U]>
630 ///         }
631 ///     }
632 ///
633 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
634 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
635 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
636 //
637 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
638 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
639 // `self: Wrapper<Self>`.
640 #[allow(dead_code)]
641 fn receiver_is_dispatchable<'tcx>(
642     tcx: TyCtxt<'tcx>,
643     method: &ty::AssocItem,
644     receiver_ty: Ty<'tcx>,
645 ) -> bool {
646     debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
647
648     let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
649     let (Some(unsize_did), Some(dispatch_from_dyn_did)) = traits else {
650         debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
651         return false;
652     };
653
654     // the type `U` in the query
655     // use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
656     // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
657     // replace this with `dyn Trait`
658     let unsized_self_ty: Ty<'tcx> =
659         tcx.mk_ty_param(u32::MAX, Symbol::intern("RustaceansAreAwesome"));
660
661     // `Receiver[Self => U]`
662     let unsized_receiver_ty =
663         receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
664
665     // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
666     // `U: ?Sized` is already implied here
667     let param_env = {
668         let param_env = tcx.param_env(method.def_id);
669
670         // Self: Unsize<U>
671         let unsize_predicate = ty::Binder::dummy(ty::TraitRef {
672             def_id: unsize_did,
673             substs: tcx.mk_substs_trait(tcx.types.self_param, &[unsized_self_ty.into()]),
674         })
675         .without_const()
676         .to_predicate(tcx);
677
678         // U: Trait<Arg1, ..., ArgN>
679         let trait_predicate = {
680             let substs =
681                 InternalSubsts::for_item(tcx, method.container.assert_trait(), |param, _| {
682                     if param.index == 0 {
683                         unsized_self_ty.into()
684                     } else {
685                         tcx.mk_param_from_def(param)
686                     }
687                 });
688
689             ty::Binder::dummy(ty::TraitRef { def_id: unsize_did, substs })
690                 .without_const()
691                 .to_predicate(tcx)
692         };
693
694         let caller_bounds: Vec<Predicate<'tcx>> =
695             param_env.caller_bounds().iter().chain([unsize_predicate, trait_predicate]).collect();
696
697         ty::ParamEnv::new(
698             tcx.intern_predicates(&caller_bounds),
699             param_env.reveal(),
700             param_env.constness(),
701         )
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 }