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::ObligationCauseCode::*;
32 pub use self::SelectionError::*;
33 pub use self::Vtable::*;
35 pub use self::chalk::{
36 ChalkEnvironmentAndGoal, ChalkEnvironmentClause, RustDefId as ChalkRustDefId,
37 RustInterner as ChalkRustInterner,
40 /// Depending on the stage of compilation, we want projection to be
41 /// more or less conservative.
42 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
44 /// At type-checking time, we refuse to project any associated
45 /// type that is marked `default`. Non-`default` ("final") types
46 /// are always projected. This is necessary in general for
47 /// soundness of specialization. However, we *could* allow
48 /// projections in fully-monomorphic cases. We choose not to,
49 /// because we prefer for `default type` to force the type
50 /// definition to be treated abstractly by any consumers of the
51 /// impl. Concretely, that means that the following example will
59 /// impl<T> Assoc for T {
60 /// default type Output = bool;
64 /// let <() as Assoc>::Output = true;
69 /// At codegen time, all monomorphic projections will succeed.
70 /// Also, `impl Trait` is normalized to the concrete type,
71 /// which has to be already collected by type-checking.
73 /// NOTE: as `impl Trait`'s concrete type should *never*
74 /// be observable directly by the user, `Reveal::All`
75 /// should not be used by checks which may expose
76 /// type equality or type contents to the user.
77 /// There are some exceptions, e.g., around OIBITS and
78 /// transmute-checking, which expose some details, but
79 /// not the whole concrete type of the `impl Trait`.
83 /// The reason why we incurred this obligation; used for error reporting.
85 /// As the happy path does not care about this struct, storing this on the heap
86 /// ends up increasing performance.
88 /// We do not want to intern this as there are a lot of obligation causes which
89 /// only live for a short period of time.
90 #[derive(Clone, PartialEq, Eq, Hash)]
91 pub struct ObligationCause<'tcx> {
92 /// `None` for `ObligationCause::dummy`, `Some` otherwise.
93 data: Option<Rc<ObligationCauseData<'tcx>>>,
96 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
97 ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
99 // Correctly format `ObligationCause::dummy`.
100 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 ObligationCauseData::fmt(self, f)
106 impl Deref for ObligationCause<'tcx> {
107 type Target = ObligationCauseData<'tcx>;
110 fn deref(&self) -> &Self::Target {
111 self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
115 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
116 pub struct ObligationCauseData<'tcx> {
119 /// The ID of the fn body that triggered this obligation. This is
120 /// used for region obligations to determine the precise
121 /// environment in which the region obligation should be evaluated
122 /// (in particular, closures can add new assumptions). See the
123 /// field `region_obligations` of the `FulfillmentContext` for more
125 pub body_id: hir::HirId,
127 pub code: ObligationCauseCode<'tcx>,
130 impl<'tcx> ObligationCause<'tcx> {
135 code: ObligationCauseCode<'tcx>,
136 ) -> ObligationCause<'tcx> {
137 ObligationCause { data: Some(Rc::new(ObligationCauseData { span, body_id, code })) }
140 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
141 ObligationCause::new(span, body_id, MiscObligation)
144 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
145 ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
149 pub fn dummy() -> ObligationCause<'tcx> {
150 ObligationCause { data: None }
153 pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
154 Rc::make_mut(self.data.get_or_insert_with(|| Rc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
157 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
159 ObligationCauseCode::CompareImplMethodObligation { .. }
160 | ObligationCauseCode::MainFunctionType
161 | ObligationCauseCode::StartFunctionType => {
162 tcx.sess.source_map().guess_head_span(self.span)
164 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
173 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
174 pub enum ObligationCauseCode<'tcx> {
175 /// Not well classified or should be obvious from the span.
178 /// A slice or array is WF only if `T: Sized`.
181 /// A tuple is WF only if its middle elements are `Sized`.
184 /// This is the trait reference from the given projection.
185 ProjectionWf(ty::ProjectionTy<'tcx>),
187 /// In an impl of trait `X` for type `Y`, type `Y` must
188 /// also implement all supertraits of `X`.
189 ItemObligation(DefId),
191 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
192 BindingObligation(DefId, Span),
194 /// A type like `&'a T` is WF only if `T: 'a`.
195 ReferenceOutlivesReferent(Ty<'tcx>),
197 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
198 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
200 /// Obligation incurred due to an object cast.
201 ObjectCastObligation(/* Object type */ Ty<'tcx>),
203 /// Obligation incurred due to a coercion.
209 /// Various cases where expressions must be `Sized` / `Copy` / etc.
210 /// `L = X` implies that `L` is `Sized`.
212 /// `(x1, .., xn)` must be `Sized`.
213 TupleInitializerSized,
214 /// `S { ... }` must be `Sized`.
215 StructInitializerSized,
216 /// Type of each variable must be `Sized`.
217 VariableType(hir::HirId),
218 /// Argument type must be `Sized`.
220 /// Return type must be `Sized`.
222 /// Yield type must be `Sized`.
224 /// Inline asm operand type must be `Sized`.
226 /// `[T, ..n]` implies that `T` must be `Copy`.
227 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
230 /// 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 `Vtable`
388 /// indicates where the vtable comes from. Note that while we call this
389 /// a "vtable", it does not necessarily indicate dynamic dispatch at
390 /// runtime. `Vtable` instances just tell the compiler where to find
391 /// methods, but in generic code those methods are typically statically
392 /// dispatched -- only when an object is constructed is a `Vtable`
393 /// instance reified into an actual vtable.
395 /// For example, the vtable may be tied to a specific impl (case A),
396 /// or it may be relative to some bound that is in scope (case B).
399 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
400 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
401 /// impl Clone for int { ... } // Impl_3
403 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
405 /// mixed: Option<T>) {
407 /// // Case A: Vtable points at a specific impl. Only possible when
408 /// // type is concretely known. If the impl itself has bounded
409 /// // type parameters, Vtable will carry resolutions for those as well:
410 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
412 /// // Case B: Vtable must be provided by caller. This applies when
413 /// // type is a type parameter.
414 /// param.clone(); // VtableParam
416 /// // Case C: A mix of cases A and B.
417 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
421 /// ### The type parameter `N`
423 /// See explanation on `VtableImplData`.
424 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
425 pub enum Vtable<'tcx, N> {
426 /// Vtable identifying a particular impl.
427 VtableImpl(VtableImplData<'tcx, N>),
429 /// Vtable for auto trait implementations.
430 /// This carries the information and nested obligations with regards
431 /// to an auto implementation for a trait `Trait`. The nested obligations
432 /// ensure the trait implementation holds for all the constituent types.
433 VtableAutoImpl(VtableAutoImplData<N>),
435 /// Successful resolution to an obligation provided by the caller
436 /// for some type parameter. The `Vec<N>` represents the
437 /// obligations incurred from normalizing the where-clause (if
441 /// Virtual calls through an object.
442 VtableObject(VtableObjectData<'tcx, N>),
444 /// Successful resolution for a builtin trait.
445 VtableBuiltin(VtableBuiltinData<N>),
447 /// Vtable automatically generated for a closure. The `DefId` is the ID
448 /// of the closure expression. This is a `VtableImpl` in spirit, but the
449 /// impl is generated by the compiler and does not appear in the source.
450 VtableClosure(VtableClosureData<'tcx, N>),
452 /// Same as above, but for a function pointer type with the given signature.
453 VtableFnPointer(VtableFnPointerData<'tcx, N>),
455 /// Vtable for a builtin `DeterminantKind` trait implementation.
456 VtableDiscriminantKind(VtableDiscriminantKindData),
458 /// Vtable automatically generated for a generator.
459 VtableGenerator(VtableGeneratorData<'tcx, N>),
461 /// Vtable for a trait alias.
462 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
465 impl<'tcx, N> Vtable<'tcx, N> {
466 pub fn nested_obligations(self) -> Vec<N> {
468 VtableImpl(i) => i.nested,
470 VtableBuiltin(i) => i.nested,
471 VtableAutoImpl(d) => d.nested,
472 VtableClosure(c) => c.nested,
473 VtableGenerator(c) => c.nested,
474 VtableObject(d) => d.nested,
475 VtableFnPointer(d) => d.nested,
476 VtableDiscriminantKind(VtableDiscriminantKindData) => Vec::new(),
477 VtableTraitAlias(d) => d.nested,
481 pub fn borrow_nested_obligations(&self) -> &[N] {
483 VtableImpl(i) => &i.nested[..],
484 VtableParam(n) => &n[..],
485 VtableBuiltin(i) => &i.nested[..],
486 VtableAutoImpl(d) => &d.nested[..],
487 VtableClosure(c) => &c.nested[..],
488 VtableGenerator(c) => &c.nested[..],
489 VtableObject(d) => &d.nested[..],
490 VtableFnPointer(d) => &d.nested[..],
491 VtableDiscriminantKind(VtableDiscriminantKindData) => &[],
492 VtableTraitAlias(d) => &d.nested[..],
496 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
501 VtableImpl(i) => VtableImpl(VtableImplData {
502 impl_def_id: i.impl_def_id,
504 nested: i.nested.into_iter().map(f).collect(),
506 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
507 VtableBuiltin(i) => {
508 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
510 VtableObject(o) => VtableObject(VtableObjectData {
511 upcast_trait_ref: o.upcast_trait_ref,
512 vtable_base: o.vtable_base,
513 nested: o.nested.into_iter().map(f).collect(),
515 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
516 trait_def_id: d.trait_def_id,
517 nested: d.nested.into_iter().map(f).collect(),
519 VtableClosure(c) => VtableClosure(VtableClosureData {
520 closure_def_id: c.closure_def_id,
522 nested: c.nested.into_iter().map(f).collect(),
524 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
525 generator_def_id: c.generator_def_id,
527 nested: c.nested.into_iter().map(f).collect(),
529 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
531 nested: p.nested.into_iter().map(f).collect(),
533 VtableDiscriminantKind(VtableDiscriminantKindData) => {
534 VtableDiscriminantKind(VtableDiscriminantKindData)
536 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
537 alias_def_id: d.alias_def_id,
539 nested: d.nested.into_iter().map(f).collect(),
545 /// Identifies a particular impl in the source, along with a set of
546 /// substitutions from the impl's type/lifetime parameters. The
547 /// `nested` vector corresponds to the nested obligations attached to
548 /// the impl's type parameters.
550 /// The type parameter `N` indicates the type used for "nested
551 /// obligations" that are required by the impl. During type-check, this
552 /// is `Obligation`, as one might expect. During codegen, however, this
553 /// is `()`, because codegen only requires a shallow resolution of an
554 /// impl, and nested obligations are satisfied later.
555 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
556 pub struct VtableImplData<'tcx, N> {
557 pub impl_def_id: DefId,
558 pub substs: SubstsRef<'tcx>,
562 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
563 pub struct VtableGeneratorData<'tcx, N> {
564 pub generator_def_id: DefId,
565 pub substs: SubstsRef<'tcx>,
566 /// Nested obligations. This can be non-empty if the generator
567 /// signature contains associated types.
571 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
572 pub struct VtableClosureData<'tcx, N> {
573 pub closure_def_id: DefId,
574 pub substs: SubstsRef<'tcx>,
575 /// Nested obligations. This can be non-empty if the closure
576 /// signature contains associated types.
580 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
581 pub struct VtableAutoImplData<N> {
582 pub trait_def_id: DefId,
586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
587 pub struct VtableBuiltinData<N> {
591 /// A vtable for some object-safe trait `Foo` automatically derived
592 /// for the object type `Foo`.
593 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
594 pub struct VtableObjectData<'tcx, N> {
595 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
596 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
598 /// The vtable is formed by concatenating together the method lists of
599 /// the base object trait and all supertraits; this is the start of
600 /// `upcast_trait_ref`'s methods in that vtable.
601 pub vtable_base: usize,
606 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
607 pub struct VtableFnPointerData<'tcx, N> {
612 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
613 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
614 pub struct VtableDiscriminantKindData;
616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
617 pub struct VtableTraitAliasData<'tcx, N> {
618 pub alias_def_id: DefId,
619 pub substs: SubstsRef<'tcx>,
623 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
624 pub enum ObjectSafetyViolation {
625 /// `Self: Sized` declared on the trait.
626 SizedSelf(SmallVec<[Span; 1]>),
628 /// Supertrait reference references `Self` an in illegal location
629 /// (e.g., `trait Foo : Bar<Self>`).
630 SupertraitSelf(SmallVec<[Span; 1]>),
632 /// Method has something illegal.
633 Method(Symbol, MethodViolationCode, Span),
635 /// Associated const.
636 AssocConst(Symbol, Span),
639 impl ObjectSafetyViolation {
640 pub fn error_msg(&self) -> Cow<'static, str> {
642 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
643 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
644 if spans.iter().any(|sp| *sp != DUMMY_SP) {
645 "it uses `Self` as a type parameter in this".into()
647 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
651 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
652 format!("associated function `{}` has no `self` parameter", name).into()
654 ObjectSafetyViolation::Method(
656 MethodViolationCode::ReferencesSelfInput(_),
658 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
659 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
660 format!("method `{}` references the `Self` type in this parameter", name).into()
662 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
663 format!("method `{}` references the `Self` type in its return type", name).into()
665 ObjectSafetyViolation::Method(
667 MethodViolationCode::WhereClauseReferencesSelf,
670 format!("method `{}` references the `Self` type in its `where` clause", name).into()
672 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
673 format!("method `{}` has generic type parameters", name).into()
675 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
676 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
678 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
679 format!("it contains associated `const` `{}`", name).into()
681 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
685 pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
687 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
690 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
692 "consider turning `{}` into a method by giving it a `&self` argument or \
693 constraining it so it does not apply to trait objects",
696 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
698 ObjectSafetyViolation::Method(
700 MethodViolationCode::UndispatchableReceiver,
703 format!("consider changing method `{}`'s `self` parameter to be `&self`", name),
704 Some(("&Self".to_string(), span)),
706 ObjectSafetyViolation::AssocConst(name, _)
707 | ObjectSafetyViolation::Method(name, ..) => {
708 (format!("consider moving `{}` to another trait", name), None)
713 pub fn spans(&self) -> SmallVec<[Span; 1]> {
714 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
715 // diagnostics use a `note` instead of a `span_label`.
717 ObjectSafetyViolation::SupertraitSelf(spans)
718 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
719 ObjectSafetyViolation::AssocConst(_, span)
720 | ObjectSafetyViolation::Method(_, _, span)
721 if *span != DUMMY_SP =>
730 /// Reasons a method might not be object-safe.
731 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
732 pub enum MethodViolationCode {
734 StaticMethod(Option<(&'static str, Span)>),
736 /// e.g., `fn foo(&self, x: Self)`
737 ReferencesSelfInput(usize),
739 /// e.g., `fn foo(&self) -> Self`
740 ReferencesSelfOutput,
742 /// e.g., `fn foo(&self) where Self: Clone`
743 WhereClauseReferencesSelf,
745 /// e.g., `fn foo<A>()`
748 /// the method's receiver (`self` argument) can't be dispatched on
749 UndispatchableReceiver,