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