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