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