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