1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
3 //! [rustc dev guide]: https://rust-lang.github.io/rustc-dev-guide/traits/resolution.html
7 pub mod specialization_graph;
10 use crate::mir::interpret::ErrorHandled;
11 use crate::ty::subst::SubstsRef;
12 use crate::ty::{self, AdtKind, List, Ty, TyCtxt};
16 use rustc_hir::def_id::DefId;
17 use rustc_span::{Span, DUMMY_SP};
18 use smallvec::SmallVec;
24 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
26 pub use self::ObligationCauseCode::*;
27 pub use self::SelectionError::*;
28 pub use self::Vtable::*;
30 /// Depending on the stage of compilation, we want projection to be
31 /// more or less conservative.
32 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
34 /// At type-checking time, we refuse to project any associated
35 /// type that is marked `default`. Non-`default` ("final") types
36 /// are always projected. This is necessary in general for
37 /// soundness of specialization. However, we *could* allow
38 /// projections in fully-monomorphic cases. We choose not to,
39 /// because we prefer for `default type` to force the type
40 /// definition to be treated abstractly by any consumers of the
41 /// impl. Concretely, that means that the following example will
49 /// impl<T> Assoc for T {
50 /// default type Output = bool;
54 /// let <() as Assoc>::Output = true;
59 /// At codegen time, all monomorphic projections will succeed.
60 /// Also, `impl Trait` is normalized to the concrete type,
61 /// which has to be already collected by type-checking.
63 /// NOTE: as `impl Trait`'s concrete type should *never*
64 /// be observable directly by the user, `Reveal::All`
65 /// should not be used by checks which may expose
66 /// type equality or type contents to the user.
67 /// There are some exceptions, e.g., around OIBITS and
68 /// transmute-checking, which expose some details, but
69 /// not the whole concrete type of the `impl Trait`.
73 /// The reason why we incurred this obligation; used for error reporting.
74 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
75 pub struct ObligationCause<'tcx> {
78 /// The ID of the fn body that triggered this obligation. This is
79 /// used for region obligations to determine the precise
80 /// environment in which the region obligation should be evaluated
81 /// (in particular, closures can add new assumptions). See the
82 /// field `region_obligations` of the `FulfillmentContext` for more
84 pub body_id: hir::HirId,
86 pub code: ObligationCauseCode<'tcx>,
89 impl<'tcx> ObligationCause<'tcx> {
94 code: ObligationCauseCode<'tcx>,
95 ) -> ObligationCause<'tcx> {
96 ObligationCause { span, body_id, code }
99 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
100 ObligationCause { span, body_id, code: MiscObligation }
103 pub fn dummy() -> ObligationCause<'tcx> {
104 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
107 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
109 ObligationCauseCode::CompareImplMethodObligation { .. }
110 | ObligationCauseCode::MainFunctionType
111 | ObligationCauseCode::StartFunctionType => tcx.sess.source_map().def_span(self.span),
112 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
121 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
122 pub enum ObligationCauseCode<'tcx> {
123 /// Not well classified or should be obvious from the span.
126 /// A slice or array is WF only if `T: Sized`.
129 /// A tuple is WF only if its middle elements are `Sized`.
132 /// This is the trait reference from the given projection.
133 ProjectionWf(ty::ProjectionTy<'tcx>),
135 /// In an impl of trait `X` for type `Y`, type `Y` must
136 /// also implement all supertraits of `X`.
137 ItemObligation(DefId),
139 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
140 BindingObligation(DefId, Span),
142 /// A type like `&'a T` is WF only if `T: 'a`.
143 ReferenceOutlivesReferent(Ty<'tcx>),
145 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
146 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
148 /// Obligation incurred due to an object cast.
149 ObjectCastObligation(/* Object type */ Ty<'tcx>),
151 /// Obligation incurred due to a coercion.
157 /// Various cases where expressions must be `Sized` / `Copy` / etc.
158 /// `L = X` implies that `L` is `Sized`.
160 /// `(x1, .., xn)` must be `Sized`.
161 TupleInitializerSized,
162 /// `S { ... }` must be `Sized`.
163 StructInitializerSized,
164 /// Type of each variable must be `Sized`.
165 VariableType(hir::HirId),
166 /// Argument type must be `Sized`.
168 /// Return type must be `Sized`.
170 /// Yield type must be `Sized`.
172 /// `[T, ..n]` implies that `T` must be `Copy`.
173 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
176 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
182 /// Constant expressions must be sized.
185 /// `static` items must have `Sync` type.
188 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
190 ImplDerivedObligation(DerivedObligationCause<'tcx>),
192 /// Error derived when matching traits/impls; see ObligationCause for more details
193 CompareImplMethodObligation {
194 item_name: ast::Name,
195 impl_item_def_id: DefId,
196 trait_item_def_id: DefId,
199 /// Error derived when matching traits/impls; see ObligationCause for more details
200 CompareImplTypeObligation {
201 item_name: ast::Name,
202 impl_item_def_id: DefId,
203 trait_item_def_id: DefId,
206 /// Checking that this expression can be assigned where it needs to be
207 // FIXME(eddyb) #11161 is the original Expr required?
210 /// Computing common supertype in the arms of a match expression
211 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
213 /// Type error arising from type checking a pattern against an expected type.
215 /// The span of the scrutinee or type expression which caused the `root_ty` type.
217 /// The root expected type induced by a scrutinee or type expression.
219 /// Whether the `Span` came from an expression or a type expression.
223 /// Constants in patterns must have `Structural` type.
224 ConstPatternStructural,
226 /// Computing common supertype in an if expression
227 IfExpression(Box<IfExpressionCause>),
229 /// Computing common supertype of an if expression with no else counter-part
230 IfExpressionWithNoElse,
232 /// `main` has wrong type
235 /// `start` has wrong type
238 /// Intrinsic has wrong type
244 /// `return` with no expression
247 /// `return` with an expression
248 ReturnValue(hir::HirId),
250 /// Return type of this function
253 /// Block implicit return
254 BlockTailExpression(hir::HirId),
256 /// #[feature(trivial_bounds)] is not enabled
259 AssocTypeBound(Box<AssocTypeBoundData>),
262 impl ObligationCauseCode<'_> {
263 // Return the base obligation, ignoring derived obligations.
264 pub fn peel_derives(&self) -> &Self {
265 let mut base_cause = self;
266 while let BuiltinDerivedObligation(cause) | ImplDerivedObligation(cause) = base_cause {
267 base_cause = &cause.parent_code;
273 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
274 pub struct AssocTypeBoundData {
275 pub impl_span: Option<Span>,
277 pub bounds: Vec<Span>,
280 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
281 #[cfg(target_arch = "x86_64")]
282 static_assert_size!(ObligationCauseCode<'_>, 32);
284 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
285 pub struct MatchExpressionArmCause<'tcx> {
287 pub source: hir::MatchSource,
288 pub prior_arms: Vec<Span>,
289 pub last_ty: Ty<'tcx>,
290 pub scrut_hir_id: hir::HirId,
293 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
294 pub struct IfExpressionCause {
296 pub outer: Option<Span>,
297 pub semicolon: Option<Span>,
300 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
301 pub struct DerivedObligationCause<'tcx> {
302 /// The trait reference of the parent obligation that led to the
303 /// current obligation. Note that only trait obligations lead to
304 /// derived obligations, so we just store the trait reference here
306 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
308 /// The parent trait had this cause.
309 pub parent_code: Rc<ObligationCauseCode<'tcx>>,
312 /// The following types:
320 /// * `InEnvironment`,
321 /// are used for representing the trait system in the form of
322 /// logic programming clauses. They are part of the interface
323 /// for the chalk SLG solver.
324 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
325 pub enum WhereClause<'tcx> {
326 Implemented(ty::TraitPredicate<'tcx>),
327 ProjectionEq(ty::ProjectionPredicate<'tcx>),
328 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
329 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
332 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
333 pub enum WellFormed<'tcx> {
334 Trait(ty::TraitPredicate<'tcx>),
338 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
339 pub enum FromEnv<'tcx> {
340 Trait(ty::TraitPredicate<'tcx>),
344 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
345 pub enum DomainGoal<'tcx> {
346 Holds(WhereClause<'tcx>),
347 WellFormed(WellFormed<'tcx>),
348 FromEnv(FromEnv<'tcx>),
349 Normalize(ty::ProjectionPredicate<'tcx>),
352 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
354 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
355 pub enum QuantifierKind {
360 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
361 pub enum GoalKind<'tcx> {
362 Implies(Clauses<'tcx>, Goal<'tcx>),
363 And(Goal<'tcx>, Goal<'tcx>),
365 DomainGoal(DomainGoal<'tcx>),
366 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
367 Subtype(Ty<'tcx>, Ty<'tcx>),
371 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
373 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
375 impl<'tcx> DomainGoal<'tcx> {
376 pub fn into_goal(self) -> GoalKind<'tcx> {
377 GoalKind::DomainGoal(self)
380 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
383 hypotheses: ty::List::empty(),
384 category: ProgramClauseCategory::Other,
389 impl<'tcx> GoalKind<'tcx> {
390 pub fn from_poly_domain_goal(
391 domain_goal: PolyDomainGoal<'tcx>,
393 ) -> GoalKind<'tcx> {
394 match domain_goal.no_bound_vars() {
395 Some(p) => p.into_goal(),
396 None => GoalKind::Quantified(
397 QuantifierKind::Universal,
398 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())),
404 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
405 /// Harrop Formulas".
406 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
407 pub enum Clause<'tcx> {
408 Implies(ProgramClause<'tcx>),
409 ForAll(ty::Binder<ProgramClause<'tcx>>),
413 pub fn category(self) -> ProgramClauseCategory {
415 Clause::Implies(clause) => clause.category,
416 Clause::ForAll(clause) => clause.skip_binder().category,
421 /// Multiple clauses.
422 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
424 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
425 /// that the domain goal `D` is true if `G1...Gn` are provable. This
426 /// is equivalent to the implication `G1..Gn => D`; we usually write
427 /// it with the reverse implication operator `:-` to emphasize the way
428 /// that programs are actually solved (via backchaining, which starts
429 /// with the goal to solve and proceeds from there).
430 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
431 pub struct ProgramClause<'tcx> {
432 /// This goal will be considered true ...
433 pub goal: DomainGoal<'tcx>,
435 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
436 pub hypotheses: Goals<'tcx>,
438 /// Useful for filtering clauses.
439 pub category: ProgramClauseCategory,
442 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
443 pub enum ProgramClauseCategory {
449 /// A set of clauses that we assume to be true.
450 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
451 pub struct Environment<'tcx> {
452 pub clauses: Clauses<'tcx>,
455 impl Environment<'tcx> {
456 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
457 InEnvironment { environment: self, goal }
461 /// Something (usually a goal), along with an environment.
462 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
463 pub struct InEnvironment<'tcx, G> {
464 pub environment: Environment<'tcx>,
468 #[derive(Clone, Debug, TypeFoldable)]
469 pub enum SelectionError<'tcx> {
471 OutputTypeParameterMismatch(
472 ty::PolyTraitRef<'tcx>,
473 ty::PolyTraitRef<'tcx>,
474 ty::error::TypeError<'tcx>,
476 TraitNotObjectSafe(DefId),
477 ConstEvalFailure(ErrorHandled),
481 /// When performing resolution, it is typically the case that there
482 /// can be one of three outcomes:
484 /// - `Ok(Some(r))`: success occurred with result `r`
485 /// - `Ok(None)`: could not definitely determine anything, usually due
486 /// to inconclusive type inference.
487 /// - `Err(e)`: error `e` occurred
488 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
490 /// Given the successful resolution of an obligation, the `Vtable`
491 /// indicates where the vtable comes from. Note that while we call this
492 /// a "vtable", it does not necessarily indicate dynamic dispatch at
493 /// runtime. `Vtable` instances just tell the compiler where to find
494 /// methods, but in generic code those methods are typically statically
495 /// dispatched -- only when an object is constructed is a `Vtable`
496 /// instance reified into an actual vtable.
498 /// For example, the vtable may be tied to a specific impl (case A),
499 /// or it may be relative to some bound that is in scope (case B).
502 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
503 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
504 /// impl Clone for int { ... } // Impl_3
506 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
508 /// mixed: Option<T>) {
510 /// // Case A: Vtable points at a specific impl. Only possible when
511 /// // type is concretely known. If the impl itself has bounded
512 /// // type parameters, Vtable will carry resolutions for those as well:
513 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
515 /// // Case B: Vtable must be provided by caller. This applies when
516 /// // type is a type parameter.
517 /// param.clone(); // VtableParam
519 /// // Case C: A mix of cases A and B.
520 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
524 /// ### The type parameter `N`
526 /// See explanation on `VtableImplData`.
527 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
528 pub enum Vtable<'tcx, N> {
529 /// Vtable identifying a particular impl.
530 VtableImpl(VtableImplData<'tcx, N>),
532 /// Vtable for auto trait implementations.
533 /// This carries the information and nested obligations with regards
534 /// to an auto implementation for a trait `Trait`. The nested obligations
535 /// ensure the trait implementation holds for all the constituent types.
536 VtableAutoImpl(VtableAutoImplData<N>),
538 /// Successful resolution to an obligation provided by the caller
539 /// for some type parameter. The `Vec<N>` represents the
540 /// obligations incurred from normalizing the where-clause (if
544 /// Virtual calls through an object.
545 VtableObject(VtableObjectData<'tcx, N>),
547 /// Successful resolution for a builtin trait.
548 VtableBuiltin(VtableBuiltinData<N>),
550 /// Vtable automatically generated for a closure. The `DefId` is the ID
551 /// of the closure expression. This is a `VtableImpl` in spirit, but the
552 /// impl is generated by the compiler and does not appear in the source.
553 VtableClosure(VtableClosureData<'tcx, N>),
555 /// Same as above, but for a function pointer type with the given signature.
556 VtableFnPointer(VtableFnPointerData<'tcx, N>),
558 /// Vtable automatically generated for a generator.
559 VtableGenerator(VtableGeneratorData<'tcx, N>),
561 /// Vtable for a trait alias.
562 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
565 impl<'tcx, N> Vtable<'tcx, N> {
566 pub fn nested_obligations(self) -> Vec<N> {
568 VtableImpl(i) => i.nested,
570 VtableBuiltin(i) => i.nested,
571 VtableAutoImpl(d) => d.nested,
572 VtableClosure(c) => c.nested,
573 VtableGenerator(c) => c.nested,
574 VtableObject(d) => d.nested,
575 VtableFnPointer(d) => d.nested,
576 VtableTraitAlias(d) => d.nested,
580 pub fn borrow_nested_obligations(&self) -> &[N] {
582 VtableImpl(i) => &i.nested[..],
583 VtableParam(n) => &n[..],
584 VtableBuiltin(i) => &i.nested[..],
585 VtableAutoImpl(d) => &d.nested[..],
586 VtableClosure(c) => &c.nested[..],
587 VtableGenerator(c) => &c.nested[..],
588 VtableObject(d) => &d.nested[..],
589 VtableFnPointer(d) => &d.nested[..],
590 VtableTraitAlias(d) => &d.nested[..],
594 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
599 VtableImpl(i) => VtableImpl(VtableImplData {
600 impl_def_id: i.impl_def_id,
602 nested: i.nested.into_iter().map(f).collect(),
604 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
605 VtableBuiltin(i) => {
606 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
608 VtableObject(o) => VtableObject(VtableObjectData {
609 upcast_trait_ref: o.upcast_trait_ref,
610 vtable_base: o.vtable_base,
611 nested: o.nested.into_iter().map(f).collect(),
613 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
614 trait_def_id: d.trait_def_id,
615 nested: d.nested.into_iter().map(f).collect(),
617 VtableClosure(c) => VtableClosure(VtableClosureData {
618 closure_def_id: c.closure_def_id,
620 nested: c.nested.into_iter().map(f).collect(),
622 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
623 generator_def_id: c.generator_def_id,
625 nested: c.nested.into_iter().map(f).collect(),
627 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
629 nested: p.nested.into_iter().map(f).collect(),
631 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
632 alias_def_id: d.alias_def_id,
634 nested: d.nested.into_iter().map(f).collect(),
640 /// Identifies a particular impl in the source, along with a set of
641 /// substitutions from the impl's type/lifetime parameters. The
642 /// `nested` vector corresponds to the nested obligations attached to
643 /// the impl's type parameters.
645 /// The type parameter `N` indicates the type used for "nested
646 /// obligations" that are required by the impl. During type-check, this
647 /// is `Obligation`, as one might expect. During codegen, however, this
648 /// is `()`, because codegen only requires a shallow resolution of an
649 /// impl, and nested obligations are satisfied later.
650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
651 pub struct VtableImplData<'tcx, N> {
652 pub impl_def_id: DefId,
653 pub substs: SubstsRef<'tcx>,
657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
658 pub struct VtableGeneratorData<'tcx, N> {
659 pub generator_def_id: DefId,
660 pub substs: SubstsRef<'tcx>,
661 /// Nested obligations. This can be non-empty if the generator
662 /// signature contains associated types.
666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
667 pub struct VtableClosureData<'tcx, N> {
668 pub closure_def_id: DefId,
669 pub substs: SubstsRef<'tcx>,
670 /// Nested obligations. This can be non-empty if the closure
671 /// signature contains associated types.
675 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
676 pub struct VtableAutoImplData<N> {
677 pub trait_def_id: DefId,
681 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
682 pub struct VtableBuiltinData<N> {
686 /// A vtable for some object-safe trait `Foo` automatically derived
687 /// for the object type `Foo`.
688 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
689 pub struct VtableObjectData<'tcx, N> {
690 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
691 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
693 /// The vtable is formed by concatenating together the method lists of
694 /// the base object trait and all supertraits; this is the start of
695 /// `upcast_trait_ref`'s methods in that vtable.
696 pub vtable_base: usize,
701 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
702 pub struct VtableFnPointerData<'tcx, N> {
707 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
708 pub struct VtableTraitAliasData<'tcx, N> {
709 pub alias_def_id: DefId,
710 pub substs: SubstsRef<'tcx>,
714 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
715 pub enum ObjectSafetyViolation {
716 /// `Self: Sized` declared on the trait.
717 SizedSelf(SmallVec<[Span; 1]>),
719 /// Supertrait reference references `Self` an in illegal location
720 /// (e.g., `trait Foo : Bar<Self>`).
721 SupertraitSelf(SmallVec<[Span; 1]>),
723 /// Method has something illegal.
724 Method(ast::Name, MethodViolationCode, Span),
726 /// Associated const.
727 AssocConst(ast::Name, Span),
730 impl ObjectSafetyViolation {
731 pub fn error_msg(&self) -> Cow<'static, str> {
733 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
734 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
735 if spans.iter().any(|sp| *sp != DUMMY_SP) {
736 "it uses `Self` as a type parameter in this".into()
738 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
742 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
743 format!("associated function `{}` has no `self` parameter", name).into()
745 ObjectSafetyViolation::Method(
747 MethodViolationCode::ReferencesSelfInput(_),
749 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
750 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
751 format!("method `{}` references the `Self` type in this parameter", name).into()
753 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
754 format!("method `{}` references the `Self` type in its return type", name).into()
756 ObjectSafetyViolation::Method(
758 MethodViolationCode::WhereClauseReferencesSelf,
761 format!("method `{}` references the `Self` type in its `where` clause", name).into()
763 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
764 format!("method `{}` has generic type parameters", name).into()
766 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
767 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
769 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
770 format!("it contains associated `const` `{}`", name).into()
772 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
776 pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
778 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
781 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
783 "consider turning `{}` into a method by giving it a `&self` argument or \
784 constraining it so it does not apply to trait objects",
787 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
789 ObjectSafetyViolation::Method(
791 MethodViolationCode::UndispatchableReceiver,
794 format!("consider changing method `{}`'s `self` parameter to be `&self`", name),
795 Some(("&Self".to_string(), span)),
797 ObjectSafetyViolation::AssocConst(name, _)
798 | ObjectSafetyViolation::Method(name, ..) => {
799 (format!("consider moving `{}` to another trait", name), None)
804 pub fn spans(&self) -> SmallVec<[Span; 1]> {
805 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
806 // diagnostics use a `note` instead of a `span_label`.
808 ObjectSafetyViolation::SupertraitSelf(spans)
809 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
810 ObjectSafetyViolation::AssocConst(_, span)
811 | ObjectSafetyViolation::Method(_, _, span)
812 if *span != DUMMY_SP =>
821 /// Reasons a method might not be object-safe.
822 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
823 pub enum MethodViolationCode {
825 StaticMethod(Option<(&'static str, Span)>),
827 /// e.g., `fn foo(&self, x: Self)`
828 ReferencesSelfInput(usize),
830 /// e.g., `fn foo(&self) -> Self`
831 ReferencesSelfOutput,
833 /// e.g., `fn foo(&self) where Self: Clone`
834 WhereClauseReferencesSelf,
836 /// e.g., `fn foo<A>()`
839 /// the method's receiver (`self` argument) can't be dispatched on
840 UndispatchableReceiver,