1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
8 pub mod specialization_graph;
11 use crate::infer::canonical::Canonical;
12 use crate::mir::interpret::ErrorHandled;
13 use crate::ty::subst::SubstsRef;
14 use crate::ty::{self, AdtKind, Ty, TyCtxt};
17 use rustc_hir::def_id::DefId;
18 use rustc_span::symbol::Symbol;
19 use rustc_span::{Span, DUMMY_SP};
20 use smallvec::SmallVec;
27 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
29 pub type ChalkCanonicalGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
31 pub use self::ImplSource::*;
32 pub use self::ObligationCauseCode::*;
33 pub use self::SelectionError::*;
35 pub use self::chalk::{
36 ChalkEnvironmentAndGoal, ChalkEnvironmentClause, RustInterner as ChalkRustInterner,
39 /// Depending on the stage of compilation, we want projection to be
40 /// more or less conservative.
41 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
43 /// At type-checking time, we refuse to project any associated
44 /// type that is marked `default`. Non-`default` ("final") types
45 /// are always projected. This is necessary in general for
46 /// soundness of specialization. However, we *could* allow
47 /// projections in fully-monomorphic cases. We choose not to,
48 /// because we prefer for `default type` to force the type
49 /// definition to be treated abstractly by any consumers of the
50 /// impl. Concretely, that means that the following example will
58 /// impl<T> Assoc for T {
59 /// default type Output = bool;
63 /// let <() as Assoc>::Output = true;
68 /// At codegen time, all monomorphic projections will succeed.
69 /// Also, `impl Trait` is normalized to the concrete type,
70 /// which has to be already collected by type-checking.
72 /// NOTE: as `impl Trait`'s concrete type should *never*
73 /// be observable directly by the user, `Reveal::All`
74 /// should not be used by checks which may expose
75 /// type equality or type contents to the user.
76 /// There are some exceptions, e.g., around OIBITS and
77 /// transmute-checking, which expose some details, but
78 /// not the whole concrete type of the `impl Trait`.
82 /// The reason why we incurred this obligation; used for error reporting.
84 /// As the happy path does not care about this struct, storing this on the heap
85 /// ends up increasing performance.
87 /// We do not want to intern this as there are a lot of obligation causes which
88 /// only live for a short period of time.
89 #[derive(Clone, PartialEq, Eq, Hash)]
90 pub struct ObligationCause<'tcx> {
91 /// `None` for `ObligationCause::dummy`, `Some` otherwise.
92 data: Option<Rc<ObligationCauseData<'tcx>>>,
95 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
96 ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
98 // Correctly format `ObligationCause::dummy`.
99 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 ObligationCauseData::fmt(self, f)
105 impl Deref for ObligationCause<'tcx> {
106 type Target = ObligationCauseData<'tcx>;
109 fn deref(&self) -> &Self::Target {
110 self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
114 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
115 pub struct ObligationCauseData<'tcx> {
118 /// The ID of the fn body that triggered this obligation. This is
119 /// used for region obligations to determine the precise
120 /// environment in which the region obligation should be evaluated
121 /// (in particular, closures can add new assumptions). See the
122 /// field `region_obligations` of the `FulfillmentContext` for more
124 pub body_id: hir::HirId,
126 pub code: ObligationCauseCode<'tcx>,
129 impl<'tcx> ObligationCause<'tcx> {
134 code: ObligationCauseCode<'tcx>,
135 ) -> ObligationCause<'tcx> {
136 ObligationCause { data: Some(Rc::new(ObligationCauseData { span, body_id, code })) }
139 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
140 ObligationCause::new(span, body_id, MiscObligation)
143 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
144 ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
148 pub fn dummy() -> ObligationCause<'tcx> {
149 ObligationCause { data: None }
152 pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
153 Rc::make_mut(self.data.get_or_insert_with(|| Rc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
156 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
158 ObligationCauseCode::CompareImplMethodObligation { .. }
159 | ObligationCauseCode::MainFunctionType
160 | ObligationCauseCode::StartFunctionType => {
161 tcx.sess.source_map().guess_head_span(self.span)
163 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
172 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
173 pub enum ObligationCauseCode<'tcx> {
174 /// Not well classified or should be obvious from the span.
177 /// A slice or array is WF only if `T: Sized`.
180 /// A tuple is WF only if its middle elements are `Sized`.
183 /// This is the trait reference from the given projection.
184 ProjectionWf(ty::ProjectionTy<'tcx>),
186 /// In an impl of trait `X` for type `Y`, type `Y` must
187 /// also implement all supertraits of `X`.
188 ItemObligation(DefId),
190 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
191 BindingObligation(DefId, Span),
193 /// A type like `&'a T` is WF only if `T: 'a`.
194 ReferenceOutlivesReferent(Ty<'tcx>),
196 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
197 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
199 /// Obligation incurred due to an object cast.
200 ObjectCastObligation(/* Object type */ Ty<'tcx>),
202 /// Obligation incurred due to a coercion.
208 /// Various cases where expressions must be `Sized` / `Copy` / etc.
209 /// `L = X` implies that `L` is `Sized`.
211 /// `(x1, .., xn)` must be `Sized`.
212 TupleInitializerSized,
213 /// `S { ... }` must be `Sized`.
214 StructInitializerSized,
215 /// Type of each variable must be `Sized`.
216 VariableType(hir::HirId),
217 /// Argument type must be `Sized`.
218 SizedArgumentType(Option<Span>),
219 /// Return type must be `Sized`.
221 /// Yield type must be `Sized`.
223 /// Inline asm operand type must be `Sized`.
225 /// `[T, ..n]` implies that `T` must be `Copy`.
226 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
229 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
236 /// Constant expressions must be sized.
239 /// `static` items must have `Sync` type.
242 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
244 ImplDerivedObligation(DerivedObligationCause<'tcx>),
246 DerivedObligation(DerivedObligationCause<'tcx>),
248 /// Error derived when matching traits/impls; see ObligationCause for more details
249 CompareImplConstObligation,
251 /// Error derived when matching traits/impls; see ObligationCause for more details
252 CompareImplMethodObligation {
254 impl_item_def_id: DefId,
255 trait_item_def_id: DefId,
258 /// Error derived when matching traits/impls; see ObligationCause for more details
259 CompareImplTypeObligation {
261 impl_item_def_id: DefId,
262 trait_item_def_id: DefId,
265 /// Checking that this expression can be assigned where it needs to be
266 // FIXME(eddyb) #11161 is the original Expr required?
269 /// Computing common supertype in the arms of a match expression
270 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
272 /// Type error arising from type checking a pattern against an expected type.
274 /// The span of the scrutinee or type expression which caused the `root_ty` type.
276 /// The root expected type induced by a scrutinee or type expression.
278 /// Whether the `Span` came from an expression or a type expression.
282 /// Constants in patterns must have `Structural` type.
283 ConstPatternStructural,
285 /// Computing common supertype in an if expression
286 IfExpression(Box<IfExpressionCause>),
288 /// Computing common supertype of an if expression with no else counter-part
289 IfExpressionWithNoElse,
291 /// `main` has wrong type
294 /// `start` has wrong type
297 /// Intrinsic has wrong type
303 /// `return` with no expression
306 /// `return` with an expression
307 ReturnValue(hir::HirId),
309 /// Return type of this function
312 /// Block implicit return
313 BlockTailExpression(hir::HirId),
315 /// #[feature(trivial_bounds)] is not enabled
319 impl ObligationCauseCode<'_> {
320 // Return the base obligation, ignoring derived obligations.
321 pub fn peel_derives(&self) -> &Self {
322 let mut base_cause = self;
323 while let BuiltinDerivedObligation(cause)
324 | ImplDerivedObligation(cause)
325 | DerivedObligation(cause) = base_cause
327 base_cause = &cause.parent_code;
333 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
334 #[cfg(target_arch = "x86_64")]
335 static_assert_size!(ObligationCauseCode<'_>, 32);
337 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
338 pub struct MatchExpressionArmCause<'tcx> {
340 pub source: hir::MatchSource,
341 pub prior_arms: Vec<Span>,
342 pub last_ty: Ty<'tcx>,
343 pub scrut_hir_id: hir::HirId,
346 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
347 pub struct IfExpressionCause {
349 pub outer: Option<Span>,
350 pub semicolon: Option<Span>,
353 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
354 pub struct DerivedObligationCause<'tcx> {
355 /// The trait reference of the parent obligation that led to the
356 /// current obligation. Note that only trait obligations lead to
357 /// derived obligations, so we just store the trait reference here
359 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
361 /// The parent trait had this cause.
362 pub parent_code: Rc<ObligationCauseCode<'tcx>>,
365 #[derive(Clone, Debug, TypeFoldable)]
366 pub enum SelectionError<'tcx> {
368 OutputTypeParameterMismatch(
369 ty::PolyTraitRef<'tcx>,
370 ty::PolyTraitRef<'tcx>,
371 ty::error::TypeError<'tcx>,
373 TraitNotObjectSafe(DefId),
374 ConstEvalFailure(ErrorHandled),
378 /// When performing resolution, it is typically the case that there
379 /// can be one of three outcomes:
381 /// - `Ok(Some(r))`: success occurred with result `r`
382 /// - `Ok(None)`: could not definitely determine anything, usually due
383 /// to inconclusive type inference.
384 /// - `Err(e)`: error `e` occurred
385 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
387 /// Given the successful resolution of an obligation, the `ImplSource`
388 /// indicates where the impl comes from.
390 /// For example, the obligation may be satisfied by a specific impl (case A),
391 /// or it may be relative to some bound that is in scope (case B).
394 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
395 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
396 /// impl Clone for i32 { ... } // Impl_3
398 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
399 /// // Case A: Vtable points at a specific impl. Only possible when
400 /// // type is concretely known. If the impl itself has bounded
401 /// // type parameters, Vtable will carry resolutions for those as well:
402 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
404 /// // Case A: ImplSource points at a specific impl. Only possible when
405 /// // type is concretely known. If the impl itself has bounded
406 /// // type parameters, ImplSource will carry resolutions for those as well:
407 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
409 /// // Case B: ImplSource must be provided by caller. This applies when
410 /// // type is a type parameter.
411 /// param.clone(); // ImplSourceParam
413 /// // Case C: A mix of cases A and B.
414 /// mixed.clone(); // ImplSource(Impl_1, [ImplSourceParam])
418 /// ### The type parameter `N`
420 /// See explanation on `ImplSourceUserDefinedData`.
421 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
422 pub enum ImplSource<'tcx, N> {
423 /// ImplSource identifying a particular impl.
424 ImplSourceUserDefined(ImplSourceUserDefinedData<'tcx, N>),
426 /// ImplSource for auto trait implementations.
427 /// This carries the information and nested obligations with regards
428 /// to an auto implementation for a trait `Trait`. The nested obligations
429 /// ensure the trait implementation holds for all the constituent types.
430 ImplSourceAutoImpl(ImplSourceAutoImplData<N>),
432 /// Successful resolution to an obligation provided by the caller
433 /// for some type parameter. The `Vec<N>` represents the
434 /// obligations incurred from normalizing the where-clause (if
436 ImplSourceParam(Vec<N>),
438 /// Virtual calls through an object.
439 ImplSourceObject(ImplSourceObjectData<'tcx, N>),
441 /// Successful resolution for a builtin trait.
442 ImplSourceBuiltin(ImplSourceBuiltinData<N>),
444 /// ImplSource automatically generated for a closure. The `DefId` is the ID
445 /// of the closure expression. This is a `ImplSourceUserDefined` in spirit, but the
446 /// impl is generated by the compiler and does not appear in the source.
447 ImplSourceClosure(ImplSourceClosureData<'tcx, N>),
449 /// Same as above, but for a function pointer type with the given signature.
450 ImplSourceFnPointer(ImplSourceFnPointerData<'tcx, N>),
452 /// ImplSource for a builtin `DeterminantKind` trait implementation.
453 ImplSourceDiscriminantKind(ImplSourceDiscriminantKindData),
455 /// ImplSource automatically generated for a generator.
456 ImplSourceGenerator(ImplSourceGeneratorData<'tcx, N>),
458 /// ImplSource for a trait alias.
459 ImplSourceTraitAlias(ImplSourceTraitAliasData<'tcx, N>),
462 impl<'tcx, N> ImplSource<'tcx, N> {
463 pub fn nested_obligations(self) -> Vec<N> {
465 ImplSourceUserDefined(i) => i.nested,
466 ImplSourceParam(n) => n,
467 ImplSourceBuiltin(i) => i.nested,
468 ImplSourceAutoImpl(d) => d.nested,
469 ImplSourceClosure(c) => c.nested,
470 ImplSourceGenerator(c) => c.nested,
471 ImplSourceObject(d) => d.nested,
472 ImplSourceFnPointer(d) => d.nested,
473 ImplSourceDiscriminantKind(ImplSourceDiscriminantKindData) => Vec::new(),
474 ImplSourceTraitAlias(d) => d.nested,
478 pub fn borrow_nested_obligations(&self) -> &[N] {
480 ImplSourceUserDefined(i) => &i.nested[..],
481 ImplSourceParam(n) => &n[..],
482 ImplSourceBuiltin(i) => &i.nested[..],
483 ImplSourceAutoImpl(d) => &d.nested[..],
484 ImplSourceClosure(c) => &c.nested[..],
485 ImplSourceGenerator(c) => &c.nested[..],
486 ImplSourceObject(d) => &d.nested[..],
487 ImplSourceFnPointer(d) => &d.nested[..],
488 ImplSourceDiscriminantKind(ImplSourceDiscriminantKindData) => &[],
489 ImplSourceTraitAlias(d) => &d.nested[..],
493 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
498 ImplSourceUserDefined(i) => ImplSourceUserDefined(ImplSourceUserDefinedData {
499 impl_def_id: i.impl_def_id,
501 nested: i.nested.into_iter().map(f).collect(),
503 ImplSourceParam(n) => ImplSourceParam(n.into_iter().map(f).collect()),
504 ImplSourceBuiltin(i) => ImplSourceBuiltin(ImplSourceBuiltinData {
505 nested: i.nested.into_iter().map(f).collect(),
507 ImplSourceObject(o) => ImplSourceObject(ImplSourceObjectData {
508 upcast_trait_ref: o.upcast_trait_ref,
509 vtable_base: o.vtable_base,
510 nested: o.nested.into_iter().map(f).collect(),
512 ImplSourceAutoImpl(d) => ImplSourceAutoImpl(ImplSourceAutoImplData {
513 trait_def_id: d.trait_def_id,
514 nested: d.nested.into_iter().map(f).collect(),
516 ImplSourceClosure(c) => ImplSourceClosure(ImplSourceClosureData {
517 closure_def_id: c.closure_def_id,
519 nested: c.nested.into_iter().map(f).collect(),
521 ImplSourceGenerator(c) => ImplSourceGenerator(ImplSourceGeneratorData {
522 generator_def_id: c.generator_def_id,
524 nested: c.nested.into_iter().map(f).collect(),
526 ImplSourceFnPointer(p) => ImplSourceFnPointer(ImplSourceFnPointerData {
528 nested: p.nested.into_iter().map(f).collect(),
530 ImplSourceDiscriminantKind(ImplSourceDiscriminantKindData) => {
531 ImplSourceDiscriminantKind(ImplSourceDiscriminantKindData)
533 ImplSourceTraitAlias(d) => ImplSourceTraitAlias(ImplSourceTraitAliasData {
534 alias_def_id: d.alias_def_id,
536 nested: d.nested.into_iter().map(f).collect(),
542 /// Identifies a particular impl in the source, along with a set of
543 /// substitutions from the impl's type/lifetime parameters. The
544 /// `nested` vector corresponds to the nested obligations attached to
545 /// the impl's type parameters.
547 /// The type parameter `N` indicates the type used for "nested
548 /// obligations" that are required by the impl. During type-check, this
549 /// is `Obligation`, as one might expect. During codegen, however, this
550 /// is `()`, because codegen only requires a shallow resolution of an
551 /// impl, and nested obligations are satisfied later.
552 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
553 pub struct ImplSourceUserDefinedData<'tcx, N> {
554 pub impl_def_id: DefId,
555 pub substs: SubstsRef<'tcx>,
559 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
560 pub struct ImplSourceGeneratorData<'tcx, N> {
561 pub generator_def_id: DefId,
562 pub substs: SubstsRef<'tcx>,
563 /// Nested obligations. This can be non-empty if the generator
564 /// signature contains associated types.
568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
569 pub struct ImplSourceClosureData<'tcx, N> {
570 pub closure_def_id: DefId,
571 pub substs: SubstsRef<'tcx>,
572 /// Nested obligations. This can be non-empty if the closure
573 /// signature contains associated types.
577 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
578 pub struct ImplSourceAutoImplData<N> {
579 pub trait_def_id: DefId,
583 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
584 pub struct ImplSourceBuiltinData<N> {
588 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
589 pub struct ImplSourceObjectData<'tcx, N> {
590 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
591 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
593 /// The vtable is formed by concatenating together the method lists of
594 /// the base object trait and all supertraits; this is the start of
595 /// `upcast_trait_ref`'s methods in that vtable.
596 pub vtable_base: usize,
601 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
602 pub struct ImplSourceFnPointerData<'tcx, N> {
607 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
608 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
609 pub struct ImplSourceDiscriminantKindData;
611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
612 pub struct ImplSourceTraitAliasData<'tcx, N> {
613 pub alias_def_id: DefId,
614 pub substs: SubstsRef<'tcx>,
618 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
619 pub enum ObjectSafetyViolation {
620 /// `Self: Sized` declared on the trait.
621 SizedSelf(SmallVec<[Span; 1]>),
623 /// Supertrait reference references `Self` an in illegal location
624 /// (e.g., `trait Foo : Bar<Self>`).
625 SupertraitSelf(SmallVec<[Span; 1]>),
627 /// Method has something illegal.
628 Method(Symbol, MethodViolationCode, Span),
630 /// Associated const.
631 AssocConst(Symbol, Span),
634 impl ObjectSafetyViolation {
635 pub fn error_msg(&self) -> Cow<'static, str> {
637 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
638 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
639 if spans.iter().any(|sp| *sp != DUMMY_SP) {
640 "it uses `Self` as a type parameter in this".into()
642 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
646 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
647 format!("associated function `{}` has no `self` parameter", name).into()
649 ObjectSafetyViolation::Method(
651 MethodViolationCode::ReferencesSelfInput(_),
653 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
654 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
655 format!("method `{}` references the `Self` type in this parameter", name).into()
657 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
658 format!("method `{}` references the `Self` type in its return type", name).into()
660 ObjectSafetyViolation::Method(
662 MethodViolationCode::WhereClauseReferencesSelf,
665 format!("method `{}` references the `Self` type in its `where` clause", name).into()
667 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
668 format!("method `{}` has generic type parameters", name).into()
670 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
671 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
673 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
674 format!("it contains associated `const` `{}`", name).into()
676 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
680 pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
682 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
685 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
687 "consider turning `{}` into a method by giving it a `&self` argument or \
688 constraining it so it does not apply to trait objects",
691 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
693 ObjectSafetyViolation::Method(
695 MethodViolationCode::UndispatchableReceiver,
698 format!("consider changing method `{}`'s `self` parameter to be `&self`", name),
699 Some(("&Self".to_string(), span)),
701 ObjectSafetyViolation::AssocConst(name, _)
702 | ObjectSafetyViolation::Method(name, ..) => {
703 (format!("consider moving `{}` to another trait", name), None)
708 pub fn spans(&self) -> SmallVec<[Span; 1]> {
709 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
710 // diagnostics use a `note` instead of a `span_label`.
712 ObjectSafetyViolation::SupertraitSelf(spans)
713 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
714 ObjectSafetyViolation::AssocConst(_, span)
715 | ObjectSafetyViolation::Method(_, _, span)
716 if *span != DUMMY_SP =>
725 /// Reasons a method might not be object-safe.
726 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
727 pub enum MethodViolationCode {
729 StaticMethod(Option<(&'static str, Span)>),
731 /// e.g., `fn foo(&self, x: Self)`
732 ReferencesSelfInput(usize),
734 /// e.g., `fn foo(&self) -> Self`
735 ReferencesSelfOutput,
737 /// e.g., `fn foo(&self) where Self: Clone`
738 WhereClauseReferencesSelf,
740 /// e.g., `fn foo<A>()`
743 /// the method's receiver (`self` argument) can't be dispatched on
744 UndispatchableReceiver,