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
7 pub mod specialization_graph
;
10 use crate::mir
::interpret
::ErrorHandled
;
11 use crate::ty
::subst
::SubstsRef
;
12 use crate::ty
::{self, AdtKind, List, Ty, TyCtxt}
;
16 use rustc_hir
::def_id
::DefId
;
17 use rustc_span
::{Span, DUMMY_SP}
;
18 use smallvec
::SmallVec
;
24 pub use self::select
::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache}
;
26 pub use self::ObligationCauseCode
::*;
27 pub use self::SelectionError
::*;
28 pub use self::Vtable
::*;
30 /// Depending on the stage of compilation, we want projection to be
31 /// more or less conservative.
32 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
34 /// At type-checking time, we refuse to project any associated
35 /// type that is marked `default`. Non-`default` ("final") types
36 /// are always projected. This is necessary in general for
37 /// soundness of specialization. However, we *could* allow
38 /// projections in fully-monomorphic cases. We choose not to,
39 /// because we prefer for `default type` to force the type
40 /// definition to be treated abstractly by any consumers of the
41 /// impl. Concretely, that means that the following example will
49 /// impl<T> Assoc for T {
50 /// default type Output = bool;
54 /// let <() as Assoc>::Output = true;
59 /// At codegen time, all monomorphic projections will succeed.
60 /// Also, `impl Trait` is normalized to the concrete type,
61 /// which has to be already collected by type-checking.
63 /// NOTE: as `impl Trait`'s concrete type should *never*
64 /// be observable directly by the user, `Reveal::All`
65 /// should not be used by checks which may expose
66 /// type equality or type contents to the user.
67 /// There are some exceptions, e.g., around OIBITS and
68 /// transmute-checking, which expose some details, but
69 /// not the whole concrete type of the `impl Trait`.
73 /// The reason why we incurred this obligation; used for error reporting.
74 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
75 pub struct ObligationCause
<'tcx
> {
78 /// The ID of the fn body that triggered this obligation. This is
79 /// used for region obligations to determine the precise
80 /// environment in which the region obligation should be evaluated
81 /// (in particular, closures can add new assumptions). See the
82 /// field `region_obligations` of the `FulfillmentContext` for more
84 pub body_id
: hir
::HirId
,
86 pub code
: ObligationCauseCode
<'tcx
>,
89 impl<'tcx
> ObligationCause
<'tcx
> {
94 code
: ObligationCauseCode
<'tcx
>,
95 ) -> ObligationCause
<'tcx
> {
96 ObligationCause { span, body_id, code }
99 pub fn misc(span
: Span
, body_id
: hir
::HirId
) -> ObligationCause
<'tcx
> {
100 ObligationCause { span, body_id, code: MiscObligation }
103 pub fn dummy() -> ObligationCause
<'tcx
> {
104 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
107 pub fn span(&self, tcx
: TyCtxt
<'tcx
>) -> Span
{
109 ObligationCauseCode
::CompareImplMethodObligation { .. }
110 | ObligationCauseCode
::MainFunctionType
111 | ObligationCauseCode
::StartFunctionType
=> {
112 tcx
.sess
.source_map().guess_head_span(self.span
)
114 ObligationCauseCode
::MatchExpressionArm(box MatchExpressionArmCause
{
123 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
124 pub enum ObligationCauseCode
<'tcx
> {
125 /// Not well classified or should be obvious from the span.
128 /// A slice or array is WF only if `T: Sized`.
131 /// A tuple is WF only if its middle elements are `Sized`.
134 /// This is the trait reference from the given projection.
135 ProjectionWf(ty
::ProjectionTy
<'tcx
>),
137 /// In an impl of trait `X` for type `Y`, type `Y` must
138 /// also implement all supertraits of `X`.
139 ItemObligation(DefId
),
141 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
142 BindingObligation(DefId
, Span
),
144 /// A type like `&'a T` is WF only if `T: 'a`.
145 ReferenceOutlivesReferent(Ty
<'tcx
>),
147 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
148 ObjectTypeBound(Ty
<'tcx
>, ty
::Region
<'tcx
>),
150 /// Obligation incurred due to an object cast.
151 ObjectCastObligation(/* Object type */ Ty
<'tcx
>),
153 /// Obligation incurred due to a coercion.
159 /// Various cases where expressions must be `Sized` / `Copy` / etc.
160 /// `L = X` implies that `L` is `Sized`.
162 /// `(x1, .., xn)` must be `Sized`.
163 TupleInitializerSized
,
164 /// `S { ... }` must be `Sized`.
165 StructInitializerSized
,
166 /// Type of each variable must be `Sized`.
167 VariableType(hir
::HirId
),
168 /// Argument type must be `Sized`.
170 /// Return type must be `Sized`.
172 /// Yield type must be `Sized`.
174 /// `[T, ..n]` implies that `T` must be `Copy`.
175 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
178 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
184 /// Constant expressions must be sized.
187 /// `static` items must have `Sync` type.
190 BuiltinDerivedObligation(DerivedObligationCause
<'tcx
>),
192 ImplDerivedObligation(DerivedObligationCause
<'tcx
>),
194 DerivedObligation(DerivedObligationCause
<'tcx
>),
196 /// Error derived when matching traits/impls; see ObligationCause for more details
197 CompareImplMethodObligation
{
198 item_name
: ast
::Name
,
199 impl_item_def_id
: DefId
,
200 trait_item_def_id
: DefId
,
203 /// Error derived when matching traits/impls; see ObligationCause for more details
204 CompareImplTypeObligation
{
205 item_name
: ast
::Name
,
206 impl_item_def_id
: DefId
,
207 trait_item_def_id
: DefId
,
210 /// Checking that this expression can be assigned where it needs to be
211 // FIXME(eddyb) #11161 is the original Expr required?
214 /// Computing common supertype in the arms of a match expression
215 MatchExpressionArm(Box
<MatchExpressionArmCause
<'tcx
>>),
217 /// Type error arising from type checking a pattern against an expected type.
219 /// The span of the scrutinee or type expression which caused the `root_ty` type.
221 /// The root expected type induced by a scrutinee or type expression.
223 /// Whether the `Span` came from an expression or a type expression.
227 /// Constants in patterns must have `Structural` type.
228 ConstPatternStructural
,
230 /// Computing common supertype in an if expression
231 IfExpression(Box
<IfExpressionCause
>),
233 /// Computing common supertype of an if expression with no else counter-part
234 IfExpressionWithNoElse
,
236 /// `main` has wrong type
239 /// `start` has wrong type
242 /// Intrinsic has wrong type
248 /// `return` with no expression
251 /// `return` with an expression
252 ReturnValue(hir
::HirId
),
254 /// Return type of this function
257 /// Block implicit return
258 BlockTailExpression(hir
::HirId
),
260 /// #[feature(trivial_bounds)] is not enabled
264 impl ObligationCauseCode
<'_
> {
265 // Return the base obligation, ignoring derived obligations.
266 pub fn peel_derives(&self) -> &Self {
267 let mut base_cause
= self;
268 while let BuiltinDerivedObligation(cause
)
269 | ImplDerivedObligation(cause
)
270 | DerivedObligation(cause
) = base_cause
272 base_cause
= &cause
.parent_code
;
278 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
279 #[cfg(target_arch = "x86_64")]
280 static_assert_size
!(ObligationCauseCode
<'_
>, 32);
282 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
283 pub struct MatchExpressionArmCause
<'tcx
> {
285 pub source
: hir
::MatchSource
,
286 pub prior_arms
: Vec
<Span
>,
287 pub last_ty
: Ty
<'tcx
>,
288 pub scrut_hir_id
: hir
::HirId
,
291 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
292 pub struct IfExpressionCause
{
294 pub outer
: Option
<Span
>,
295 pub semicolon
: Option
<Span
>,
298 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
299 pub struct DerivedObligationCause
<'tcx
> {
300 /// The trait reference of the parent obligation that led to the
301 /// current obligation. Note that only trait obligations lead to
302 /// derived obligations, so we just store the trait reference here
304 pub parent_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
306 /// The parent trait had this cause.
307 pub parent_code
: Rc
<ObligationCauseCode
<'tcx
>>,
310 /// The following types:
318 /// * `InEnvironment`,
319 /// are used for representing the trait system in the form of
320 /// logic programming clauses. They are part of the interface
321 /// for the chalk SLG solver.
322 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
323 pub enum WhereClause
<'tcx
> {
324 Implemented(ty
::TraitPredicate
<'tcx
>),
325 ProjectionEq(ty
::ProjectionPredicate
<'tcx
>),
326 RegionOutlives(ty
::RegionOutlivesPredicate
<'tcx
>),
327 TypeOutlives(ty
::TypeOutlivesPredicate
<'tcx
>),
330 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
331 pub enum WellFormed
<'tcx
> {
332 Trait(ty
::TraitPredicate
<'tcx
>),
336 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
337 pub enum FromEnv
<'tcx
> {
338 Trait(ty
::TraitPredicate
<'tcx
>),
342 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
343 pub enum DomainGoal
<'tcx
> {
344 Holds(WhereClause
<'tcx
>),
345 WellFormed(WellFormed
<'tcx
>),
346 FromEnv(FromEnv
<'tcx
>),
347 Normalize(ty
::ProjectionPredicate
<'tcx
>),
350 pub type PolyDomainGoal
<'tcx
> = ty
::Binder
<DomainGoal
<'tcx
>>;
352 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
353 pub enum QuantifierKind
{
358 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
359 pub enum GoalKind
<'tcx
> {
360 Implies(Clauses
<'tcx
>, Goal
<'tcx
>),
361 And(Goal
<'tcx
>, Goal
<'tcx
>),
363 DomainGoal(DomainGoal
<'tcx
>),
364 Quantified(QuantifierKind
, ty
::Binder
<Goal
<'tcx
>>),
365 Subtype(Ty
<'tcx
>, Ty
<'tcx
>),
369 pub type Goal
<'tcx
> = &'tcx GoalKind
<'tcx
>;
371 pub type Goals
<'tcx
> = &'tcx List
<Goal
<'tcx
>>;
373 impl<'tcx
> DomainGoal
<'tcx
> {
374 pub fn into_goal(self) -> GoalKind
<'tcx
> {
375 GoalKind
::DomainGoal(self)
378 pub fn into_program_clause(self) -> ProgramClause
<'tcx
> {
381 hypotheses
: ty
::List
::empty(),
382 category
: ProgramClauseCategory
::Other
,
387 impl<'tcx
> GoalKind
<'tcx
> {
388 pub fn from_poly_domain_goal(
389 domain_goal
: PolyDomainGoal
<'tcx
>,
391 ) -> GoalKind
<'tcx
> {
392 match domain_goal
.no_bound_vars() {
393 Some(p
) => p
.into_goal(),
394 None
=> GoalKind
::Quantified(
395 QuantifierKind
::Universal
,
396 domain_goal
.map_bound(|p
| tcx
.mk_goal(p
.into_goal())),
402 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
403 /// Harrop Formulas".
404 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
405 pub enum Clause
<'tcx
> {
406 Implies(ProgramClause
<'tcx
>),
407 ForAll(ty
::Binder
<ProgramClause
<'tcx
>>),
411 pub fn category(self) -> ProgramClauseCategory
{
413 Clause
::Implies(clause
) => clause
.category
,
414 Clause
::ForAll(clause
) => clause
.skip_binder().category
,
419 /// Multiple clauses.
420 pub type Clauses
<'tcx
> = &'tcx List
<Clause
<'tcx
>>;
422 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
423 /// that the domain goal `D` is true if `G1...Gn` are provable. This
424 /// is equivalent to the implication `G1..Gn => D`; we usually write
425 /// it with the reverse implication operator `:-` to emphasize the way
426 /// that programs are actually solved (via backchaining, which starts
427 /// with the goal to solve and proceeds from there).
428 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
429 pub struct ProgramClause
<'tcx
> {
430 /// This goal will be considered true ...
431 pub goal
: DomainGoal
<'tcx
>,
433 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
434 pub hypotheses
: Goals
<'tcx
>,
436 /// Useful for filtering clauses.
437 pub category
: ProgramClauseCategory
,
440 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
441 pub enum ProgramClauseCategory
{
447 /// A set of clauses that we assume to be true.
448 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
449 pub struct Environment
<'tcx
> {
450 pub clauses
: Clauses
<'tcx
>,
453 impl Environment
<'tcx
> {
454 pub fn with
<G
>(self, goal
: G
) -> InEnvironment
<'tcx
, G
> {
455 InEnvironment { environment: self, goal }
459 /// Something (usually a goal), along with an environment.
460 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
461 pub struct InEnvironment
<'tcx
, G
> {
462 pub environment
: Environment
<'tcx
>,
466 #[derive(Clone, Debug, TypeFoldable)]
467 pub enum SelectionError
<'tcx
> {
469 OutputTypeParameterMismatch(
470 ty
::PolyTraitRef
<'tcx
>,
471 ty
::PolyTraitRef
<'tcx
>,
472 ty
::error
::TypeError
<'tcx
>,
474 TraitNotObjectSafe(DefId
),
475 ConstEvalFailure(ErrorHandled
),
479 /// When performing resolution, it is typically the case that there
480 /// can be one of three outcomes:
482 /// - `Ok(Some(r))`: success occurred with result `r`
483 /// - `Ok(None)`: could not definitely determine anything, usually due
484 /// to inconclusive type inference.
485 /// - `Err(e)`: error `e` occurred
486 pub type SelectionResult
<'tcx
, T
> = Result
<Option
<T
>, SelectionError
<'tcx
>>;
488 /// Given the successful resolution of an obligation, the `Vtable`
489 /// indicates where the vtable comes from. Note that while we call this
490 /// a "vtable", it does not necessarily indicate dynamic dispatch at
491 /// runtime. `Vtable` instances just tell the compiler where to find
492 /// methods, but in generic code those methods are typically statically
493 /// dispatched -- only when an object is constructed is a `Vtable`
494 /// instance reified into an actual vtable.
496 /// For example, the vtable may be tied to a specific impl (case A),
497 /// or it may be relative to some bound that is in scope (case B).
500 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
501 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
502 /// impl Clone for int { ... } // Impl_3
504 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
506 /// mixed: Option<T>) {
508 /// // Case A: Vtable points at a specific impl. Only possible when
509 /// // type is concretely known. If the impl itself has bounded
510 /// // type parameters, Vtable will carry resolutions for those as well:
511 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
513 /// // Case B: Vtable must be provided by caller. This applies when
514 /// // type is a type parameter.
515 /// param.clone(); // VtableParam
517 /// // Case C: A mix of cases A and B.
518 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
522 /// ### The type parameter `N`
524 /// See explanation on `VtableImplData`.
525 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
526 pub enum Vtable
<'tcx
, N
> {
527 /// Vtable identifying a particular impl.
528 VtableImpl(VtableImplData
<'tcx
, N
>),
530 /// Vtable for auto trait implementations.
531 /// This carries the information and nested obligations with regards
532 /// to an auto implementation for a trait `Trait`. The nested obligations
533 /// ensure the trait implementation holds for all the constituent types.
534 VtableAutoImpl(VtableAutoImplData
<N
>),
536 /// Successful resolution to an obligation provided by the caller
537 /// for some type parameter. The `Vec<N>` represents the
538 /// obligations incurred from normalizing the where-clause (if
542 /// Virtual calls through an object.
543 VtableObject(VtableObjectData
<'tcx
, N
>),
545 /// Successful resolution for a builtin trait.
546 VtableBuiltin(VtableBuiltinData
<N
>),
548 /// Vtable automatically generated for a closure. The `DefId` is the ID
549 /// of the closure expression. This is a `VtableImpl` in spirit, but the
550 /// impl is generated by the compiler and does not appear in the source.
551 VtableClosure(VtableClosureData
<'tcx
, N
>),
553 /// Same as above, but for a function pointer type with the given signature.
554 VtableFnPointer(VtableFnPointerData
<'tcx
, N
>),
556 /// Vtable automatically generated for a generator.
557 VtableGenerator(VtableGeneratorData
<'tcx
, N
>),
559 /// Vtable for a trait alias.
560 VtableTraitAlias(VtableTraitAliasData
<'tcx
, N
>),
563 impl<'tcx
, N
> Vtable
<'tcx
, N
> {
564 pub fn nested_obligations(self) -> Vec
<N
> {
566 VtableImpl(i
) => i
.nested
,
568 VtableBuiltin(i
) => i
.nested
,
569 VtableAutoImpl(d
) => d
.nested
,
570 VtableClosure(c
) => c
.nested
,
571 VtableGenerator(c
) => c
.nested
,
572 VtableObject(d
) => d
.nested
,
573 VtableFnPointer(d
) => d
.nested
,
574 VtableTraitAlias(d
) => d
.nested
,
578 pub fn borrow_nested_obligations(&self) -> &[N
] {
580 VtableImpl(i
) => &i
.nested
[..],
581 VtableParam(n
) => &n
[..],
582 VtableBuiltin(i
) => &i
.nested
[..],
583 VtableAutoImpl(d
) => &d
.nested
[..],
584 VtableClosure(c
) => &c
.nested
[..],
585 VtableGenerator(c
) => &c
.nested
[..],
586 VtableObject(d
) => &d
.nested
[..],
587 VtableFnPointer(d
) => &d
.nested
[..],
588 VtableTraitAlias(d
) => &d
.nested
[..],
592 pub fn map
<M
, F
>(self, f
: F
) -> Vtable
<'tcx
, M
>
597 VtableImpl(i
) => VtableImpl(VtableImplData
{
598 impl_def_id
: i
.impl_def_id
,
600 nested
: i
.nested
.into_iter().map(f
).collect(),
602 VtableParam(n
) => VtableParam(n
.into_iter().map(f
).collect()),
603 VtableBuiltin(i
) => {
604 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() }
)
606 VtableObject(o
) => VtableObject(VtableObjectData
{
607 upcast_trait_ref
: o
.upcast_trait_ref
,
608 vtable_base
: o
.vtable_base
,
609 nested
: o
.nested
.into_iter().map(f
).collect(),
611 VtableAutoImpl(d
) => VtableAutoImpl(VtableAutoImplData
{
612 trait_def_id
: d
.trait_def_id
,
613 nested
: d
.nested
.into_iter().map(f
).collect(),
615 VtableClosure(c
) => VtableClosure(VtableClosureData
{
616 closure_def_id
: c
.closure_def_id
,
618 nested
: c
.nested
.into_iter().map(f
).collect(),
620 VtableGenerator(c
) => VtableGenerator(VtableGeneratorData
{
621 generator_def_id
: c
.generator_def_id
,
623 nested
: c
.nested
.into_iter().map(f
).collect(),
625 VtableFnPointer(p
) => VtableFnPointer(VtableFnPointerData
{
627 nested
: p
.nested
.into_iter().map(f
).collect(),
629 VtableTraitAlias(d
) => VtableTraitAlias(VtableTraitAliasData
{
630 alias_def_id
: d
.alias_def_id
,
632 nested
: d
.nested
.into_iter().map(f
).collect(),
638 /// Identifies a particular impl in the source, along with a set of
639 /// substitutions from the impl's type/lifetime parameters. The
640 /// `nested` vector corresponds to the nested obligations attached to
641 /// the impl's type parameters.
643 /// The type parameter `N` indicates the type used for "nested
644 /// obligations" that are required by the impl. During type-check, this
645 /// is `Obligation`, as one might expect. During codegen, however, this
646 /// is `()`, because codegen only requires a shallow resolution of an
647 /// impl, and nested obligations are satisfied later.
648 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
649 pub struct VtableImplData
<'tcx
, N
> {
650 pub impl_def_id
: DefId
,
651 pub substs
: SubstsRef
<'tcx
>,
655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
656 pub struct VtableGeneratorData
<'tcx
, N
> {
657 pub generator_def_id
: DefId
,
658 pub substs
: SubstsRef
<'tcx
>,
659 /// Nested obligations. This can be non-empty if the generator
660 /// signature contains associated types.
664 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
665 pub struct VtableClosureData
<'tcx
, N
> {
666 pub closure_def_id
: DefId
,
667 pub substs
: SubstsRef
<'tcx
>,
668 /// Nested obligations. This can be non-empty if the closure
669 /// signature contains associated types.
673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
674 pub struct VtableAutoImplData
<N
> {
675 pub trait_def_id
: DefId
,
679 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
680 pub struct VtableBuiltinData
<N
> {
684 /// A vtable for some object-safe trait `Foo` automatically derived
685 /// for the object type `Foo`.
686 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
687 pub struct VtableObjectData
<'tcx
, N
> {
688 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
689 pub upcast_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
691 /// The vtable is formed by concatenating together the method lists of
692 /// the base object trait and all supertraits; this is the start of
693 /// `upcast_trait_ref`'s methods in that vtable.
694 pub vtable_base
: usize,
699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
700 pub struct VtableFnPointerData
<'tcx
, N
> {
705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
706 pub struct VtableTraitAliasData
<'tcx
, N
> {
707 pub alias_def_id
: DefId
,
708 pub substs
: SubstsRef
<'tcx
>,
712 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
713 pub enum ObjectSafetyViolation
{
714 /// `Self: Sized` declared on the trait.
715 SizedSelf(SmallVec
<[Span
; 1]>),
717 /// Supertrait reference references `Self` an in illegal location
718 /// (e.g., `trait Foo : Bar<Self>`).
719 SupertraitSelf(SmallVec
<[Span
; 1]>),
721 /// Method has something illegal.
722 Method(ast
::Name
, MethodViolationCode
, Span
),
724 /// Associated const.
725 AssocConst(ast
::Name
, Span
),
728 impl ObjectSafetyViolation
{
729 pub fn error_msg(&self) -> Cow
<'
static, str> {
731 ObjectSafetyViolation
::SizedSelf(_
) => "it requires `Self: Sized`".into(),
732 ObjectSafetyViolation
::SupertraitSelf(ref spans
) => {
733 if spans
.iter().any(|sp
| *sp
!= DUMMY_SP
) {
734 "it uses `Self` as a type parameter in this".into()
736 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
740 ObjectSafetyViolation
::Method(name
, MethodViolationCode
::StaticMethod(_
), _
) => {
741 format
!("associated function `{}` has no `self` parameter", name
).into()
743 ObjectSafetyViolation
::Method(
745 MethodViolationCode
::ReferencesSelfInput(_
),
747 ) => format
!("method `{}` references the `Self` type in its parameters", name
).into(),
748 ObjectSafetyViolation
::Method(name
, MethodViolationCode
::ReferencesSelfInput(_
), _
) => {
749 format
!("method `{}` references the `Self` type in this parameter", name
).into()
751 ObjectSafetyViolation
::Method(name
, MethodViolationCode
::ReferencesSelfOutput
, _
) => {
752 format
!("method `{}` references the `Self` type in its return type", name
).into()
754 ObjectSafetyViolation
::Method(
756 MethodViolationCode
::WhereClauseReferencesSelf
,
759 format
!("method `{}` references the `Self` type in its `where` clause", name
).into()
761 ObjectSafetyViolation
::Method(name
, MethodViolationCode
::Generic
, _
) => {
762 format
!("method `{}` has generic type parameters", name
).into()
764 ObjectSafetyViolation
::Method(name
, MethodViolationCode
::UndispatchableReceiver
, _
) => {
765 format
!("method `{}`'s `self` parameter cannot be dispatched on", name
).into()
767 ObjectSafetyViolation
::AssocConst(name
, DUMMY_SP
) => {
768 format
!("it contains associated `const` `{}`", name
).into()
770 ObjectSafetyViolation
::AssocConst(..) => "it contains this associated `const`".into(),
774 pub fn solution(&self) -> Option
<(String
, Option
<(String
, Span
)>)> {
776 ObjectSafetyViolation
::SizedSelf(_
) | ObjectSafetyViolation
::SupertraitSelf(_
) => {
779 ObjectSafetyViolation
::Method(name
, MethodViolationCode
::StaticMethod(sugg
), _
) => (
781 "consider turning `{}` into a method by giving it a `&self` argument or \
782 constraining it so it does not apply to trait objects",
785 sugg
.map(|(sugg
, sp
)| (sugg
.to_string(), sp
)),
787 ObjectSafetyViolation
::Method(
789 MethodViolationCode
::UndispatchableReceiver
,
792 format
!("consider changing method `{}`'s `self` parameter to be `&self`", name
),
793 Some(("&Self".to_string(), span
)),
795 ObjectSafetyViolation
::AssocConst(name
, _
)
796 | ObjectSafetyViolation
::Method(name
, ..) => {
797 (format
!("consider moving `{}` to another trait", name
), None
)
802 pub fn spans(&self) -> SmallVec
<[Span
; 1]> {
803 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
804 // diagnostics use a `note` instead of a `span_label`.
806 ObjectSafetyViolation
::SupertraitSelf(spans
)
807 | ObjectSafetyViolation
::SizedSelf(spans
) => spans
.clone(),
808 ObjectSafetyViolation
::AssocConst(_
, span
)
809 | ObjectSafetyViolation
::Method(_
, _
, span
)
810 if *span
!= DUMMY_SP
=>
819 /// Reasons a method might not be object-safe.
820 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
821 pub enum MethodViolationCode
{
823 StaticMethod(Option
<(&'
static str, Span
)>),
825 /// e.g., `fn foo(&self, x: Self)`
826 ReferencesSelfInput(usize),
828 /// e.g., `fn foo(&self) -> Self`
829 ReferencesSelfOutput
,
831 /// e.g., `fn foo(&self) where Self: Clone`
832 WhereClauseReferencesSelf
,
834 /// e.g., `fn foo<A>()`
837 /// the method's receiver (`self` argument) can't be dispatched on
838 UndispatchableReceiver
,