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