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