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