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_hir::Constness;
20 use rustc_span::symbol::Symbol;
21 use rustc_span::{Span, DUMMY_SP};
22 use smallvec::SmallVec;
29 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
31 pub type CanonicalChalkEnvironmentAndGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
33 pub use self::ObligationCauseCode::*;
35 pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner};
37 /// Depending on the stage of compilation, we want projection to be
38 /// more or less conservative.
39 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
41 /// At type-checking time, we refuse to project any associated
42 /// type that is marked `default`. Non-`default` ("final") types
43 /// are always projected. This is necessary in general for
44 /// soundness of specialization. However, we *could* allow
45 /// projections in fully-monomorphic cases. We choose not to,
46 /// because we prefer for `default type` to force the type
47 /// definition to be treated abstractly by any consumers of the
48 /// impl. Concretely, that means that the following example will
56 /// impl<T> Assoc for T {
57 /// default type Output = bool;
61 /// let <() as Assoc>::Output = true;
66 /// At codegen time, all monomorphic projections will succeed.
67 /// Also, `impl Trait` is normalized to the concrete type,
68 /// which has to be already collected by type-checking.
70 /// NOTE: as `impl Trait`'s concrete type should *never*
71 /// be observable directly by the user, `Reveal::All`
72 /// should not be used by checks which may expose
73 /// type equality or type contents to the user.
74 /// There are some exceptions, e.g., around auto traits and
75 /// transmute-checking, which expose some details, but
76 /// not the whole concrete type of the `impl Trait`.
80 /// The reason why we incurred this obligation; used for error reporting.
82 /// As the happy path does not care about this struct, storing this on the heap
83 /// ends up increasing performance.
85 /// We do not want to intern this as there are a lot of obligation causes which
86 /// only live for a short period of time.
87 #[derive(Clone, PartialEq, Eq, Hash, Lift)]
88 pub struct ObligationCause<'tcx> {
89 /// `None` for `ObligationCause::dummy`, `Some` otherwise.
90 data: Option<Rc<ObligationCauseData<'tcx>>>,
93 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
94 ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
96 // Correctly format `ObligationCause::dummy`.
97 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 ObligationCauseData::fmt(self, f)
103 impl Deref for ObligationCause<'tcx> {
104 type Target = ObligationCauseData<'tcx>;
107 fn deref(&self) -> &Self::Target {
108 self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
112 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
113 pub struct ObligationCauseData<'tcx> {
116 /// The ID of the fn body that triggered this obligation. This is
117 /// used for region obligations to determine the precise
118 /// environment in which the region obligation should be evaluated
119 /// (in particular, closures can add new assumptions). See the
120 /// field `region_obligations` of the `FulfillmentContext` for more
122 pub body_id: hir::HirId,
124 pub code: ObligationCauseCode<'tcx>,
127 impl<'tcx> ObligationCause<'tcx> {
132 code: ObligationCauseCode<'tcx>,
133 ) -> ObligationCause<'tcx> {
134 ObligationCause { data: Some(Rc::new(ObligationCauseData { span, body_id, code })) }
137 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
138 ObligationCause::new(span, body_id, MiscObligation)
141 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
142 ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
146 pub fn dummy() -> ObligationCause<'tcx> {
147 ObligationCause { data: None }
150 pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
151 Rc::make_mut(self.data.get_or_insert_with(|| Rc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
154 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
156 ObligationCauseCode::CompareImplMethodObligation { .. }
157 | ObligationCauseCode::MainFunctionType
158 | ObligationCauseCode::StartFunctionType => {
159 tcx.sess.source_map().guess_head_span(self.span)
161 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
170 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
171 pub struct UnifyReceiverContext<'tcx> {
172 pub assoc_item: ty::AssocItem,
173 pub param_env: ty::ParamEnv<'tcx>,
174 pub substs: SubstsRef<'tcx>,
177 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
178 pub enum ObligationCauseCode<'tcx> {
179 /// Not well classified or should be obvious from the span.
182 /// A slice or array is WF only if `T: Sized`.
185 /// A tuple is WF only if its middle elements are `Sized`.
188 /// This is the trait reference from the given projection.
189 ProjectionWf(ty::ProjectionTy<'tcx>),
191 /// In an impl of trait `X` for type `Y`, type `Y` must
192 /// also implement all supertraits of `X`.
193 ItemObligation(DefId),
195 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
196 BindingObligation(DefId, Span),
198 /// A type like `&'a T` is WF only if `T: 'a`.
199 ReferenceOutlivesReferent(Ty<'tcx>),
201 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
202 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
204 /// Obligation incurred due to an object cast.
205 ObjectCastObligation(/* Object type */ Ty<'tcx>),
207 /// Obligation incurred due to a coercion.
213 /// Various cases where expressions must be `Sized` / `Copy` / etc.
214 /// `L = X` implies that `L` is `Sized`.
216 /// `(x1, .., xn)` must be `Sized`.
217 TupleInitializerSized,
218 /// `S { ... }` must be `Sized`.
219 StructInitializerSized,
220 /// Type of each variable must be `Sized`.
221 VariableType(hir::HirId),
222 /// Argument type must be `Sized`.
223 SizedArgumentType(Option<Span>),
224 /// Return type must be `Sized`.
226 /// Yield type must be `Sized`.
228 /// Inline asm operand type must be `Sized`.
230 /// `[T, ..n]` implies that `T` must be `Copy`.
231 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
234 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
241 /// Constant expressions must be sized.
244 /// `static` items must have `Sync` type.
247 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
249 ImplDerivedObligation(DerivedObligationCause<'tcx>),
251 DerivedObligation(DerivedObligationCause<'tcx>),
253 /// Error derived when matching traits/impls; see ObligationCause for more details
254 CompareImplConstObligation,
256 /// Error derived when matching traits/impls; see ObligationCause for more details
257 CompareImplMethodObligation {
259 impl_item_def_id: DefId,
260 trait_item_def_id: DefId,
263 /// Error derived when matching traits/impls; see ObligationCause for more details
264 CompareImplTypeObligation {
266 impl_item_def_id: DefId,
267 trait_item_def_id: DefId,
270 /// Checking that this expression can be assigned where it needs to be
271 // FIXME(eddyb) #11161 is the original Expr required?
274 /// Computing common supertype in the arms of a match expression
275 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
277 /// Type error arising from type checking a pattern against an expected type.
279 /// The span of the scrutinee or type expression which caused the `root_ty` type.
281 /// The root expected type induced by a scrutinee or type expression.
283 /// Whether the `Span` came from an expression or a type expression.
287 /// Constants in patterns must have `Structural` type.
288 ConstPatternStructural,
290 /// Computing common supertype in an if expression
291 IfExpression(Box<IfExpressionCause>),
293 /// Computing common supertype of an if expression with no else counter-part
294 IfExpressionWithNoElse,
296 /// `main` has wrong type
299 /// `start` has wrong type
302 /// Intrinsic has wrong type
308 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
310 /// `return` with no expression
313 /// `return` with an expression
314 ReturnValue(hir::HirId),
316 /// Return type of this function
319 /// Block implicit return
320 BlockTailExpression(hir::HirId),
322 /// #[feature(trivial_bounds)] is not enabled
326 impl ObligationCauseCode<'_> {
327 // Return the base obligation, ignoring derived obligations.
328 pub fn peel_derives(&self) -> &Self {
329 let mut base_cause = self;
330 while let BuiltinDerivedObligation(cause)
331 | ImplDerivedObligation(cause)
332 | DerivedObligation(cause) = base_cause
334 base_cause = &cause.parent_code;
340 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
341 #[cfg(target_arch = "x86_64")]
342 static_assert_size!(ObligationCauseCode<'_>, 32);
344 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
345 pub enum StatementAsExpression {
350 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
351 type Lifted = StatementAsExpression;
352 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
357 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
358 pub struct MatchExpressionArmCause<'tcx> {
360 pub scrut_span: Span,
361 pub semi_span: Option<(Span, StatementAsExpression)>,
362 pub source: hir::MatchSource,
363 pub prior_arms: Vec<Span>,
364 pub last_ty: Ty<'tcx>,
365 pub scrut_hir_id: hir::HirId,
366 pub opt_suggest_box_span: Option<Span>,
369 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
370 pub struct IfExpressionCause {
373 pub outer: Option<Span>,
374 pub semicolon: Option<(Span, StatementAsExpression)>,
375 pub opt_suggest_box_span: Option<Span>,
378 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
379 pub struct DerivedObligationCause<'tcx> {
380 /// The trait reference of the parent obligation that led to the
381 /// current obligation. Note that only trait obligations lead to
382 /// derived obligations, so we just store the trait reference here
384 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
386 /// The parent trait had this cause.
387 pub parent_code: Rc<ObligationCauseCode<'tcx>>,
390 #[derive(Clone, Debug, TypeFoldable, Lift)]
391 pub enum SelectionError<'tcx> {
393 OutputTypeParameterMismatch(
394 ty::PolyTraitRef<'tcx>,
395 ty::PolyTraitRef<'tcx>,
396 ty::error::TypeError<'tcx>,
398 TraitNotObjectSafe(DefId),
399 ConstEvalFailure(ErrorHandled),
403 /// When performing resolution, it is typically the case that there
404 /// can be one of three outcomes:
406 /// - `Ok(Some(r))`: success occurred with result `r`
407 /// - `Ok(None)`: could not definitely determine anything, usually due
408 /// to inconclusive type inference.
409 /// - `Err(e)`: error `e` occurred
410 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
412 /// Given the successful resolution of an obligation, the `ImplSource`
413 /// indicates where the impl comes from.
415 /// For example, the obligation may be satisfied by a specific impl (case A),
416 /// or it may be relative to some bound that is in scope (case B).
419 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
420 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
421 /// impl Clone for i32 { ... } // Impl_3
423 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
424 /// // Case A: Vtable points at a specific impl. Only possible when
425 /// // type is concretely known. If the impl itself has bounded
426 /// // type parameters, Vtable will carry resolutions for those as well:
427 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
429 /// // Case A: ImplSource points at a specific impl. Only possible when
430 /// // type is concretely known. If the impl itself has bounded
431 /// // type parameters, ImplSource will carry resolutions for those as well:
432 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
434 /// // Case B: ImplSource must be provided by caller. This applies when
435 /// // type is a type parameter.
436 /// param.clone(); // ImplSource::Param
438 /// // Case C: A mix of cases A and B.
439 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
443 /// ### The type parameter `N`
445 /// See explanation on `ImplSourceUserDefinedData`.
446 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
447 pub enum ImplSource<'tcx, N> {
448 /// ImplSource identifying a particular impl.
449 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
451 /// ImplSource for auto trait implementations.
452 /// This carries the information and nested obligations with regards
453 /// to an auto implementation for a trait `Trait`. The nested obligations
454 /// ensure the trait implementation holds for all the constituent types.
455 AutoImpl(ImplSourceAutoImplData<N>),
457 /// Successful resolution to an obligation provided by the caller
458 /// for some type parameter. The `Vec<N>` represents the
459 /// obligations incurred from normalizing the where-clause (if
461 Param(Vec<N>, Constness),
463 /// Virtual calls through an object.
464 Object(ImplSourceObjectData<'tcx, N>),
466 /// Successful resolution for a builtin trait.
467 Builtin(ImplSourceBuiltinData<N>),
469 /// ImplSource automatically generated for a closure. The `DefId` is the ID
470 /// of the closure expression. This is a `ImplSource::UserDefined` in spirit, but the
471 /// impl is generated by the compiler and does not appear in the source.
472 Closure(ImplSourceClosureData<'tcx, N>),
474 /// Same as above, but for a function pointer type with the given signature.
475 FnPointer(ImplSourceFnPointerData<'tcx, N>),
477 /// ImplSource for a builtin `DeterminantKind` trait implementation.
478 DiscriminantKind(ImplSourceDiscriminantKindData),
480 /// ImplSource automatically generated for a generator.
481 Generator(ImplSourceGeneratorData<'tcx, N>),
483 /// ImplSource for a trait alias.
484 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
487 impl<'tcx, N> ImplSource<'tcx, N> {
488 pub fn nested_obligations(self) -> Vec<N> {
490 ImplSource::UserDefined(i) => i.nested,
491 ImplSource::Param(n, _) => n,
492 ImplSource::Builtin(i) => i.nested,
493 ImplSource::AutoImpl(d) => d.nested,
494 ImplSource::Closure(c) => c.nested,
495 ImplSource::Generator(c) => c.nested,
496 ImplSource::Object(d) => d.nested,
497 ImplSource::FnPointer(d) => d.nested,
498 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => Vec::new(),
499 ImplSource::TraitAlias(d) => d.nested,
503 pub fn borrow_nested_obligations(&self) -> &[N] {
505 ImplSource::UserDefined(i) => &i.nested[..],
506 ImplSource::Param(n, _) => &n[..],
507 ImplSource::Builtin(i) => &i.nested[..],
508 ImplSource::AutoImpl(d) => &d.nested[..],
509 ImplSource::Closure(c) => &c.nested[..],
510 ImplSource::Generator(c) => &c.nested[..],
511 ImplSource::Object(d) => &d.nested[..],
512 ImplSource::FnPointer(d) => &d.nested[..],
513 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => &[],
514 ImplSource::TraitAlias(d) => &d.nested[..],
518 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
523 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
524 impl_def_id: i.impl_def_id,
526 nested: i.nested.into_iter().map(f).collect(),
528 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
529 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
530 nested: i.nested.into_iter().map(f).collect(),
532 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
533 upcast_trait_ref: o.upcast_trait_ref,
534 vtable_base: o.vtable_base,
535 nested: o.nested.into_iter().map(f).collect(),
537 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
538 trait_def_id: d.trait_def_id,
539 nested: d.nested.into_iter().map(f).collect(),
541 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
542 closure_def_id: c.closure_def_id,
544 nested: c.nested.into_iter().map(f).collect(),
546 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
547 generator_def_id: c.generator_def_id,
549 nested: c.nested.into_iter().map(f).collect(),
551 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
553 nested: p.nested.into_iter().map(f).collect(),
555 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
556 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
558 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
559 alias_def_id: d.alias_def_id,
561 nested: d.nested.into_iter().map(f).collect(),
567 /// Identifies a particular impl in the source, along with a set of
568 /// substitutions from the impl's type/lifetime parameters. The
569 /// `nested` vector corresponds to the nested obligations attached to
570 /// the impl's type parameters.
572 /// The type parameter `N` indicates the type used for "nested
573 /// obligations" that are required by the impl. During type-check, this
574 /// is `Obligation`, as one might expect. During codegen, however, this
575 /// is `()`, because codegen only requires a shallow resolution of an
576 /// impl, and nested obligations are satisfied later.
577 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
578 pub struct ImplSourceUserDefinedData<'tcx, N> {
579 pub impl_def_id: DefId,
580 pub substs: SubstsRef<'tcx>,
584 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
585 pub struct ImplSourceGeneratorData<'tcx, N> {
586 pub generator_def_id: DefId,
587 pub substs: SubstsRef<'tcx>,
588 /// Nested obligations. This can be non-empty if the generator
589 /// signature contains associated types.
593 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
594 pub struct ImplSourceClosureData<'tcx, N> {
595 pub closure_def_id: DefId,
596 pub substs: SubstsRef<'tcx>,
597 /// Nested obligations. This can be non-empty if the closure
598 /// signature contains associated types.
602 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
603 pub struct ImplSourceAutoImplData<N> {
604 pub trait_def_id: DefId,
608 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
609 pub struct ImplSourceBuiltinData<N> {
613 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
614 pub struct ImplSourceObjectData<'tcx, N> {
615 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
616 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
618 /// The vtable is formed by concatenating together the method lists of
619 /// the base object trait and all supertraits; this is the start of
620 /// `upcast_trait_ref`'s methods in that vtable.
621 pub vtable_base: usize,
626 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
627 pub struct ImplSourceFnPointerData<'tcx, N> {
632 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
633 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
634 pub struct ImplSourceDiscriminantKindData;
636 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
637 pub struct ImplSourceTraitAliasData<'tcx, N> {
638 pub alias_def_id: DefId,
639 pub substs: SubstsRef<'tcx>,
643 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
644 pub enum ObjectSafetyViolation {
645 /// `Self: Sized` declared on the trait.
646 SizedSelf(SmallVec<[Span; 1]>),
648 /// Supertrait reference references `Self` an in illegal location
649 /// (e.g., `trait Foo : Bar<Self>`).
650 SupertraitSelf(SmallVec<[Span; 1]>),
652 /// Method has something illegal.
653 Method(Symbol, MethodViolationCode, Span),
655 /// Associated const.
656 AssocConst(Symbol, Span),
659 impl ObjectSafetyViolation {
660 pub fn error_msg(&self) -> Cow<'static, str> {
662 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
663 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
664 if spans.iter().any(|sp| *sp != DUMMY_SP) {
665 "it uses `Self` as a type parameter".into()
667 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
671 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
672 format!("associated function `{}` has no `self` parameter", name).into()
674 ObjectSafetyViolation::Method(
676 MethodViolationCode::ReferencesSelfInput(_),
678 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
679 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
680 format!("method `{}` references the `Self` type in this parameter", name).into()
682 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
683 format!("method `{}` references the `Self` type in its return type", name).into()
685 ObjectSafetyViolation::Method(
687 MethodViolationCode::WhereClauseReferencesSelf,
690 format!("method `{}` references the `Self` type in its `where` clause", name).into()
692 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
693 format!("method `{}` has generic type parameters", name).into()
695 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
696 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
698 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
699 format!("it contains associated `const` `{}`", name).into()
701 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
705 pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
707 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
708 ObjectSafetyViolation::Method(
710 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
716 "consider turning `{}` into a method by giving it a `&self` argument",
719 format!("&self{}", if has_args { ", " } else { "" }),
720 Applicability::MaybeIncorrect,
723 Some((sugg, span)) => {
727 "alternatively, consider constraining `{}` so it does not apply to \
732 Applicability::MaybeIncorrect,
737 "consider turning `{}` into a method by giving it a `&self` \
738 argument or constraining it so it does not apply to trait objects",
744 ObjectSafetyViolation::Method(
746 MethodViolationCode::UndispatchableReceiver,
752 "consider changing method `{}`'s `self` parameter to be `&self`",
756 Applicability::MachineApplicable,
759 ObjectSafetyViolation::AssocConst(name, _)
760 | ObjectSafetyViolation::Method(name, ..) => {
761 err.help(&format!("consider moving `{}` to another trait", name));
766 pub fn spans(&self) -> SmallVec<[Span; 1]> {
767 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
768 // diagnostics use a `note` instead of a `span_label`.
770 ObjectSafetyViolation::SupertraitSelf(spans)
771 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
772 ObjectSafetyViolation::AssocConst(_, span)
773 | ObjectSafetyViolation::Method(_, _, span)
774 if *span != DUMMY_SP =>
783 /// Reasons a method might not be object-safe.
784 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
785 pub enum MethodViolationCode {
787 StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
789 /// e.g., `fn foo(&self, x: Self)`
790 ReferencesSelfInput(usize),
792 /// e.g., `fn foo(&self) -> Self`
793 ReferencesSelfOutput,
795 /// e.g., `fn foo(&self) where Self: Clone`
796 WhereClauseReferencesSelf,
798 /// e.g., `fn foo<A>()`
801 /// the method's receiver (`self` argument) can't be dispatched on
802 UndispatchableReceiver,