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