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