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