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};
16 use rustc_errors::{Applicability, DiagnosticBuilder};
18 use rustc_hir::def_id::DefId;
19 use rustc_span::symbol::Symbol;
20 use rustc_span::{Span, DUMMY_SP};
21 use smallvec::SmallVec;
28 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
30 pub type CanonicalChalkEnvironmentAndGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
32 pub use self::ObligationCauseCode::*;
34 pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner};
36 /// Depending on the stage of compilation, we want projection to be
37 /// more or less conservative.
38 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
40 /// At type-checking time, we refuse to project any associated
41 /// type that is marked `default`. Non-`default` ("final") types
42 /// are always projected. This is necessary in general for
43 /// soundness of specialization. However, we *could* allow
44 /// projections in fully-monomorphic cases. We choose not to,
45 /// because we prefer for `default type` to force the type
46 /// definition to be treated abstractly by any consumers of the
47 /// impl. Concretely, that means that the following example will
55 /// impl<T> Assoc for T {
56 /// default type Output = bool;
60 /// let <() as Assoc>::Output = true;
65 /// At codegen time, all monomorphic projections will succeed.
66 /// Also, `impl Trait` is normalized to the concrete type,
67 /// which has to be already collected by type-checking.
69 /// NOTE: as `impl Trait`'s concrete type should *never*
70 /// be observable directly by the user, `Reveal::All`
71 /// should not be used by checks which may expose
72 /// type equality or type contents to the user.
73 /// There are some exceptions, e.g., around OIBITS and
74 /// transmute-checking, which expose some details, but
75 /// not the whole concrete type of the `impl Trait`.
79 /// The reason why we incurred this obligation; used for error reporting.
81 /// As the happy path does not care about this struct, storing this on the heap
82 /// ends up increasing performance.
84 /// We do not want to intern this as there are a lot of obligation causes which
85 /// only live for a short period of time.
86 #[derive(Clone, PartialEq, Eq, Hash, Lift)]
87 pub struct ObligationCause<'tcx> {
88 /// `None` for `ObligationCause::dummy`, `Some` otherwise.
89 data: Option<Rc<ObligationCauseData<'tcx>>>,
92 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
93 ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
95 // Correctly format `ObligationCause::dummy`.
96 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 ObligationCauseData::fmt(self, f)
102 impl Deref for ObligationCause<'tcx> {
103 type Target = ObligationCauseData<'tcx>;
106 fn deref(&self) -> &Self::Target {
107 self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
111 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
112 pub struct ObligationCauseData<'tcx> {
115 /// The ID of the fn body that triggered this obligation. This is
116 /// used for region obligations to determine the precise
117 /// environment in which the region obligation should be evaluated
118 /// (in particular, closures can add new assumptions). See the
119 /// field `region_obligations` of the `FulfillmentContext` for more
121 pub body_id: hir::HirId,
123 pub code: ObligationCauseCode<'tcx>,
126 impl<'tcx> ObligationCause<'tcx> {
131 code: ObligationCauseCode<'tcx>,
132 ) -> ObligationCause<'tcx> {
133 ObligationCause { data: Some(Rc::new(ObligationCauseData { span, body_id, code })) }
136 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
137 ObligationCause::new(span, body_id, MiscObligation)
140 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
141 ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
145 pub fn dummy() -> ObligationCause<'tcx> {
146 ObligationCause { data: None }
149 pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
150 Rc::make_mut(self.data.get_or_insert_with(|| Rc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
153 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
155 ObligationCauseCode::CompareImplMethodObligation { .. }
156 | ObligationCauseCode::MainFunctionType
157 | ObligationCauseCode::StartFunctionType => {
158 tcx.sess.source_map().guess_head_span(self.span)
160 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
169 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
170 pub struct UnifyReceiverContext<'tcx> {
171 pub assoc_item: ty::AssocItem,
172 pub param_env: ty::ParamEnv<'tcx>,
173 pub substs: SubstsRef<'tcx>,
176 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
177 pub enum ObligationCauseCode<'tcx> {
178 /// Not well classified or should be obvious from the span.
181 /// A slice or array is WF only if `T: Sized`.
184 /// A tuple is WF only if its middle elements are `Sized`.
187 /// This is the trait reference from the given projection.
188 ProjectionWf(ty::ProjectionTy<'tcx>),
190 /// In an impl of trait `X` for type `Y`, type `Y` must
191 /// also implement all supertraits of `X`.
192 ItemObligation(DefId),
194 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
195 BindingObligation(DefId, Span),
197 /// A type like `&'a T` is WF only if `T: 'a`.
198 ReferenceOutlivesReferent(Ty<'tcx>),
200 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
201 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
203 /// Obligation incurred due to an object cast.
204 ObjectCastObligation(/* Object type */ Ty<'tcx>),
206 /// Obligation incurred due to a coercion.
212 /// Various cases where expressions must be `Sized` / `Copy` / etc.
213 /// `L = X` implies that `L` is `Sized`.
215 /// `(x1, .., xn)` must be `Sized`.
216 TupleInitializerSized,
217 /// `S { ... }` must be `Sized`.
218 StructInitializerSized,
219 /// Type of each variable must be `Sized`.
220 VariableType(hir::HirId),
221 /// Argument type must be `Sized`.
222 SizedArgumentType(Option<Span>),
223 /// Return type must be `Sized`.
225 /// Yield type must be `Sized`.
227 /// Inline asm operand type must be `Sized`.
229 /// `[T, ..n]` implies that `T` must be `Copy`.
230 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
233 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
240 /// Constant expressions must be sized.
243 /// `static` items must have `Sync` type.
246 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
248 ImplDerivedObligation(DerivedObligationCause<'tcx>),
250 DerivedObligation(DerivedObligationCause<'tcx>),
252 /// Error derived when matching traits/impls; see ObligationCause for more details
253 CompareImplConstObligation,
255 /// Error derived when matching traits/impls; see ObligationCause for more details
256 CompareImplMethodObligation {
258 impl_item_def_id: DefId,
259 trait_item_def_id: DefId,
262 /// Error derived when matching traits/impls; see ObligationCause for more details
263 CompareImplTypeObligation {
265 impl_item_def_id: DefId,
266 trait_item_def_id: DefId,
269 /// Checking that this expression can be assigned where it needs to be
270 // FIXME(eddyb) #11161 is the original Expr required?
273 /// Computing common supertype in the arms of a match expression
274 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
276 /// Type error arising from type checking a pattern against an expected type.
278 /// The span of the scrutinee or type expression which caused the `root_ty` type.
280 /// The root expected type induced by a scrutinee or type expression.
282 /// Whether the `Span` came from an expression or a type expression.
286 /// Constants in patterns must have `Structural` type.
287 ConstPatternStructural,
289 /// Computing common supertype in an if expression
290 IfExpression(Box<IfExpressionCause>),
292 /// Computing common supertype of an if expression with no else counter-part
293 IfExpressionWithNoElse,
295 /// `main` has wrong type
298 /// `start` has wrong type
301 /// Intrinsic has wrong type
307 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
309 /// `return` with no expression
312 /// `return` with an expression
313 ReturnValue(hir::HirId),
315 /// Return type of this function
318 /// Block implicit return
319 BlockTailExpression(hir::HirId),
321 /// #[feature(trivial_bounds)] is not enabled
325 impl ObligationCauseCode<'_> {
326 // Return the base obligation, ignoring derived obligations.
327 pub fn peel_derives(&self) -> &Self {
328 let mut base_cause = self;
329 while let BuiltinDerivedObligation(cause)
330 | ImplDerivedObligation(cause)
331 | DerivedObligation(cause) = base_cause
333 base_cause = &cause.parent_code;
339 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
340 #[cfg(target_arch = "x86_64")]
341 static_assert_size!(ObligationCauseCode<'_>, 32);
343 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
344 pub struct MatchExpressionArmCause<'tcx> {
346 pub scrut_span: Span,
347 pub semi_span: Option<Span>,
348 pub source: hir::MatchSource,
349 pub prior_arms: Vec<Span>,
350 pub last_ty: Ty<'tcx>,
351 pub scrut_hir_id: hir::HirId,
352 pub opt_suggest_box_span: Option<Span>,
355 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
356 pub struct IfExpressionCause {
359 pub outer: Option<Span>,
360 pub semicolon: Option<Span>,
361 pub opt_suggest_box_span: Option<Span>,
364 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
365 pub struct DerivedObligationCause<'tcx> {
366 /// The trait reference of the parent obligation that led to the
367 /// current obligation. Note that only trait obligations lead to
368 /// derived obligations, so we just store the trait reference here
370 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
372 /// The parent trait had this cause.
373 pub parent_code: Rc<ObligationCauseCode<'tcx>>,
376 #[derive(Clone, Debug, TypeFoldable, Lift)]
377 pub enum SelectionError<'tcx> {
379 OutputTypeParameterMismatch(
380 ty::PolyTraitRef<'tcx>,
381 ty::PolyTraitRef<'tcx>,
382 ty::error::TypeError<'tcx>,
384 TraitNotObjectSafe(DefId),
385 ConstEvalFailure(ErrorHandled),
389 /// When performing resolution, it is typically the case that there
390 /// can be one of three outcomes:
392 /// - `Ok(Some(r))`: success occurred with result `r`
393 /// - `Ok(None)`: could not definitely determine anything, usually due
394 /// to inconclusive type inference.
395 /// - `Err(e)`: error `e` occurred
396 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
398 /// Given the successful resolution of an obligation, the `ImplSource`
399 /// indicates where the impl comes from.
401 /// For example, the obligation may be satisfied by a specific impl (case A),
402 /// or it may be relative to some bound that is in scope (case B).
405 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
406 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
407 /// impl Clone for i32 { ... } // Impl_3
409 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
410 /// // Case A: Vtable points at a specific impl. Only possible when
411 /// // type is concretely known. If the impl itself has bounded
412 /// // type parameters, Vtable will carry resolutions for those as well:
413 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
415 /// // Case A: ImplSource points at a specific impl. Only possible when
416 /// // type is concretely known. If the impl itself has bounded
417 /// // type parameters, ImplSource will carry resolutions for those as well:
418 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
420 /// // Case B: ImplSource must be provided by caller. This applies when
421 /// // type is a type parameter.
422 /// param.clone(); // ImplSource::Param
424 /// // Case C: A mix of cases A and B.
425 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
429 /// ### The type parameter `N`
431 /// See explanation on `ImplSourceUserDefinedData`.
432 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
433 pub enum ImplSource<'tcx, N> {
434 /// ImplSource identifying a particular impl.
435 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
437 /// ImplSource for auto trait implementations.
438 /// This carries the information and nested obligations with regards
439 /// to an auto implementation for a trait `Trait`. The nested obligations
440 /// ensure the trait implementation holds for all the constituent types.
441 AutoImpl(ImplSourceAutoImplData<N>),
443 /// Successful resolution to an obligation provided by the caller
444 /// for some type parameter. The `Vec<N>` represents the
445 /// obligations incurred from normalizing the where-clause (if
449 /// Virtual calls through an object.
450 Object(ImplSourceObjectData<'tcx, N>),
452 /// Successful resolution for a builtin trait.
453 Builtin(ImplSourceBuiltinData<N>),
455 /// ImplSource automatically generated for a closure. The `DefId` is the ID
456 /// of the closure expression. This is a `ImplSource::UserDefined` in spirit, but the
457 /// impl is generated by the compiler and does not appear in the source.
458 Closure(ImplSourceClosureData<'tcx, N>),
460 /// Same as above, but for a function pointer type with the given signature.
461 FnPointer(ImplSourceFnPointerData<'tcx, N>),
463 /// ImplSource for a builtin `DeterminantKind` trait implementation.
464 DiscriminantKind(ImplSourceDiscriminantKindData),
466 /// ImplSource automatically generated for a generator.
467 Generator(ImplSourceGeneratorData<'tcx, N>),
469 /// ImplSource for a trait alias.
470 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
473 impl<'tcx, N> ImplSource<'tcx, N> {
474 pub fn nested_obligations(self) -> Vec<N> {
476 ImplSource::UserDefined(i) => i.nested,
477 ImplSource::Param(n) => n,
478 ImplSource::Builtin(i) => i.nested,
479 ImplSource::AutoImpl(d) => d.nested,
480 ImplSource::Closure(c) => c.nested,
481 ImplSource::Generator(c) => c.nested,
482 ImplSource::Object(d) => d.nested,
483 ImplSource::FnPointer(d) => d.nested,
484 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => Vec::new(),
485 ImplSource::TraitAlias(d) => d.nested,
489 pub fn borrow_nested_obligations(&self) -> &[N] {
491 ImplSource::UserDefined(i) => &i.nested[..],
492 ImplSource::Param(n) => &n[..],
493 ImplSource::Builtin(i) => &i.nested[..],
494 ImplSource::AutoImpl(d) => &d.nested[..],
495 ImplSource::Closure(c) => &c.nested[..],
496 ImplSource::Generator(c) => &c.nested[..],
497 ImplSource::Object(d) => &d.nested[..],
498 ImplSource::FnPointer(d) => &d.nested[..],
499 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => &[],
500 ImplSource::TraitAlias(d) => &d.nested[..],
504 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
509 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
510 impl_def_id: i.impl_def_id,
512 nested: i.nested.into_iter().map(f).collect(),
514 ImplSource::Param(n) => ImplSource::Param(n.into_iter().map(f).collect()),
515 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
516 nested: i.nested.into_iter().map(f).collect(),
518 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
519 upcast_trait_ref: o.upcast_trait_ref,
520 vtable_base: o.vtable_base,
521 nested: o.nested.into_iter().map(f).collect(),
523 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
524 trait_def_id: d.trait_def_id,
525 nested: d.nested.into_iter().map(f).collect(),
527 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
528 closure_def_id: c.closure_def_id,
530 nested: c.nested.into_iter().map(f).collect(),
532 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
533 generator_def_id: c.generator_def_id,
535 nested: c.nested.into_iter().map(f).collect(),
537 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
539 nested: p.nested.into_iter().map(f).collect(),
541 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
542 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
544 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
545 alias_def_id: d.alias_def_id,
547 nested: d.nested.into_iter().map(f).collect(),
553 /// Identifies a particular impl in the source, along with a set of
554 /// substitutions from the impl's type/lifetime parameters. The
555 /// `nested` vector corresponds to the nested obligations attached to
556 /// the impl's type parameters.
558 /// The type parameter `N` indicates the type used for "nested
559 /// obligations" that are required by the impl. During type-check, this
560 /// is `Obligation`, as one might expect. During codegen, however, this
561 /// is `()`, because codegen only requires a shallow resolution of an
562 /// impl, and nested obligations are satisfied later.
563 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
564 pub struct ImplSourceUserDefinedData<'tcx, N> {
565 pub impl_def_id: DefId,
566 pub substs: SubstsRef<'tcx>,
570 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
571 pub struct ImplSourceGeneratorData<'tcx, N> {
572 pub generator_def_id: DefId,
573 pub substs: SubstsRef<'tcx>,
574 /// Nested obligations. This can be non-empty if the generator
575 /// signature contains associated types.
579 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
580 pub struct ImplSourceClosureData<'tcx, N> {
581 pub closure_def_id: DefId,
582 pub substs: SubstsRef<'tcx>,
583 /// Nested obligations. This can be non-empty if the closure
584 /// signature contains associated types.
588 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
589 pub struct ImplSourceAutoImplData<N> {
590 pub trait_def_id: DefId,
594 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
595 pub struct ImplSourceBuiltinData<N> {
599 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
600 pub struct ImplSourceObjectData<'tcx, N> {
601 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
602 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
604 /// The vtable is formed by concatenating together the method lists of
605 /// the base object trait and all supertraits; this is the start of
606 /// `upcast_trait_ref`'s methods in that vtable.
607 pub vtable_base: usize,
612 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
613 pub struct ImplSourceFnPointerData<'tcx, N> {
618 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
619 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
620 pub struct ImplSourceDiscriminantKindData;
622 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
623 pub struct ImplSourceTraitAliasData<'tcx, N> {
624 pub alias_def_id: DefId,
625 pub substs: SubstsRef<'tcx>,
629 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
630 pub enum ObjectSafetyViolation {
631 /// `Self: Sized` declared on the trait.
632 SizedSelf(SmallVec<[Span; 1]>),
634 /// Supertrait reference references `Self` an in illegal location
635 /// (e.g., `trait Foo : Bar<Self>`).
636 SupertraitSelf(SmallVec<[Span; 1]>),
638 /// Method has something illegal.
639 Method(Symbol, MethodViolationCode, Span),
641 /// Associated const.
642 AssocConst(Symbol, Span),
645 impl ObjectSafetyViolation {
646 pub fn error_msg(&self) -> Cow<'static, str> {
648 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
649 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
650 if spans.iter().any(|sp| *sp != DUMMY_SP) {
651 "it uses `Self` as a type parameter".into()
653 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
657 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
658 format!("associated function `{}` has no `self` parameter", name).into()
660 ObjectSafetyViolation::Method(
662 MethodViolationCode::ReferencesSelfInput(_),
664 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
665 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
666 format!("method `{}` references the `Self` type in this parameter", name).into()
668 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
669 format!("method `{}` references the `Self` type in its return type", name).into()
671 ObjectSafetyViolation::Method(
673 MethodViolationCode::WhereClauseReferencesSelf,
676 format!("method `{}` references the `Self` type in its `where` clause", name).into()
678 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
679 format!("method `{}` has generic type parameters", name).into()
681 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
682 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
684 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
685 format!("it contains associated `const` `{}`", name).into()
687 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
691 pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
693 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
694 ObjectSafetyViolation::Method(
696 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
702 "consider turning `{}` into a method by giving it a `&self` argument",
705 format!("&self{}", if has_args { ", " } else { "" }),
706 Applicability::MaybeIncorrect,
709 Some((sugg, span)) => {
713 "alternatively, consider constraining `{}` so it does not apply to \
718 Applicability::MaybeIncorrect,
723 "consider turning `{}` into a method by giving it a `&self` \
724 argument or constraining it so it does not apply to trait objects",
730 ObjectSafetyViolation::Method(
732 MethodViolationCode::UndispatchableReceiver,
738 "consider changing method `{}`'s `self` parameter to be `&self`",
742 Applicability::MachineApplicable,
745 ObjectSafetyViolation::AssocConst(name, _)
746 | ObjectSafetyViolation::Method(name, ..) => {
747 err.help(&format!("consider moving `{}` to another trait", name));
752 pub fn spans(&self) -> SmallVec<[Span; 1]> {
753 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
754 // diagnostics use a `note` instead of a `span_label`.
756 ObjectSafetyViolation::SupertraitSelf(spans)
757 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
758 ObjectSafetyViolation::AssocConst(_, span)
759 | ObjectSafetyViolation::Method(_, _, span)
760 if *span != DUMMY_SP =>
769 /// Reasons a method might not be object-safe.
770 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
771 pub enum MethodViolationCode {
773 StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
775 /// e.g., `fn foo(&self, x: Self)`
776 ReferencesSelfInput(usize),
778 /// e.g., `fn foo(&self) -> Self`
779 ReferencesSelfOutput,
781 /// e.g., `fn foo(&self) where Self: Clone`
782 WhereClauseReferencesSelf,
784 /// e.g., `fn foo<A>()`
787 /// the method's receiver (`self` argument) can't be dispatched on
788 UndispatchableReceiver,