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