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