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