]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/mod.rs
Rename rustc guide to rustc dev guide
[rust.git] / src / librustc / traits / mod.rs
1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
2 //!
3 //! [rustc dev guide]: https://rust-lang.github.io/rustc-dev-guide/traits/resolution.html
4
5 pub mod query;
6 pub mod select;
7 pub mod specialization_graph;
8 mod structural_impls;
9
10 use crate::mir::interpret::ErrorHandled;
11 use crate::ty::subst::SubstsRef;
12 use crate::ty::{self, AdtKind, List, Ty, TyCtxt};
13
14 use rustc_ast::ast;
15 use rustc_hir as hir;
16 use rustc_hir::def_id::DefId;
17 use rustc_span::{Span, DUMMY_SP};
18 use smallvec::SmallVec;
19
20 use std::borrow::Cow;
21 use std::fmt::Debug;
22 use std::rc::Rc;
23
24 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
25
26 pub use self::ObligationCauseCode::*;
27 pub use self::SelectionError::*;
28 pub use self::Vtable::*;
29
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)]
33 pub enum Reveal {
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
42     /// fail to compile:
43     ///
44     /// ```
45     /// trait Assoc {
46     ///     type Output;
47     /// }
48     ///
49     /// impl<T> Assoc for T {
50     ///     default type Output = bool;
51     /// }
52     ///
53     /// fn main() {
54     ///     let <() as Assoc>::Output = true;
55     /// }
56     /// ```
57     UserFacing,
58
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.
62     ///
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`.
70     All,
71 }
72
73 /// The reason why we incurred this obligation; used for error reporting.
74 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
75 pub struct ObligationCause<'tcx> {
76     pub span: Span,
77
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
83     /// information.
84     pub body_id: hir::HirId,
85
86     pub code: ObligationCauseCode<'tcx>,
87 }
88
89 impl<'tcx> ObligationCause<'tcx> {
90     #[inline]
91     pub fn new(
92         span: Span,
93         body_id: hir::HirId,
94         code: ObligationCauseCode<'tcx>,
95     ) -> ObligationCause<'tcx> {
96         ObligationCause { span, body_id, code }
97     }
98
99     pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
100         ObligationCause { span, body_id, code: MiscObligation }
101     }
102
103     pub fn dummy() -> ObligationCause<'tcx> {
104         ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
105     }
106
107     pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
108         match self.code {
109             ObligationCauseCode::CompareImplMethodObligation { .. }
110             | ObligationCauseCode::MainFunctionType
111             | ObligationCauseCode::StartFunctionType => tcx.sess.source_map().def_span(self.span),
112             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
113                 arm_span,
114                 ..
115             }) => arm_span,
116             _ => self.span,
117         }
118     }
119 }
120
121 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
122 pub enum ObligationCauseCode<'tcx> {
123     /// Not well classified or should be obvious from the span.
124     MiscObligation,
125
126     /// A slice or array is WF only if `T: Sized`.
127     SliceOrArrayElem,
128
129     /// A tuple is WF only if its middle elements are `Sized`.
130     TupleElem,
131
132     /// This is the trait reference from the given projection.
133     ProjectionWf(ty::ProjectionTy<'tcx>),
134
135     /// In an impl of trait `X` for type `Y`, type `Y` must
136     /// also implement all supertraits of `X`.
137     ItemObligation(DefId),
138
139     /// Like `ItemObligation`, but with extra detail on the source of the obligation.
140     BindingObligation(DefId, Span),
141
142     /// A type like `&'a T` is WF only if `T: 'a`.
143     ReferenceOutlivesReferent(Ty<'tcx>),
144
145     /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
146     ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
147
148     /// Obligation incurred due to an object cast.
149     ObjectCastObligation(/* Object type */ Ty<'tcx>),
150
151     /// Obligation incurred due to a coercion.
152     Coercion {
153         source: Ty<'tcx>,
154         target: Ty<'tcx>,
155     },
156
157     /// Various cases where expressions must be `Sized` / `Copy` / etc.
158     /// `L = X` implies that `L` is `Sized`.
159     AssignmentLhsSized,
160     /// `(x1, .., xn)` must be `Sized`.
161     TupleInitializerSized,
162     /// `S { ... }` must be `Sized`.
163     StructInitializerSized,
164     /// Type of each variable must be `Sized`.
165     VariableType(hir::HirId),
166     /// Argument type must be `Sized`.
167     SizedArgumentType,
168     /// Return type must be `Sized`.
169     SizedReturnType,
170     /// Yield type must be `Sized`.
171     SizedYieldType,
172     /// `[T, ..n]` implies that `T` must be `Copy`.
173     /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
174     RepeatVec(bool),
175
176     /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
177     FieldSized {
178         adt_kind: AdtKind,
179         last: bool,
180     },
181
182     /// Constant expressions must be sized.
183     ConstSized,
184
185     /// `static` items must have `Sync` type.
186     SharedStatic,
187
188     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
189
190     ImplDerivedObligation(DerivedObligationCause<'tcx>),
191
192     /// Error derived when matching traits/impls; see ObligationCause for more details
193     CompareImplMethodObligation {
194         item_name: ast::Name,
195         impl_item_def_id: DefId,
196         trait_item_def_id: DefId,
197     },
198
199     /// Error derived when matching traits/impls; see ObligationCause for more details
200     CompareImplTypeObligation {
201         item_name: ast::Name,
202         impl_item_def_id: DefId,
203         trait_item_def_id: DefId,
204     },
205
206     /// Checking that this expression can be assigned where it needs to be
207     // FIXME(eddyb) #11161 is the original Expr required?
208     ExprAssignable,
209
210     /// Computing common supertype in the arms of a match expression
211     MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
212
213     /// Type error arising from type checking a pattern against an expected type.
214     Pattern {
215         /// The span of the scrutinee or type expression which caused the `root_ty` type.
216         span: Option<Span>,
217         /// The root expected type induced by a scrutinee or type expression.
218         root_ty: Ty<'tcx>,
219         /// Whether the `Span` came from an expression or a type expression.
220         origin_expr: bool,
221     },
222
223     /// Constants in patterns must have `Structural` type.
224     ConstPatternStructural,
225
226     /// Computing common supertype in an if expression
227     IfExpression(Box<IfExpressionCause>),
228
229     /// Computing common supertype of an if expression with no else counter-part
230     IfExpressionWithNoElse,
231
232     /// `main` has wrong type
233     MainFunctionType,
234
235     /// `start` has wrong type
236     StartFunctionType,
237
238     /// Intrinsic has wrong type
239     IntrinsicType,
240
241     /// Method receiver
242     MethodReceiver,
243
244     /// `return` with no expression
245     ReturnNoExpression,
246
247     /// `return` with an expression
248     ReturnValue(hir::HirId),
249
250     /// Return type of this function
251     ReturnType,
252
253     /// Block implicit return
254     BlockTailExpression(hir::HirId),
255
256     /// #[feature(trivial_bounds)] is not enabled
257     TrivialBound,
258
259     AssocTypeBound(Box<AssocTypeBoundData>),
260 }
261
262 impl ObligationCauseCode<'_> {
263     // Return the base obligation, ignoring derived obligations.
264     pub fn peel_derives(&self) -> &Self {
265         let mut base_cause = self;
266         while let BuiltinDerivedObligation(cause) | ImplDerivedObligation(cause) = base_cause {
267             base_cause = &cause.parent_code;
268         }
269         base_cause
270     }
271 }
272
273 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
274 pub struct AssocTypeBoundData {
275     pub impl_span: Option<Span>,
276     pub original: Span,
277     pub bounds: Vec<Span>,
278 }
279
280 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
281 #[cfg(target_arch = "x86_64")]
282 static_assert_size!(ObligationCauseCode<'_>, 32);
283
284 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
285 pub struct MatchExpressionArmCause<'tcx> {
286     pub arm_span: Span,
287     pub source: hir::MatchSource,
288     pub prior_arms: Vec<Span>,
289     pub last_ty: Ty<'tcx>,
290     pub scrut_hir_id: hir::HirId,
291 }
292
293 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
294 pub struct IfExpressionCause {
295     pub then: Span,
296     pub outer: Option<Span>,
297     pub semicolon: Option<Span>,
298 }
299
300 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
301 pub struct DerivedObligationCause<'tcx> {
302     /// The trait reference of the parent obligation that led to the
303     /// current obligation. Note that only trait obligations lead to
304     /// derived obligations, so we just store the trait reference here
305     /// directly.
306     pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
307
308     /// The parent trait had this cause.
309     pub parent_code: Rc<ObligationCauseCode<'tcx>>,
310 }
311
312 /// The following types:
313 /// * `WhereClause`,
314 /// * `WellFormed`,
315 /// * `FromEnv`,
316 /// * `DomainGoal`,
317 /// * `Goal`,
318 /// * `Clause`,
319 /// * `Environment`,
320 /// * `InEnvironment`,
321 /// are used for representing the trait system in the form of
322 /// logic programming clauses. They are part of the interface
323 /// for the chalk SLG solver.
324 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
325 pub enum WhereClause<'tcx> {
326     Implemented(ty::TraitPredicate<'tcx>),
327     ProjectionEq(ty::ProjectionPredicate<'tcx>),
328     RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
329     TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
330 }
331
332 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
333 pub enum WellFormed<'tcx> {
334     Trait(ty::TraitPredicate<'tcx>),
335     Ty(Ty<'tcx>),
336 }
337
338 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
339 pub enum FromEnv<'tcx> {
340     Trait(ty::TraitPredicate<'tcx>),
341     Ty(Ty<'tcx>),
342 }
343
344 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
345 pub enum DomainGoal<'tcx> {
346     Holds(WhereClause<'tcx>),
347     WellFormed(WellFormed<'tcx>),
348     FromEnv(FromEnv<'tcx>),
349     Normalize(ty::ProjectionPredicate<'tcx>),
350 }
351
352 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
353
354 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
355 pub enum QuantifierKind {
356     Universal,
357     Existential,
358 }
359
360 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
361 pub enum GoalKind<'tcx> {
362     Implies(Clauses<'tcx>, Goal<'tcx>),
363     And(Goal<'tcx>, Goal<'tcx>),
364     Not(Goal<'tcx>),
365     DomainGoal(DomainGoal<'tcx>),
366     Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
367     Subtype(Ty<'tcx>, Ty<'tcx>),
368     CannotProve,
369 }
370
371 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
372
373 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
374
375 impl<'tcx> DomainGoal<'tcx> {
376     pub fn into_goal(self) -> GoalKind<'tcx> {
377         GoalKind::DomainGoal(self)
378     }
379
380     pub fn into_program_clause(self) -> ProgramClause<'tcx> {
381         ProgramClause {
382             goal: self,
383             hypotheses: ty::List::empty(),
384             category: ProgramClauseCategory::Other,
385         }
386     }
387 }
388
389 impl<'tcx> GoalKind<'tcx> {
390     pub fn from_poly_domain_goal(
391         domain_goal: PolyDomainGoal<'tcx>,
392         tcx: TyCtxt<'tcx>,
393     ) -> GoalKind<'tcx> {
394         match domain_goal.no_bound_vars() {
395             Some(p) => p.into_goal(),
396             None => GoalKind::Quantified(
397                 QuantifierKind::Universal,
398                 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())),
399             ),
400         }
401     }
402 }
403
404 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
405 /// Harrop Formulas".
406 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
407 pub enum Clause<'tcx> {
408     Implies(ProgramClause<'tcx>),
409     ForAll(ty::Binder<ProgramClause<'tcx>>),
410 }
411
412 impl Clause<'tcx> {
413     pub fn category(self) -> ProgramClauseCategory {
414         match self {
415             Clause::Implies(clause) => clause.category,
416             Clause::ForAll(clause) => clause.skip_binder().category,
417         }
418     }
419 }
420
421 /// Multiple clauses.
422 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
423
424 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
425 /// that the domain goal `D` is true if `G1...Gn` are provable. This
426 /// is equivalent to the implication `G1..Gn => D`; we usually write
427 /// it with the reverse implication operator `:-` to emphasize the way
428 /// that programs are actually solved (via backchaining, which starts
429 /// with the goal to solve and proceeds from there).
430 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
431 pub struct ProgramClause<'tcx> {
432     /// This goal will be considered true ...
433     pub goal: DomainGoal<'tcx>,
434
435     /// ... if we can prove these hypotheses (there may be no hypotheses at all):
436     pub hypotheses: Goals<'tcx>,
437
438     /// Useful for filtering clauses.
439     pub category: ProgramClauseCategory,
440 }
441
442 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
443 pub enum ProgramClauseCategory {
444     ImpliedBound,
445     WellFormed,
446     Other,
447 }
448
449 /// A set of clauses that we assume to be true.
450 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
451 pub struct Environment<'tcx> {
452     pub clauses: Clauses<'tcx>,
453 }
454
455 impl Environment<'tcx> {
456     pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
457         InEnvironment { environment: self, goal }
458     }
459 }
460
461 /// Something (usually a goal), along with an environment.
462 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
463 pub struct InEnvironment<'tcx, G> {
464     pub environment: Environment<'tcx>,
465     pub goal: G,
466 }
467
468 #[derive(Clone, Debug, TypeFoldable)]
469 pub enum SelectionError<'tcx> {
470     Unimplemented,
471     OutputTypeParameterMismatch(
472         ty::PolyTraitRef<'tcx>,
473         ty::PolyTraitRef<'tcx>,
474         ty::error::TypeError<'tcx>,
475     ),
476     TraitNotObjectSafe(DefId),
477     ConstEvalFailure(ErrorHandled),
478     Overflow,
479 }
480
481 /// When performing resolution, it is typically the case that there
482 /// can be one of three outcomes:
483 ///
484 /// - `Ok(Some(r))`: success occurred with result `r`
485 /// - `Ok(None)`: could not definitely determine anything, usually due
486 ///   to inconclusive type inference.
487 /// - `Err(e)`: error `e` occurred
488 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
489
490 /// Given the successful resolution of an obligation, the `Vtable`
491 /// indicates where the vtable comes from. Note that while we call this
492 /// a "vtable", it does not necessarily indicate dynamic dispatch at
493 /// runtime. `Vtable` instances just tell the compiler where to find
494 /// methods, but in generic code those methods are typically statically
495 /// dispatched -- only when an object is constructed is a `Vtable`
496 /// instance reified into an actual vtable.
497 ///
498 /// For example, the vtable may be tied to a specific impl (case A),
499 /// or it may be relative to some bound that is in scope (case B).
500 ///
501 /// ```
502 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
503 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
504 /// impl Clone for int { ... }             // Impl_3
505 ///
506 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
507 ///                 param: T,
508 ///                 mixed: Option<T>) {
509 ///
510 ///    // Case A: Vtable points at a specific impl. Only possible when
511 ///    // type is concretely known. If the impl itself has bounded
512 ///    // type parameters, Vtable will carry resolutions for those as well:
513 ///    concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
514 ///
515 ///    // Case B: Vtable must be provided by caller. This applies when
516 ///    // type is a type parameter.
517 ///    param.clone();    // VtableParam
518 ///
519 ///    // Case C: A mix of cases A and B.
520 ///    mixed.clone();    // Vtable(Impl_1, [VtableParam])
521 /// }
522 /// ```
523 ///
524 /// ### The type parameter `N`
525 ///
526 /// See explanation on `VtableImplData`.
527 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
528 pub enum Vtable<'tcx, N> {
529     /// Vtable identifying a particular impl.
530     VtableImpl(VtableImplData<'tcx, N>),
531
532     /// Vtable for auto trait implementations.
533     /// This carries the information and nested obligations with regards
534     /// to an auto implementation for a trait `Trait`. The nested obligations
535     /// ensure the trait implementation holds for all the constituent types.
536     VtableAutoImpl(VtableAutoImplData<N>),
537
538     /// Successful resolution to an obligation provided by the caller
539     /// for some type parameter. The `Vec<N>` represents the
540     /// obligations incurred from normalizing the where-clause (if
541     /// any).
542     VtableParam(Vec<N>),
543
544     /// Virtual calls through an object.
545     VtableObject(VtableObjectData<'tcx, N>),
546
547     /// Successful resolution for a builtin trait.
548     VtableBuiltin(VtableBuiltinData<N>),
549
550     /// Vtable automatically generated for a closure. The `DefId` is the ID
551     /// of the closure expression. This is a `VtableImpl` in spirit, but the
552     /// impl is generated by the compiler and does not appear in the source.
553     VtableClosure(VtableClosureData<'tcx, N>),
554
555     /// Same as above, but for a function pointer type with the given signature.
556     VtableFnPointer(VtableFnPointerData<'tcx, N>),
557
558     /// Vtable automatically generated for a generator.
559     VtableGenerator(VtableGeneratorData<'tcx, N>),
560
561     /// Vtable for a trait alias.
562     VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
563 }
564
565 impl<'tcx, N> Vtable<'tcx, N> {
566     pub fn nested_obligations(self) -> Vec<N> {
567         match self {
568             VtableImpl(i) => i.nested,
569             VtableParam(n) => n,
570             VtableBuiltin(i) => i.nested,
571             VtableAutoImpl(d) => d.nested,
572             VtableClosure(c) => c.nested,
573             VtableGenerator(c) => c.nested,
574             VtableObject(d) => d.nested,
575             VtableFnPointer(d) => d.nested,
576             VtableTraitAlias(d) => d.nested,
577         }
578     }
579
580     pub fn borrow_nested_obligations(&self) -> &[N] {
581         match &self {
582             VtableImpl(i) => &i.nested[..],
583             VtableParam(n) => &n[..],
584             VtableBuiltin(i) => &i.nested[..],
585             VtableAutoImpl(d) => &d.nested[..],
586             VtableClosure(c) => &c.nested[..],
587             VtableGenerator(c) => &c.nested[..],
588             VtableObject(d) => &d.nested[..],
589             VtableFnPointer(d) => &d.nested[..],
590             VtableTraitAlias(d) => &d.nested[..],
591         }
592     }
593
594     pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
595     where
596         F: FnMut(N) -> M,
597     {
598         match self {
599             VtableImpl(i) => VtableImpl(VtableImplData {
600                 impl_def_id: i.impl_def_id,
601                 substs: i.substs,
602                 nested: i.nested.into_iter().map(f).collect(),
603             }),
604             VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
605             VtableBuiltin(i) => {
606                 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
607             }
608             VtableObject(o) => VtableObject(VtableObjectData {
609                 upcast_trait_ref: o.upcast_trait_ref,
610                 vtable_base: o.vtable_base,
611                 nested: o.nested.into_iter().map(f).collect(),
612             }),
613             VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
614                 trait_def_id: d.trait_def_id,
615                 nested: d.nested.into_iter().map(f).collect(),
616             }),
617             VtableClosure(c) => VtableClosure(VtableClosureData {
618                 closure_def_id: c.closure_def_id,
619                 substs: c.substs,
620                 nested: c.nested.into_iter().map(f).collect(),
621             }),
622             VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
623                 generator_def_id: c.generator_def_id,
624                 substs: c.substs,
625                 nested: c.nested.into_iter().map(f).collect(),
626             }),
627             VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
628                 fn_ty: p.fn_ty,
629                 nested: p.nested.into_iter().map(f).collect(),
630             }),
631             VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
632                 alias_def_id: d.alias_def_id,
633                 substs: d.substs,
634                 nested: d.nested.into_iter().map(f).collect(),
635             }),
636         }
637     }
638 }
639
640 /// Identifies a particular impl in the source, along with a set of
641 /// substitutions from the impl's type/lifetime parameters. The
642 /// `nested` vector corresponds to the nested obligations attached to
643 /// the impl's type parameters.
644 ///
645 /// The type parameter `N` indicates the type used for "nested
646 /// obligations" that are required by the impl. During type-check, this
647 /// is `Obligation`, as one might expect. During codegen, however, this
648 /// is `()`, because codegen only requires a shallow resolution of an
649 /// impl, and nested obligations are satisfied later.
650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
651 pub struct VtableImplData<'tcx, N> {
652     pub impl_def_id: DefId,
653     pub substs: SubstsRef<'tcx>,
654     pub nested: Vec<N>,
655 }
656
657 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
658 pub struct VtableGeneratorData<'tcx, N> {
659     pub generator_def_id: DefId,
660     pub substs: SubstsRef<'tcx>,
661     /// Nested obligations. This can be non-empty if the generator
662     /// signature contains associated types.
663     pub nested: Vec<N>,
664 }
665
666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
667 pub struct VtableClosureData<'tcx, N> {
668     pub closure_def_id: DefId,
669     pub substs: SubstsRef<'tcx>,
670     /// Nested obligations. This can be non-empty if the closure
671     /// signature contains associated types.
672     pub nested: Vec<N>,
673 }
674
675 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
676 pub struct VtableAutoImplData<N> {
677     pub trait_def_id: DefId,
678     pub nested: Vec<N>,
679 }
680
681 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
682 pub struct VtableBuiltinData<N> {
683     pub nested: Vec<N>,
684 }
685
686 /// A vtable for some object-safe trait `Foo` automatically derived
687 /// for the object type `Foo`.
688 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
689 pub struct VtableObjectData<'tcx, N> {
690     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
691     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
692
693     /// The vtable is formed by concatenating together the method lists of
694     /// the base object trait and all supertraits; this is the start of
695     /// `upcast_trait_ref`'s methods in that vtable.
696     pub vtable_base: usize,
697
698     pub nested: Vec<N>,
699 }
700
701 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
702 pub struct VtableFnPointerData<'tcx, N> {
703     pub fn_ty: Ty<'tcx>,
704     pub nested: Vec<N>,
705 }
706
707 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
708 pub struct VtableTraitAliasData<'tcx, N> {
709     pub alias_def_id: DefId,
710     pub substs: SubstsRef<'tcx>,
711     pub nested: Vec<N>,
712 }
713
714 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
715 pub enum ObjectSafetyViolation {
716     /// `Self: Sized` declared on the trait.
717     SizedSelf(SmallVec<[Span; 1]>),
718
719     /// Supertrait reference references `Self` an in illegal location
720     /// (e.g., `trait Foo : Bar<Self>`).
721     SupertraitSelf(SmallVec<[Span; 1]>),
722
723     /// Method has something illegal.
724     Method(ast::Name, MethodViolationCode, Span),
725
726     /// Associated const.
727     AssocConst(ast::Name, Span),
728 }
729
730 impl ObjectSafetyViolation {
731     pub fn error_msg(&self) -> Cow<'static, str> {
732         match *self {
733             ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
734             ObjectSafetyViolation::SupertraitSelf(ref spans) => {
735                 if spans.iter().any(|sp| *sp != DUMMY_SP) {
736                     "it uses `Self` as a type parameter in this".into()
737                 } else {
738                     "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
739                         .into()
740                 }
741             }
742             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
743                 format!("associated function `{}` has no `self` parameter", name).into()
744             }
745             ObjectSafetyViolation::Method(
746                 name,
747                 MethodViolationCode::ReferencesSelfInput(_),
748                 DUMMY_SP,
749             ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
750             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
751                 format!("method `{}` references the `Self` type in this parameter", name).into()
752             }
753             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
754                 format!("method `{}` references the `Self` type in its return type", name).into()
755             }
756             ObjectSafetyViolation::Method(
757                 name,
758                 MethodViolationCode::WhereClauseReferencesSelf,
759                 _,
760             ) => {
761                 format!("method `{}` references the `Self` type in its `where` clause", name).into()
762             }
763             ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
764                 format!("method `{}` has generic type parameters", name).into()
765             }
766             ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
767                 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
768             }
769             ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
770                 format!("it contains associated `const` `{}`", name).into()
771             }
772             ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
773         }
774     }
775
776     pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
777         Some(match *self {
778             ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
779                 return None;
780             }
781             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
782                 format!(
783                     "consider turning `{}` into a method by giving it a `&self` argument or \
784                      constraining it so it does not apply to trait objects",
785                     name
786                 ),
787                 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
788             ),
789             ObjectSafetyViolation::Method(
790                 name,
791                 MethodViolationCode::UndispatchableReceiver,
792                 span,
793             ) => (
794                 format!("consider changing method `{}`'s `self` parameter to be `&self`", name),
795                 Some(("&Self".to_string(), span)),
796             ),
797             ObjectSafetyViolation::AssocConst(name, _)
798             | ObjectSafetyViolation::Method(name, ..) => {
799                 (format!("consider moving `{}` to another trait", name), None)
800             }
801         })
802     }
803
804     pub fn spans(&self) -> SmallVec<[Span; 1]> {
805         // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
806         // diagnostics use a `note` instead of a `span_label`.
807         match self {
808             ObjectSafetyViolation::SupertraitSelf(spans)
809             | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
810             ObjectSafetyViolation::AssocConst(_, span)
811             | ObjectSafetyViolation::Method(_, _, span)
812                 if *span != DUMMY_SP =>
813             {
814                 smallvec![*span]
815             }
816             _ => smallvec![],
817         }
818     }
819 }
820
821 /// Reasons a method might not be object-safe.
822 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
823 pub enum MethodViolationCode {
824     /// e.g., `fn foo()`
825     StaticMethod(Option<(&'static str, Span)>),
826
827     /// e.g., `fn foo(&self, x: Self)`
828     ReferencesSelfInput(usize),
829
830     /// e.g., `fn foo(&self) -> Self`
831     ReferencesSelfOutput,
832
833     /// e.g., `fn foo(&self) where Self: Clone`
834     WhereClauseReferencesSelf,
835
836     /// e.g., `fn foo<A>()`
837     Generic,
838
839     /// the method's receiver (`self` argument) can't be dispatched on
840     UndispatchableReceiver,
841 }