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::abstract_const::NotConstEvaluatable;
13 use crate::ty::subst::SubstsRef;
14 use crate::ty::{self, AdtKind, Ty, TyCtxt};
16 use rustc_data_structures::sync::Lrc;
17 use rustc_errors::{Applicability, DiagnosticBuilder};
19 use rustc_hir::def_id::{DefId, LocalDefId};
20 use rustc_hir::Constness;
21 use rustc_span::symbol::Symbol;
22 use rustc_span::{Span, DUMMY_SP};
23 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<Lrc<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(Lrc::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 Lrc::make_mut(self.data.get_or_insert_with(|| Lrc::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 the function in the array repeat expression is a `const fn`,
232 /// display a help message suggesting to move the function call to a
233 /// new `const` item while saying that `T` doesn't implement `Copy`.
236 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
243 /// Constant expressions must be sized.
246 /// `static` items must have `Sync` type.
249 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
251 ImplDerivedObligation(DerivedObligationCause<'tcx>),
253 DerivedObligation(DerivedObligationCause<'tcx>),
255 /// Error derived when matching traits/impls; see ObligationCause for more details
256 CompareImplConstObligation,
258 /// Error derived when matching traits/impls; see ObligationCause for more details
259 CompareImplMethodObligation {
261 impl_item_def_id: DefId,
262 trait_item_def_id: DefId,
265 /// Error derived when matching traits/impls; see ObligationCause for more details
266 CompareImplTypeObligation {
268 impl_item_def_id: DefId,
269 trait_item_def_id: DefId,
272 /// Checking that this expression can be assigned where it needs to be
273 // FIXME(eddyb) #11161 is the original Expr required?
276 /// Computing common supertype in the arms of a match expression
277 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
279 /// Type error arising from type checking a pattern against an expected type.
281 /// The span of the scrutinee or type expression which caused the `root_ty` type.
283 /// The root expected type induced by a scrutinee or type expression.
285 /// Whether the `Span` came from an expression or a type expression.
289 /// Constants in patterns must have `Structural` type.
290 ConstPatternStructural,
292 /// Computing common supertype in an if expression
293 IfExpression(Box<IfExpressionCause>),
295 /// Computing common supertype of an if expression with no else counter-part
296 IfExpressionWithNoElse,
298 /// `main` has wrong type
301 /// `start` has wrong type
304 /// Intrinsic has wrong type
310 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
312 /// `return` with no expression
315 /// `return` with an expression
316 ReturnValue(hir::HirId),
318 /// Return type of this function
321 /// Block implicit return
322 BlockTailExpression(hir::HirId),
324 /// #[feature(trivial_bounds)] is not enabled
327 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
330 /// Well-formed checking. If a `WellFormedLoc` is provided,
331 /// then it will be used to eprform HIR-based wf checking
332 /// after an error occurs, in order to generate a more precise error span.
333 /// This is purely for diagnostic purposes - it is always
334 /// correct to use `MiscObligation` instead, or to specify
335 /// `WellFormed(None)`
336 WellFormed(Option<WellFormedLoc>),
338 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
339 MatchImpl(Lrc<ObligationCauseCode<'tcx>>, DefId),
342 /// The 'location' at which we try to perform HIR-based wf checking.
343 /// This information is used to obtain an `hir::Ty`, which
344 /// we can walk in order to obtain precise spans for any
345 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
346 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
347 pub enum WellFormedLoc {
348 /// Use the type of the provided definition.
350 /// Use the type of the parameter of the provided function.
351 /// We cannot use `hir::Param`, since the function may
352 /// not have a body (e.g. a trait method definition)
354 /// The function to lookup the parameter in
355 function: LocalDefId,
356 /// The index of the parameter to use.
357 /// Parameters are indexed from 0, with the return type
358 /// being the last 'parameter'
363 impl ObligationCauseCode<'_> {
364 // Return the base obligation, ignoring derived obligations.
365 pub fn peel_derives(&self) -> &Self {
366 let mut base_cause = self;
367 while let BuiltinDerivedObligation(cause)
368 | ImplDerivedObligation(cause)
369 | DerivedObligation(cause) = base_cause
371 base_cause = &cause.parent_code;
377 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
378 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
379 static_assert_size!(ObligationCauseCode<'_>, 40);
381 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
382 pub enum StatementAsExpression {
387 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
388 type Lifted = StatementAsExpression;
389 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
394 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
395 pub struct MatchExpressionArmCause<'tcx> {
397 pub scrut_span: Span,
398 pub semi_span: Option<(Span, StatementAsExpression)>,
399 pub source: hir::MatchSource,
400 pub prior_arms: Vec<Span>,
401 pub last_ty: Ty<'tcx>,
402 pub scrut_hir_id: hir::HirId,
403 pub opt_suggest_box_span: Option<Span>,
406 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
407 pub struct IfExpressionCause {
410 pub outer: Option<Span>,
411 pub semicolon: Option<(Span, StatementAsExpression)>,
412 pub opt_suggest_box_span: Option<Span>,
415 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
416 pub struct DerivedObligationCause<'tcx> {
417 /// The trait reference of the parent obligation that led to the
418 /// current obligation. Note that only trait obligations lead to
419 /// derived obligations, so we just store the trait reference here
421 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
423 /// The parent trait had this cause.
424 pub parent_code: Lrc<ObligationCauseCode<'tcx>>,
427 #[derive(Clone, Debug, TypeFoldable, Lift)]
428 pub enum SelectionError<'tcx> {
430 OutputTypeParameterMismatch(
431 ty::PolyTraitRef<'tcx>,
432 ty::PolyTraitRef<'tcx>,
433 ty::error::TypeError<'tcx>,
435 TraitNotObjectSafe(DefId),
436 NotConstEvaluatable(NotConstEvaluatable),
440 /// When performing resolution, it is typically the case that there
441 /// can be one of three outcomes:
443 /// - `Ok(Some(r))`: success occurred with result `r`
444 /// - `Ok(None)`: could not definitely determine anything, usually due
445 /// to inconclusive type inference.
446 /// - `Err(e)`: error `e` occurred
447 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
449 /// Given the successful resolution of an obligation, the `ImplSource`
450 /// indicates where the impl comes from.
452 /// For example, the obligation may be satisfied by a specific impl (case A),
453 /// or it may be relative to some bound that is in scope (case B).
456 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
457 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
458 /// impl Clone for i32 { ... } // Impl_3
460 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
461 /// // Case A: ImplSource points at a specific impl. Only possible when
462 /// // type is concretely known. If the impl itself has bounded
463 /// // type parameters, ImplSource will carry resolutions for those as well:
464 /// concrete.clone(); // ImpleSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
466 /// // Case A: ImplSource points at a specific impl. Only possible when
467 /// // type is concretely known. If the impl itself has bounded
468 /// // type parameters, ImplSource will carry resolutions for those as well:
469 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
471 /// // Case B: ImplSource must be provided by caller. This applies when
472 /// // type is a type parameter.
473 /// param.clone(); // ImplSource::Param
475 /// // Case C: A mix of cases A and B.
476 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
480 /// ### The type parameter `N`
482 /// See explanation on `ImplSourceUserDefinedData`.
483 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
484 pub enum ImplSource<'tcx, N> {
485 /// ImplSource identifying a particular impl.
486 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
488 /// ImplSource for auto trait implementations.
489 /// This carries the information and nested obligations with regards
490 /// to an auto implementation for a trait `Trait`. The nested obligations
491 /// ensure the trait implementation holds for all the constituent types.
492 AutoImpl(ImplSourceAutoImplData<N>),
494 /// Successful resolution to an obligation provided by the caller
495 /// for some type parameter. The `Vec<N>` represents the
496 /// obligations incurred from normalizing the where-clause (if
498 Param(Vec<N>, Constness),
500 /// Virtual calls through an object.
501 Object(ImplSourceObjectData<'tcx, N>),
503 /// Successful resolution for a builtin trait.
504 Builtin(ImplSourceBuiltinData<N>),
506 /// ImplSource automatically generated for a closure. The `DefId` is the ID
507 /// of the closure expression. This is a `ImplSource::UserDefined` in spirit, but the
508 /// impl is generated by the compiler and does not appear in the source.
509 Closure(ImplSourceClosureData<'tcx, N>),
511 /// Same as above, but for a function pointer type with the given signature.
512 FnPointer(ImplSourceFnPointerData<'tcx, N>),
514 /// ImplSource for a builtin `DeterminantKind` trait implementation.
515 DiscriminantKind(ImplSourceDiscriminantKindData),
517 /// ImplSource for a builtin `Pointee` trait implementation.
518 Pointee(ImplSourcePointeeData),
520 /// ImplSource automatically generated for a generator.
521 Generator(ImplSourceGeneratorData<'tcx, N>),
523 /// ImplSource for a trait alias.
524 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
527 impl<'tcx, N> ImplSource<'tcx, N> {
528 pub fn nested_obligations(self) -> Vec<N> {
530 ImplSource::UserDefined(i) => i.nested,
531 ImplSource::Param(n, _) => n,
532 ImplSource::Builtin(i) => i.nested,
533 ImplSource::AutoImpl(d) => d.nested,
534 ImplSource::Closure(c) => c.nested,
535 ImplSource::Generator(c) => c.nested,
536 ImplSource::Object(d) => d.nested,
537 ImplSource::FnPointer(d) => d.nested,
538 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
539 | ImplSource::Pointee(ImplSourcePointeeData) => Vec::new(),
540 ImplSource::TraitAlias(d) => d.nested,
544 pub fn borrow_nested_obligations(&self) -> &[N] {
546 ImplSource::UserDefined(i) => &i.nested[..],
547 ImplSource::Param(n, _) => &n[..],
548 ImplSource::Builtin(i) => &i.nested[..],
549 ImplSource::AutoImpl(d) => &d.nested[..],
550 ImplSource::Closure(c) => &c.nested[..],
551 ImplSource::Generator(c) => &c.nested[..],
552 ImplSource::Object(d) => &d.nested[..],
553 ImplSource::FnPointer(d) => &d.nested[..],
554 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
555 | ImplSource::Pointee(ImplSourcePointeeData) => &[],
556 ImplSource::TraitAlias(d) => &d.nested[..],
560 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
565 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
566 impl_def_id: i.impl_def_id,
568 nested: i.nested.into_iter().map(f).collect(),
570 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
571 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
572 nested: i.nested.into_iter().map(f).collect(),
574 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
575 upcast_trait_ref: o.upcast_trait_ref,
576 vtable_base: o.vtable_base,
577 nested: o.nested.into_iter().map(f).collect(),
579 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
580 trait_def_id: d.trait_def_id,
581 nested: d.nested.into_iter().map(f).collect(),
583 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
584 closure_def_id: c.closure_def_id,
586 nested: c.nested.into_iter().map(f).collect(),
588 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
589 generator_def_id: c.generator_def_id,
591 nested: c.nested.into_iter().map(f).collect(),
593 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
595 nested: p.nested.into_iter().map(f).collect(),
597 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
598 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
600 ImplSource::Pointee(ImplSourcePointeeData) => {
601 ImplSource::Pointee(ImplSourcePointeeData)
603 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
604 alias_def_id: d.alias_def_id,
606 nested: d.nested.into_iter().map(f).collect(),
612 /// Identifies a particular impl in the source, along with a set of
613 /// substitutions from the impl's type/lifetime parameters. The
614 /// `nested` vector corresponds to the nested obligations attached to
615 /// the impl's type parameters.
617 /// The type parameter `N` indicates the type used for "nested
618 /// obligations" that are required by the impl. During type-check, this
619 /// is `Obligation`, as one might expect. During codegen, however, this
620 /// is `()`, because codegen only requires a shallow resolution of an
621 /// impl, and nested obligations are satisfied later.
622 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
623 pub struct ImplSourceUserDefinedData<'tcx, N> {
624 pub impl_def_id: DefId,
625 pub substs: SubstsRef<'tcx>,
629 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
630 pub struct ImplSourceGeneratorData<'tcx, N> {
631 pub generator_def_id: DefId,
632 pub substs: SubstsRef<'tcx>,
633 /// Nested obligations. This can be non-empty if the generator
634 /// signature contains associated types.
638 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
639 pub struct ImplSourceClosureData<'tcx, N> {
640 pub closure_def_id: DefId,
641 pub substs: SubstsRef<'tcx>,
642 /// Nested obligations. This can be non-empty if the closure
643 /// signature contains associated types.
647 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
648 pub struct ImplSourceAutoImplData<N> {
649 pub trait_def_id: DefId,
653 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
654 pub struct ImplSourceBuiltinData<N> {
658 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
659 pub struct ImplSourceObjectData<'tcx, N> {
660 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
661 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
663 /// The vtable is formed by concatenating together the method lists of
664 /// the base object trait and all supertraits; this is the start of
665 /// `upcast_trait_ref`'s methods in that vtable.
666 pub vtable_base: usize,
671 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
672 pub struct ImplSourceFnPointerData<'tcx, N> {
677 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
678 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
679 pub struct ImplSourceDiscriminantKindData;
681 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
682 pub struct ImplSourcePointeeData;
684 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
685 pub struct ImplSourceTraitAliasData<'tcx, N> {
686 pub alias_def_id: DefId,
687 pub substs: SubstsRef<'tcx>,
691 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
692 pub enum ObjectSafetyViolation {
693 /// `Self: Sized` declared on the trait.
694 SizedSelf(SmallVec<[Span; 1]>),
696 /// Supertrait reference references `Self` an in illegal location
697 /// (e.g., `trait Foo : Bar<Self>`).
698 SupertraitSelf(SmallVec<[Span; 1]>),
700 /// Method has something illegal.
701 Method(Symbol, MethodViolationCode, Span),
703 /// Associated const.
704 AssocConst(Symbol, Span),
710 impl ObjectSafetyViolation {
711 pub fn error_msg(&self) -> Cow<'static, str> {
713 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
714 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
715 if spans.iter().any(|sp| *sp != DUMMY_SP) {
716 "it uses `Self` as a type parameter".into()
718 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
722 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
723 format!("associated function `{}` has no `self` parameter", name).into()
725 ObjectSafetyViolation::Method(
727 MethodViolationCode::ReferencesSelfInput(_),
729 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
730 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
731 format!("method `{}` references the `Self` type in this parameter", name).into()
733 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
734 format!("method `{}` references the `Self` type in its return type", name).into()
736 ObjectSafetyViolation::Method(
738 MethodViolationCode::WhereClauseReferencesSelf,
741 format!("method `{}` references the `Self` type in its `where` clause", name).into()
743 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
744 format!("method `{}` has generic type parameters", name).into()
746 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
747 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
749 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
750 format!("it contains associated `const` `{}`", name).into()
752 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
753 ObjectSafetyViolation::GAT(name, _) => {
754 format!("it contains the generic associated type `{}`", name).into()
759 pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
761 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
762 ObjectSafetyViolation::Method(
764 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
770 "consider turning `{}` into a method by giving it a `&self` argument",
773 format!("&self{}", if has_args { ", " } else { "" }),
774 Applicability::MaybeIncorrect,
777 Some((sugg, span)) => {
781 "alternatively, consider constraining `{}` so it does not apply to \
786 Applicability::MaybeIncorrect,
791 "consider turning `{}` into a method by giving it a `&self` \
792 argument or constraining it so it does not apply to trait objects",
798 ObjectSafetyViolation::Method(
800 MethodViolationCode::UndispatchableReceiver,
806 "consider changing method `{}`'s `self` parameter to be `&self`",
810 Applicability::MachineApplicable,
813 ObjectSafetyViolation::AssocConst(name, _)
814 | ObjectSafetyViolation::GAT(name, _)
815 | ObjectSafetyViolation::Method(name, ..) => {
816 err.help(&format!("consider moving `{}` to another trait", name));
821 pub fn spans(&self) -> SmallVec<[Span; 1]> {
822 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
823 // diagnostics use a `note` instead of a `span_label`.
825 ObjectSafetyViolation::SupertraitSelf(spans)
826 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
827 ObjectSafetyViolation::AssocConst(_, span)
828 | ObjectSafetyViolation::GAT(_, span)
829 | ObjectSafetyViolation::Method(_, _, span)
830 if *span != DUMMY_SP =>
839 /// Reasons a method might not be object-safe.
840 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
841 pub enum MethodViolationCode {
843 StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
845 /// e.g., `fn foo(&self, x: Self)`
846 ReferencesSelfInput(usize),
848 /// e.g., `fn foo(&self) -> Self`
849 ReferencesSelfOutput,
851 /// e.g., `fn foo(&self) where Self: Clone`
852 WhereClauseReferencesSelf,
854 /// e.g., `fn foo<A>()`
857 /// the method's receiver (`self` argument) can't be dispatched on
858 UndispatchableReceiver,