]> git.lizzy.rs Git - rust.git/blob - src/librustc_middle/traits/mod.rs
use enum to represent ObligationCause::dummy without allocating
[rust.git] / src / librustc_middle / traits / mod.rs
1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
4
5 mod chalk;
6 pub mod query;
7 pub mod select;
8 pub mod specialization_graph;
9 mod structural_impls;
10
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};
15
16 use rustc_hir as hir;
17 use rustc_hir::def_id::DefId;
18 use rustc_span::symbol::Symbol;
19 use rustc_span::{Span, DUMMY_SP};
20 use smallvec::SmallVec;
21
22 use std::borrow::Cow;
23 use std::fmt;
24 use std::ops::Deref;
25 use std::rc::Rc;
26
27 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
28
29 pub type ChalkCanonicalGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
30
31 pub use self::ObligationCauseCode::*;
32 pub use self::SelectionError::*;
33 pub use self::Vtable::*;
34
35 pub use self::chalk::{
36     ChalkEnvironmentAndGoal, ChalkEnvironmentClause, RustDefId as ChalkRustDefId,
37     RustInterner as ChalkRustInterner,
38 };
39
40 /// Depending on the stage of compilation, we want projection to be
41 /// more or less conservative.
42 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
43 pub enum Reveal {
44     /// At type-checking time, we refuse to project any associated
45     /// type that is marked `default`. Non-`default` ("final") types
46     /// are always projected. This is necessary in general for
47     /// soundness of specialization. However, we *could* allow
48     /// projections in fully-monomorphic cases. We choose not to,
49     /// because we prefer for `default type` to force the type
50     /// definition to be treated abstractly by any consumers of the
51     /// impl. Concretely, that means that the following example will
52     /// fail to compile:
53     ///
54     /// ```
55     /// trait Assoc {
56     ///     type Output;
57     /// }
58     ///
59     /// impl<T> Assoc for T {
60     ///     default type Output = bool;
61     /// }
62     ///
63     /// fn main() {
64     ///     let <() as Assoc>::Output = true;
65     /// }
66     /// ```
67     UserFacing,
68
69     /// At codegen time, all monomorphic projections will succeed.
70     /// Also, `impl Trait` is normalized to the concrete type,
71     /// which has to be already collected by type-checking.
72     ///
73     /// NOTE: as `impl Trait`'s concrete type should *never*
74     /// be observable directly by the user, `Reveal::All`
75     /// should not be used by checks which may expose
76     /// type equality or type contents to the user.
77     /// There are some exceptions, e.g., around OIBITS and
78     /// transmute-checking, which expose some details, but
79     /// not the whole concrete type of the `impl Trait`.
80     All,
81 }
82
83 /// The reason why we incurred this obligation; used for error reporting.
84 ///
85 /// As the happy path does not care about this struct, storing this on the heap
86 /// ends up increasing performance.
87 ///
88 /// We do not want to intern this as there are a lot of obligation causes which
89 /// only live for a short period of time.
90 #[derive(Clone, PartialEq, Eq, Hash)]
91 pub struct ObligationCause<'tcx> {
92     /// `None` for `ObligationCause::dummy`, `Some` otherwise.
93     data: Option<Rc<ObligationCauseData<'tcx>>>,
94 }
95
96 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
97     ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
98
99 // Correctly format `ObligationCause::dummy`.
100 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
101     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102         ObligationCauseData::fmt(self, f)
103     }
104 }
105
106 impl Deref for ObligationCause<'tcx> {
107     type Target = ObligationCauseData<'tcx>;
108
109     #[inline(always)]
110     fn deref(&self) -> &Self::Target {
111         self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
112     }
113 }
114
115 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
116 pub struct ObligationCauseData<'tcx> {
117     pub span: Span,
118
119     /// The ID of the fn body that triggered this obligation. This is
120     /// used for region obligations to determine the precise
121     /// environment in which the region obligation should be evaluated
122     /// (in particular, closures can add new assumptions). See the
123     /// field `region_obligations` of the `FulfillmentContext` for more
124     /// information.
125     pub body_id: hir::HirId,
126
127     pub code: ObligationCauseCode<'tcx>,
128 }
129
130 impl<'tcx> ObligationCause<'tcx> {
131     #[inline]
132     pub fn new(
133         span: Span,
134         body_id: hir::HirId,
135         code: ObligationCauseCode<'tcx>,
136     ) -> ObligationCause<'tcx> {
137         ObligationCause { data: Some(Rc::new(ObligationCauseData { span, body_id, code })) }
138     }
139
140     pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
141         ObligationCause::new(span, body_id, MiscObligation)
142     }
143
144     pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
145         ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
146     }
147
148     #[inline(always)]
149     pub fn dummy() -> ObligationCause<'tcx> {
150         ObligationCause { data: None }
151     }
152
153     pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
154         Rc::make_mut(self.data.get_or_insert_with(|| Rc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
155     }
156
157     pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
158         match self.code {
159             ObligationCauseCode::CompareImplMethodObligation { .. }
160             | ObligationCauseCode::MainFunctionType
161             | ObligationCauseCode::StartFunctionType => {
162                 tcx.sess.source_map().guess_head_span(self.span)
163             }
164             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
165                 arm_span,
166                 ..
167             }) => arm_span,
168             _ => self.span,
169         }
170     }
171 }
172
173 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
174 pub enum ObligationCauseCode<'tcx> {
175     /// Not well classified or should be obvious from the span.
176     MiscObligation,
177
178     /// A slice or array is WF only if `T: Sized`.
179     SliceOrArrayElem,
180
181     /// A tuple is WF only if its middle elements are `Sized`.
182     TupleElem,
183
184     /// This is the trait reference from the given projection.
185     ProjectionWf(ty::ProjectionTy<'tcx>),
186
187     /// In an impl of trait `X` for type `Y`, type `Y` must
188     /// also implement all supertraits of `X`.
189     ItemObligation(DefId),
190
191     /// Like `ItemObligation`, but with extra detail on the source of the obligation.
192     BindingObligation(DefId, Span),
193
194     /// A type like `&'a T` is WF only if `T: 'a`.
195     ReferenceOutlivesReferent(Ty<'tcx>),
196
197     /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
198     ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
199
200     /// Obligation incurred due to an object cast.
201     ObjectCastObligation(/* Object type */ Ty<'tcx>),
202
203     /// Obligation incurred due to a coercion.
204     Coercion {
205         source: Ty<'tcx>,
206         target: Ty<'tcx>,
207     },
208
209     /// Various cases where expressions must be `Sized` / `Copy` / etc.
210     /// `L = X` implies that `L` is `Sized`.
211     AssignmentLhsSized,
212     /// `(x1, .., xn)` must be `Sized`.
213     TupleInitializerSized,
214     /// `S { ... }` must be `Sized`.
215     StructInitializerSized,
216     /// Type of each variable must be `Sized`.
217     VariableType(hir::HirId),
218     /// Argument type must be `Sized`.
219     SizedArgumentType,
220     /// Return type must be `Sized`.
221     SizedReturnType,
222     /// Yield type must be `Sized`.
223     SizedYieldType,
224     /// Inline asm operand type must be `Sized`.
225     InlineAsmSized,
226     /// `[T, ..n]` implies that `T` must be `Copy`.
227     /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
228     RepeatVec(bool),
229
230     /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
231     FieldSized {
232         adt_kind: AdtKind,
233         last: bool,
234     },
235
236     /// Constant expressions must be sized.
237     ConstSized,
238
239     /// `static` items must have `Sync` type.
240     SharedStatic,
241
242     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
243
244     ImplDerivedObligation(DerivedObligationCause<'tcx>),
245
246     DerivedObligation(DerivedObligationCause<'tcx>),
247
248     /// Error derived when matching traits/impls; see ObligationCause for more details
249     CompareImplConstObligation,
250
251     /// Error derived when matching traits/impls; see ObligationCause for more details
252     CompareImplMethodObligation {
253         item_name: Symbol,
254         impl_item_def_id: DefId,
255         trait_item_def_id: DefId,
256     },
257
258     /// Error derived when matching traits/impls; see ObligationCause for more details
259     CompareImplTypeObligation {
260         item_name: Symbol,
261         impl_item_def_id: DefId,
262         trait_item_def_id: DefId,
263     },
264
265     /// Checking that this expression can be assigned where it needs to be
266     // FIXME(eddyb) #11161 is the original Expr required?
267     ExprAssignable,
268
269     /// Computing common supertype in the arms of a match expression
270     MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
271
272     /// Type error arising from type checking a pattern against an expected type.
273     Pattern {
274         /// The span of the scrutinee or type expression which caused the `root_ty` type.
275         span: Option<Span>,
276         /// The root expected type induced by a scrutinee or type expression.
277         root_ty: Ty<'tcx>,
278         /// Whether the `Span` came from an expression or a type expression.
279         origin_expr: bool,
280     },
281
282     /// Constants in patterns must have `Structural` type.
283     ConstPatternStructural,
284
285     /// Computing common supertype in an if expression
286     IfExpression(Box<IfExpressionCause>),
287
288     /// Computing common supertype of an if expression with no else counter-part
289     IfExpressionWithNoElse,
290
291     /// `main` has wrong type
292     MainFunctionType,
293
294     /// `start` has wrong type
295     StartFunctionType,
296
297     /// Intrinsic has wrong type
298     IntrinsicType,
299
300     /// Method receiver
301     MethodReceiver,
302
303     /// `return` with no expression
304     ReturnNoExpression,
305
306     /// `return` with an expression
307     ReturnValue(hir::HirId),
308
309     /// Return type of this function
310     ReturnType,
311
312     /// Block implicit return
313     BlockTailExpression(hir::HirId),
314
315     /// #[feature(trivial_bounds)] is not enabled
316     TrivialBound,
317 }
318
319 impl ObligationCauseCode<'_> {
320     // Return the base obligation, ignoring derived obligations.
321     pub fn peel_derives(&self) -> &Self {
322         let mut base_cause = self;
323         while let BuiltinDerivedObligation(cause)
324         | ImplDerivedObligation(cause)
325         | DerivedObligation(cause) = base_cause
326         {
327             base_cause = &cause.parent_code;
328         }
329         base_cause
330     }
331 }
332
333 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
334 #[cfg(target_arch = "x86_64")]
335 static_assert_size!(ObligationCauseCode<'_>, 32);
336
337 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
338 pub struct MatchExpressionArmCause<'tcx> {
339     pub arm_span: Span,
340     pub source: hir::MatchSource,
341     pub prior_arms: Vec<Span>,
342     pub last_ty: Ty<'tcx>,
343     pub scrut_hir_id: hir::HirId,
344 }
345
346 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
347 pub struct IfExpressionCause {
348     pub then: Span,
349     pub outer: Option<Span>,
350     pub semicolon: Option<Span>,
351 }
352
353 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
354 pub struct DerivedObligationCause<'tcx> {
355     /// The trait reference of the parent obligation that led to the
356     /// current obligation. Note that only trait obligations lead to
357     /// derived obligations, so we just store the trait reference here
358     /// directly.
359     pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
360
361     /// The parent trait had this cause.
362     pub parent_code: Rc<ObligationCauseCode<'tcx>>,
363 }
364
365 #[derive(Clone, Debug, TypeFoldable)]
366 pub enum SelectionError<'tcx> {
367     Unimplemented,
368     OutputTypeParameterMismatch(
369         ty::PolyTraitRef<'tcx>,
370         ty::PolyTraitRef<'tcx>,
371         ty::error::TypeError<'tcx>,
372     ),
373     TraitNotObjectSafe(DefId),
374     ConstEvalFailure(ErrorHandled),
375     Overflow,
376 }
377
378 /// When performing resolution, it is typically the case that there
379 /// can be one of three outcomes:
380 ///
381 /// - `Ok(Some(r))`: success occurred with result `r`
382 /// - `Ok(None)`: could not definitely determine anything, usually due
383 ///   to inconclusive type inference.
384 /// - `Err(e)`: error `e` occurred
385 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
386
387 /// Given the successful resolution of an obligation, the `Vtable`
388 /// indicates where the vtable comes from. Note that while we call this
389 /// a "vtable", it does not necessarily indicate dynamic dispatch at
390 /// runtime. `Vtable` instances just tell the compiler where to find
391 /// methods, but in generic code those methods are typically statically
392 /// dispatched -- only when an object is constructed is a `Vtable`
393 /// instance reified into an actual vtable.
394 ///
395 /// For example, the vtable may be tied to a specific impl (case A),
396 /// or it may be relative to some bound that is in scope (case B).
397 ///
398 /// ```
399 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
400 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
401 /// impl Clone for int { ... }             // Impl_3
402 ///
403 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
404 ///                 param: T,
405 ///                 mixed: Option<T>) {
406 ///
407 ///    // Case A: Vtable points at a specific impl. Only possible when
408 ///    // type is concretely known. If the impl itself has bounded
409 ///    // type parameters, Vtable will carry resolutions for those as well:
410 ///    concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
411 ///
412 ///    // Case B: Vtable must be provided by caller. This applies when
413 ///    // type is a type parameter.
414 ///    param.clone();    // VtableParam
415 ///
416 ///    // Case C: A mix of cases A and B.
417 ///    mixed.clone();    // Vtable(Impl_1, [VtableParam])
418 /// }
419 /// ```
420 ///
421 /// ### The type parameter `N`
422 ///
423 /// See explanation on `VtableImplData`.
424 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
425 pub enum Vtable<'tcx, N> {
426     /// Vtable identifying a particular impl.
427     VtableImpl(VtableImplData<'tcx, N>),
428
429     /// Vtable for auto trait implementations.
430     /// This carries the information and nested obligations with regards
431     /// to an auto implementation for a trait `Trait`. The nested obligations
432     /// ensure the trait implementation holds for all the constituent types.
433     VtableAutoImpl(VtableAutoImplData<N>),
434
435     /// Successful resolution to an obligation provided by the caller
436     /// for some type parameter. The `Vec<N>` represents the
437     /// obligations incurred from normalizing the where-clause (if
438     /// any).
439     VtableParam(Vec<N>),
440
441     /// Virtual calls through an object.
442     VtableObject(VtableObjectData<'tcx, N>),
443
444     /// Successful resolution for a builtin trait.
445     VtableBuiltin(VtableBuiltinData<N>),
446
447     /// Vtable automatically generated for a closure. The `DefId` is the ID
448     /// of the closure expression. This is a `VtableImpl` in spirit, but the
449     /// impl is generated by the compiler and does not appear in the source.
450     VtableClosure(VtableClosureData<'tcx, N>),
451
452     /// Same as above, but for a function pointer type with the given signature.
453     VtableFnPointer(VtableFnPointerData<'tcx, N>),
454
455     /// Vtable for a builtin `DeterminantKind` trait implementation.
456     VtableDiscriminantKind(VtableDiscriminantKindData),
457
458     /// Vtable automatically generated for a generator.
459     VtableGenerator(VtableGeneratorData<'tcx, N>),
460
461     /// Vtable for a trait alias.
462     VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
463 }
464
465 impl<'tcx, N> Vtable<'tcx, N> {
466     pub fn nested_obligations(self) -> Vec<N> {
467         match self {
468             VtableImpl(i) => i.nested,
469             VtableParam(n) => n,
470             VtableBuiltin(i) => i.nested,
471             VtableAutoImpl(d) => d.nested,
472             VtableClosure(c) => c.nested,
473             VtableGenerator(c) => c.nested,
474             VtableObject(d) => d.nested,
475             VtableFnPointer(d) => d.nested,
476             VtableDiscriminantKind(VtableDiscriminantKindData) => Vec::new(),
477             VtableTraitAlias(d) => d.nested,
478         }
479     }
480
481     pub fn borrow_nested_obligations(&self) -> &[N] {
482         match &self {
483             VtableImpl(i) => &i.nested[..],
484             VtableParam(n) => &n[..],
485             VtableBuiltin(i) => &i.nested[..],
486             VtableAutoImpl(d) => &d.nested[..],
487             VtableClosure(c) => &c.nested[..],
488             VtableGenerator(c) => &c.nested[..],
489             VtableObject(d) => &d.nested[..],
490             VtableFnPointer(d) => &d.nested[..],
491             VtableDiscriminantKind(VtableDiscriminantKindData) => &[],
492             VtableTraitAlias(d) => &d.nested[..],
493         }
494     }
495
496     pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
497     where
498         F: FnMut(N) -> M,
499     {
500         match self {
501             VtableImpl(i) => VtableImpl(VtableImplData {
502                 impl_def_id: i.impl_def_id,
503                 substs: i.substs,
504                 nested: i.nested.into_iter().map(f).collect(),
505             }),
506             VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
507             VtableBuiltin(i) => {
508                 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
509             }
510             VtableObject(o) => VtableObject(VtableObjectData {
511                 upcast_trait_ref: o.upcast_trait_ref,
512                 vtable_base: o.vtable_base,
513                 nested: o.nested.into_iter().map(f).collect(),
514             }),
515             VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
516                 trait_def_id: d.trait_def_id,
517                 nested: d.nested.into_iter().map(f).collect(),
518             }),
519             VtableClosure(c) => VtableClosure(VtableClosureData {
520                 closure_def_id: c.closure_def_id,
521                 substs: c.substs,
522                 nested: c.nested.into_iter().map(f).collect(),
523             }),
524             VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
525                 generator_def_id: c.generator_def_id,
526                 substs: c.substs,
527                 nested: c.nested.into_iter().map(f).collect(),
528             }),
529             VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
530                 fn_ty: p.fn_ty,
531                 nested: p.nested.into_iter().map(f).collect(),
532             }),
533             VtableDiscriminantKind(VtableDiscriminantKindData) => {
534                 VtableDiscriminantKind(VtableDiscriminantKindData)
535             }
536             VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
537                 alias_def_id: d.alias_def_id,
538                 substs: d.substs,
539                 nested: d.nested.into_iter().map(f).collect(),
540             }),
541         }
542     }
543 }
544
545 /// Identifies a particular impl in the source, along with a set of
546 /// substitutions from the impl's type/lifetime parameters. The
547 /// `nested` vector corresponds to the nested obligations attached to
548 /// the impl's type parameters.
549 ///
550 /// The type parameter `N` indicates the type used for "nested
551 /// obligations" that are required by the impl. During type-check, this
552 /// is `Obligation`, as one might expect. During codegen, however, this
553 /// is `()`, because codegen only requires a shallow resolution of an
554 /// impl, and nested obligations are satisfied later.
555 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
556 pub struct VtableImplData<'tcx, N> {
557     pub impl_def_id: DefId,
558     pub substs: SubstsRef<'tcx>,
559     pub nested: Vec<N>,
560 }
561
562 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
563 pub struct VtableGeneratorData<'tcx, N> {
564     pub generator_def_id: DefId,
565     pub substs: SubstsRef<'tcx>,
566     /// Nested obligations. This can be non-empty if the generator
567     /// signature contains associated types.
568     pub nested: Vec<N>,
569 }
570
571 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
572 pub struct VtableClosureData<'tcx, N> {
573     pub closure_def_id: DefId,
574     pub substs: SubstsRef<'tcx>,
575     /// Nested obligations. This can be non-empty if the closure
576     /// signature contains associated types.
577     pub nested: Vec<N>,
578 }
579
580 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
581 pub struct VtableAutoImplData<N> {
582     pub trait_def_id: DefId,
583     pub nested: Vec<N>,
584 }
585
586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
587 pub struct VtableBuiltinData<N> {
588     pub nested: Vec<N>,
589 }
590
591 /// A vtable for some object-safe trait `Foo` automatically derived
592 /// for the object type `Foo`.
593 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
594 pub struct VtableObjectData<'tcx, N> {
595     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
596     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
597
598     /// The vtable is formed by concatenating together the method lists of
599     /// the base object trait and all supertraits; this is the start of
600     /// `upcast_trait_ref`'s methods in that vtable.
601     pub vtable_base: usize,
602
603     pub nested: Vec<N>,
604 }
605
606 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
607 pub struct VtableFnPointerData<'tcx, N> {
608     pub fn_ty: Ty<'tcx>,
609     pub nested: Vec<N>,
610 }
611
612 // FIXME(@lcnr): This should be  refactored and merged with other builtin vtables.
613 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
614 pub struct VtableDiscriminantKindData;
615
616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
617 pub struct VtableTraitAliasData<'tcx, N> {
618     pub alias_def_id: DefId,
619     pub substs: SubstsRef<'tcx>,
620     pub nested: Vec<N>,
621 }
622
623 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
624 pub enum ObjectSafetyViolation {
625     /// `Self: Sized` declared on the trait.
626     SizedSelf(SmallVec<[Span; 1]>),
627
628     /// Supertrait reference references `Self` an in illegal location
629     /// (e.g., `trait Foo : Bar<Self>`).
630     SupertraitSelf(SmallVec<[Span; 1]>),
631
632     /// Method has something illegal.
633     Method(Symbol, MethodViolationCode, Span),
634
635     /// Associated const.
636     AssocConst(Symbol, Span),
637 }
638
639 impl ObjectSafetyViolation {
640     pub fn error_msg(&self) -> Cow<'static, str> {
641         match *self {
642             ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
643             ObjectSafetyViolation::SupertraitSelf(ref spans) => {
644                 if spans.iter().any(|sp| *sp != DUMMY_SP) {
645                     "it uses `Self` as a type parameter in this".into()
646                 } else {
647                     "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
648                         .into()
649                 }
650             }
651             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
652                 format!("associated function `{}` has no `self` parameter", name).into()
653             }
654             ObjectSafetyViolation::Method(
655                 name,
656                 MethodViolationCode::ReferencesSelfInput(_),
657                 DUMMY_SP,
658             ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
659             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
660                 format!("method `{}` references the `Self` type in this parameter", name).into()
661             }
662             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
663                 format!("method `{}` references the `Self` type in its return type", name).into()
664             }
665             ObjectSafetyViolation::Method(
666                 name,
667                 MethodViolationCode::WhereClauseReferencesSelf,
668                 _,
669             ) => {
670                 format!("method `{}` references the `Self` type in its `where` clause", name).into()
671             }
672             ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
673                 format!("method `{}` has generic type parameters", name).into()
674             }
675             ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
676                 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
677             }
678             ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
679                 format!("it contains associated `const` `{}`", name).into()
680             }
681             ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
682         }
683     }
684
685     pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
686         Some(match *self {
687             ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
688                 return None;
689             }
690             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
691                 format!(
692                     "consider turning `{}` into a method by giving it a `&self` argument or \
693                      constraining it so it does not apply to trait objects",
694                     name
695                 ),
696                 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
697             ),
698             ObjectSafetyViolation::Method(
699                 name,
700                 MethodViolationCode::UndispatchableReceiver,
701                 span,
702             ) => (
703                 format!("consider changing method `{}`'s `self` parameter to be `&self`", name),
704                 Some(("&Self".to_string(), span)),
705             ),
706             ObjectSafetyViolation::AssocConst(name, _)
707             | ObjectSafetyViolation::Method(name, ..) => {
708                 (format!("consider moving `{}` to another trait", name), None)
709             }
710         })
711     }
712
713     pub fn spans(&self) -> SmallVec<[Span; 1]> {
714         // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
715         // diagnostics use a `note` instead of a `span_label`.
716         match self {
717             ObjectSafetyViolation::SupertraitSelf(spans)
718             | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
719             ObjectSafetyViolation::AssocConst(_, span)
720             | ObjectSafetyViolation::Method(_, _, span)
721                 if *span != DUMMY_SP =>
722             {
723                 smallvec![*span]
724             }
725             _ => smallvec![],
726         }
727     }
728 }
729
730 /// Reasons a method might not be object-safe.
731 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
732 pub enum MethodViolationCode {
733     /// e.g., `fn foo()`
734     StaticMethod(Option<(&'static str, Span)>),
735
736     /// e.g., `fn foo(&self, x: Self)`
737     ReferencesSelfInput(usize),
738
739     /// e.g., `fn foo(&self) -> Self`
740     ReferencesSelfOutput,
741
742     /// e.g., `fn foo(&self) where Self: Clone`
743     WhereClauseReferencesSelf,
744
745     /// e.g., `fn foo<A>()`
746     Generic,
747
748     /// the method's receiver (`self` argument) can't be dispatched on
749     UndispatchableReceiver,
750 }