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