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