]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/mod.rs
Rollup merge of #67543 - JohnTitor:regression-tests, r=Centril
[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 #[allow(dead_code)]
6 pub mod auto_trait;
7 mod chalk_fulfill;
8 mod coherence;
9 pub mod error_reporting;
10 mod engine;
11 mod fulfill;
12 mod project;
13 mod object_safety;
14 mod on_unimplemented;
15 mod select;
16 mod specialize;
17 mod structural_impls;
18 pub mod codegen;
19 mod util;
20 pub mod query;
21
22 use chalk_engine;
23 use crate::hir;
24 use crate::hir::def_id::DefId;
25 use crate::infer::{InferCtxt, SuppressRegionErrors};
26 use crate::infer::outlives::env::OutlivesEnvironment;
27 use crate::middle::region;
28 use crate::mir::interpret::ErrorHandled;
29 use rustc_macros::HashStable;
30 use syntax::ast;
31 use syntax_pos::{Span, DUMMY_SP};
32 use crate::ty::subst::{InternalSubsts, SubstsRef};
33 use crate::ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
34 use crate::ty::error::{ExpectedFound, TypeError};
35 use crate::ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
36 use crate::util::common::ErrorReported;
37
38 use std::fmt::Debug;
39 use std::rc::Rc;
40
41 pub use self::SelectionError::*;
42 pub use self::FulfillmentErrorCode::*;
43 pub use self::Vtable::*;
44 pub use self::ObligationCauseCode::*;
45
46 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
47 pub use self::coherence::{OrphanCheckErr, OverlapResult};
48 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
49 pub use self::project::MismatchedProjectionTypes;
50 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
51 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
52 pub use self::object_safety::ObjectSafetyViolation;
53 pub use self::object_safety::MethodViolationCode;
54 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
55 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
56 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
57 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
58 pub use self::specialize::find_associated_item;
59 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
60 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
61 pub use self::engine::{TraitEngine, TraitEngineExt};
62 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
63 pub use self::util::{
64     supertraits, supertrait_def_ids, transitive_bounds, Supertraits, SupertraitDefIds,
65 };
66 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
67
68 pub use self::chalk_fulfill::{
69     CanonicalGoal as ChalkCanonicalGoal,
70     FulfillmentContext as ChalkFulfillmentContext
71 };
72
73 pub use self::ObligationCauseCode::*;
74 pub use self::FulfillmentErrorCode::*;
75 pub use self::SelectionError::*;
76 pub use self::Vtable::*;
77
78 /// Whether to enable bug compatibility with issue #43355.
79 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
80 pub enum IntercrateMode {
81     Issue43355,
82     Fixed
83 }
84
85 /// The mode that trait queries run in.
86 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
87 pub enum TraitQueryMode {
88     // Standard/un-canonicalized queries get accurate
89     // spans etc. passed in and hence can do reasonable
90     // error reporting on their own.
91     Standard,
92     // Canonicalized queries get dummy spans and hence
93     // must generally propagate errors to
94     // pre-canonicalization callsites.
95     Canonical,
96 }
97
98 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
99 /// which the vtable must be found. The process of finding a vtable is
100 /// called "resolving" the `Obligation`. This process consists of
101 /// either identifying an `impl` (e.g., `impl Eq for int`) that
102 /// provides the required vtable, or else finding a bound that is in
103 /// scope. The eventual result is usually a `Selection` (defined below).
104 #[derive(Clone, PartialEq, Eq, Hash)]
105 pub struct Obligation<'tcx, T> {
106     /// The reason we have to prove this thing.
107     pub cause: ObligationCause<'tcx>,
108
109     /// The environment in which we should prove this thing.
110     pub param_env: ty::ParamEnv<'tcx>,
111
112     /// The thing we are trying to prove.
113     pub predicate: T,
114
115     /// If we started proving this as a result of trying to prove
116     /// something else, track the total depth to ensure termination.
117     /// If this goes over a certain threshold, we abort compilation --
118     /// in such cases, we can not say whether or not the predicate
119     /// holds for certain. Stupid halting problem; such a drag.
120     pub recursion_depth: usize,
121 }
122
123 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
124 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
125
126 // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
127 #[cfg(target_arch = "x86_64")]
128 static_assert_size!(PredicateObligation<'_>, 112);
129
130 /// The reason why we incurred this obligation; used for error reporting.
131 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
132 pub struct ObligationCause<'tcx> {
133     pub span: Span,
134
135     /// The ID of the fn body that triggered this obligation. This is
136     /// used for region obligations to determine the precise
137     /// environment in which the region obligation should be evaluated
138     /// (in particular, closures can add new assumptions). See the
139     /// field `region_obligations` of the `FulfillmentContext` for more
140     /// information.
141     pub body_id: hir::HirId,
142
143     pub code: ObligationCauseCode<'tcx>
144 }
145
146 impl<'tcx> ObligationCause<'tcx> {
147     pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
148         match self.code {
149             ObligationCauseCode::CompareImplMethodObligation { .. } |
150             ObligationCauseCode::MainFunctionType |
151             ObligationCauseCode::StartFunctionType => {
152                 tcx.sess.source_map().def_span(self.span)
153             }
154             ObligationCauseCode::MatchExpressionArm(
155                 box MatchExpressionArmCause { arm_span, .. }) => arm_span,
156             _ => self.span,
157         }
158     }
159 }
160
161 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
162 pub enum ObligationCauseCode<'tcx> {
163     /// Not well classified or should be obvious from the span.
164     MiscObligation,
165
166     /// A slice or array is WF only if `T: Sized`.
167     SliceOrArrayElem,
168
169     /// A tuple is WF only if its middle elements are `Sized`.
170     TupleElem,
171
172     /// This is the trait reference from the given projection.
173     ProjectionWf(ty::ProjectionTy<'tcx>),
174
175     /// In an impl of trait `X` for type `Y`, type `Y` must
176     /// also implement all supertraits of `X`.
177     ItemObligation(DefId),
178
179     /// Like `ItemObligation`, but with extra detail on the source of the obligation.
180     BindingObligation(DefId, Span),
181
182     /// A type like `&'a T` is WF only if `T: 'a`.
183     ReferenceOutlivesReferent(Ty<'tcx>),
184
185     /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
186     ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
187
188     /// Obligation incurred due to an object cast.
189     ObjectCastObligation(/* Object type */ Ty<'tcx>),
190
191     /// Obligation incurred due to a coercion.
192     Coercion { source: Ty<'tcx>, target: Ty<'tcx> },
193
194     /// Various cases where expressions must be `Sized` / `Copy` / etc.
195     /// `L = X` implies that `L` is `Sized`.
196     AssignmentLhsSized,
197     /// `(x1, .., xn)` must be `Sized`.
198     TupleInitializerSized,
199     /// `S { ... }` must be `Sized`.
200     StructInitializerSized,
201     /// Type of each variable must be `Sized`.
202     VariableType(hir::HirId),
203     /// Argument type must be `Sized`.
204     SizedArgumentType,
205     /// Return type must be `Sized`.
206     SizedReturnType,
207     /// Yield type must be `Sized`.
208     SizedYieldType,
209     /// `[T, ..n]` implies that `T` must be `Copy`.
210     /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
211     RepeatVec(bool),
212
213     /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
214     FieldSized { adt_kind: AdtKind, last: bool },
215
216     /// Constant expressions must be sized.
217     ConstSized,
218
219     /// `static` items must have `Sync` type.
220     SharedStatic,
221
222     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
223
224     ImplDerivedObligation(DerivedObligationCause<'tcx>),
225
226     /// Error derived when matching traits/impls; see ObligationCause for more details
227     CompareImplMethodObligation {
228         item_name: ast::Name,
229         impl_item_def_id: DefId,
230         trait_item_def_id: DefId,
231     },
232
233     /// Error derived when matching traits/impls; see ObligationCause for more details
234     CompareImplTypeObligation {
235         item_name: ast::Name,
236         impl_item_def_id: DefId,
237         trait_item_def_id: DefId,
238     },
239
240     /// Checking that this expression can be assigned where it needs to be
241     // FIXME(eddyb) #11161 is the original Expr required?
242     ExprAssignable,
243
244     /// Computing common supertype in the arms of a match expression
245     MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
246
247     /// Computing common supertype in the pattern guard for the arms of a match expression
248     MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
249
250     /// Constants in patterns must have `Structural` type.
251     ConstPatternStructural,
252
253     /// Computing common supertype in an if expression
254     IfExpression(Box<IfExpressionCause>),
255
256     /// Computing common supertype of an if expression with no else counter-part
257     IfExpressionWithNoElse,
258
259     /// `main` has wrong type
260     MainFunctionType,
261
262     /// `start` has wrong type
263     StartFunctionType,
264
265     /// Intrinsic has wrong type
266     IntrinsicType,
267
268     /// Method receiver
269     MethodReceiver,
270
271     /// `return` with no expression
272     ReturnNoExpression,
273
274     /// `return` with an expression
275     ReturnValue(hir::HirId),
276
277     /// Return type of this function
278     ReturnType,
279
280     /// Block implicit return
281     BlockTailExpression(hir::HirId),
282
283     /// #[feature(trivial_bounds)] is not enabled
284     TrivialBound,
285
286     AssocTypeBound(Box<AssocTypeBoundData>),
287 }
288
289 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
290 pub struct AssocTypeBoundData {
291     pub impl_span: Option<Span>,
292     pub original: Span,
293     pub bounds: Vec<Span>,
294 }
295
296 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
297 #[cfg(target_arch = "x86_64")]
298 static_assert_size!(ObligationCauseCode<'_>, 32);
299
300 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
301 pub struct MatchExpressionArmCause<'tcx> {
302     pub arm_span: Span,
303     pub source: hir::MatchSource,
304     pub prior_arms: Vec<Span>,
305     pub last_ty: Ty<'tcx>,
306     pub discrim_hir_id: hir::HirId,
307 }
308
309 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
310 pub struct IfExpressionCause {
311     pub then: Span,
312     pub outer: Option<Span>,
313     pub semicolon: Option<Span>,
314 }
315
316 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
317 pub struct DerivedObligationCause<'tcx> {
318     /// The trait reference of the parent obligation that led to the
319     /// current obligation. Note that only trait obligations lead to
320     /// derived obligations, so we just store the trait reference here
321     /// directly.
322     parent_trait_ref: ty::PolyTraitRef<'tcx>,
323
324     /// The parent trait had this cause.
325     parent_code: Rc<ObligationCauseCode<'tcx>>
326 }
327
328 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
329 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
330 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
331
332 /// The following types:
333 /// * `WhereClause`,
334 /// * `WellFormed`,
335 /// * `FromEnv`,
336 /// * `DomainGoal`,
337 /// * `Goal`,
338 /// * `Clause`,
339 /// * `Environment`,
340 /// * `InEnvironment`,
341 /// are used for representing the trait system in the form of
342 /// logic programming clauses. They are part of the interface
343 /// for the chalk SLG solver.
344 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
345 pub enum WhereClause<'tcx> {
346     Implemented(ty::TraitPredicate<'tcx>),
347     ProjectionEq(ty::ProjectionPredicate<'tcx>),
348     RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
349     TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
350 }
351
352 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
353 pub enum WellFormed<'tcx> {
354     Trait(ty::TraitPredicate<'tcx>),
355     Ty(Ty<'tcx>),
356 }
357
358 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
359 pub enum FromEnv<'tcx> {
360     Trait(ty::TraitPredicate<'tcx>),
361     Ty(Ty<'tcx>),
362 }
363
364 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
365 pub enum DomainGoal<'tcx> {
366     Holds(WhereClause<'tcx>),
367     WellFormed(WellFormed<'tcx>),
368     FromEnv(FromEnv<'tcx>),
369     Normalize(ty::ProjectionPredicate<'tcx>),
370 }
371
372 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
373
374 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
375 pub enum QuantifierKind {
376     Universal,
377     Existential,
378 }
379
380 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
381 pub enum GoalKind<'tcx> {
382     Implies(Clauses<'tcx>, Goal<'tcx>),
383     And(Goal<'tcx>, Goal<'tcx>),
384     Not(Goal<'tcx>),
385     DomainGoal(DomainGoal<'tcx>),
386     Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
387     Subtype(Ty<'tcx>, Ty<'tcx>),
388     CannotProve,
389 }
390
391 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
392
393 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
394
395 impl<'tcx> DomainGoal<'tcx> {
396     pub fn into_goal(self) -> GoalKind<'tcx> {
397         GoalKind::DomainGoal(self)
398     }
399
400     pub fn into_program_clause(self) -> ProgramClause<'tcx> {
401         ProgramClause {
402             goal: self,
403             hypotheses: ty::List::empty(),
404             category: ProgramClauseCategory::Other,
405         }
406     }
407 }
408
409 impl<'tcx> GoalKind<'tcx> {
410     pub fn from_poly_domain_goal(
411         domain_goal: PolyDomainGoal<'tcx>,
412         tcx: TyCtxt<'tcx>,
413     ) -> GoalKind<'tcx> {
414         match domain_goal.no_bound_vars() {
415             Some(p) => p.into_goal(),
416             None => GoalKind::Quantified(
417                 QuantifierKind::Universal,
418                 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
419             ),
420         }
421     }
422 }
423
424 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
425 /// Harrop Formulas".
426 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
427 pub enum Clause<'tcx> {
428     Implies(ProgramClause<'tcx>),
429     ForAll(ty::Binder<ProgramClause<'tcx>>),
430 }
431
432 impl Clause<'tcx> {
433     pub fn category(self) -> ProgramClauseCategory {
434         match self {
435             Clause::Implies(clause) => clause.category,
436             Clause::ForAll(clause) => clause.skip_binder().category,
437         }
438     }
439 }
440
441 /// Multiple clauses.
442 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
443
444 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
445 /// that the domain goal `D` is true if `G1...Gn` are provable. This
446 /// is equivalent to the implication `G1..Gn => D`; we usually write
447 /// it with the reverse implication operator `:-` to emphasize the way
448 /// that programs are actually solved (via backchaining, which starts
449 /// with the goal to solve and proceeds from there).
450 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
451 pub struct ProgramClause<'tcx> {
452     /// This goal will be considered true ...
453     pub goal: DomainGoal<'tcx>,
454
455     /// ... if we can prove these hypotheses (there may be no hypotheses at all):
456     pub hypotheses: Goals<'tcx>,
457
458     /// Useful for filtering clauses.
459     pub category: ProgramClauseCategory,
460 }
461
462 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
463 pub enum ProgramClauseCategory {
464     ImpliedBound,
465     WellFormed,
466     Other,
467 }
468
469 /// A set of clauses that we assume to be true.
470 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
471 pub struct Environment<'tcx> {
472     pub clauses: Clauses<'tcx>,
473 }
474
475 impl Environment<'tcx> {
476     pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
477         InEnvironment {
478             environment: self,
479             goal,
480         }
481     }
482 }
483
484 /// Something (usually a goal), along with an environment.
485 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
486 pub struct InEnvironment<'tcx, G> {
487     pub environment: Environment<'tcx>,
488     pub goal: G,
489 }
490
491 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
492
493 #[derive(Clone,Debug,TypeFoldable)]
494 pub enum SelectionError<'tcx> {
495     Unimplemented,
496     OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
497                                 ty::PolyTraitRef<'tcx>,
498                                 ty::error::TypeError<'tcx>),
499     TraitNotObjectSafe(DefId),
500     ConstEvalFailure(ErrorHandled),
501     Overflow,
502 }
503
504 pub struct FulfillmentError<'tcx> {
505     pub obligation: PredicateObligation<'tcx>,
506     pub code: FulfillmentErrorCode<'tcx>,
507     /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
508     /// obligation error caused by a call argument. When this is the case, we also signal that in
509     /// this field to ensure accuracy of suggestions.
510     pub points_at_arg_span: bool,
511 }
512
513 #[derive(Clone)]
514 pub enum FulfillmentErrorCode<'tcx> {
515     CodeSelectionError(SelectionError<'tcx>),
516     CodeProjectionError(MismatchedProjectionTypes<'tcx>),
517     CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
518                      TypeError<'tcx>), // always comes from a SubtypePredicate
519     CodeAmbiguity,
520 }
521
522 /// When performing resolution, it is typically the case that there
523 /// can be one of three outcomes:
524 ///
525 /// - `Ok(Some(r))`: success occurred with result `r`
526 /// - `Ok(None)`: could not definitely determine anything, usually due
527 ///   to inconclusive type inference.
528 /// - `Err(e)`: error `e` occurred
529 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
530
531 /// Given the successful resolution of an obligation, the `Vtable`
532 /// indicates where the vtable comes from. Note that while we call this
533 /// a "vtable", it does not necessarily indicate dynamic dispatch at
534 /// runtime. `Vtable` instances just tell the compiler where to find
535 /// methods, but in generic code those methods are typically statically
536 /// dispatched -- only when an object is constructed is a `Vtable`
537 /// instance reified into an actual vtable.
538 ///
539 /// For example, the vtable may be tied to a specific impl (case A),
540 /// or it may be relative to some bound that is in scope (case B).
541 ///
542 /// ```
543 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
544 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
545 /// impl Clone for int { ... }             // Impl_3
546 ///
547 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
548 ///                 param: T,
549 ///                 mixed: Option<T>) {
550 ///
551 ///    // Case A: Vtable points at a specific impl. Only possible when
552 ///    // type is concretely known. If the impl itself has bounded
553 ///    // type parameters, Vtable will carry resolutions for those as well:
554 ///    concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
555 ///
556 ///    // Case B: Vtable must be provided by caller. This applies when
557 ///    // type is a type parameter.
558 ///    param.clone();    // VtableParam
559 ///
560 ///    // Case C: A mix of cases A and B.
561 ///    mixed.clone();    // Vtable(Impl_1, [VtableParam])
562 /// }
563 /// ```
564 ///
565 /// ### The type parameter `N`
566 ///
567 /// See explanation on `VtableImplData`.
568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
569 pub enum Vtable<'tcx, N> {
570     /// Vtable identifying a particular impl.
571     VtableImpl(VtableImplData<'tcx, N>),
572
573     /// Vtable for auto trait implementations.
574     /// This carries the information and nested obligations with regards
575     /// to an auto implementation for a trait `Trait`. The nested obligations
576     /// ensure the trait implementation holds for all the constituent types.
577     VtableAutoImpl(VtableAutoImplData<N>),
578
579     /// Successful resolution to an obligation provided by the caller
580     /// for some type parameter. The `Vec<N>` represents the
581     /// obligations incurred from normalizing the where-clause (if
582     /// any).
583     VtableParam(Vec<N>),
584
585     /// Virtual calls through an object.
586     VtableObject(VtableObjectData<'tcx, N>),
587
588     /// Successful resolution for a builtin trait.
589     VtableBuiltin(VtableBuiltinData<N>),
590
591     /// Vtable automatically generated for a closure. The `DefId` is the ID
592     /// of the closure expression. This is a `VtableImpl` in spirit, but the
593     /// impl is generated by the compiler and does not appear in the source.
594     VtableClosure(VtableClosureData<'tcx, N>),
595
596     /// Same as above, but for a function pointer type with the given signature.
597     VtableFnPointer(VtableFnPointerData<'tcx, N>),
598
599     /// Vtable automatically generated for a generator.
600     VtableGenerator(VtableGeneratorData<'tcx, N>),
601
602     /// Vtable for a trait alias.
603     VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
604 }
605
606 /// Identifies a particular impl in the source, along with a set of
607 /// substitutions from the impl's type/lifetime parameters. The
608 /// `nested` vector corresponds to the nested obligations attached to
609 /// the impl's type parameters.
610 ///
611 /// The type parameter `N` indicates the type used for "nested
612 /// obligations" that are required by the impl. During type-check, this
613 /// is `Obligation`, as one might expect. During codegen, however, this
614 /// is `()`, because codegen only requires a shallow resolution of an
615 /// impl, and nested obligations are satisfied later.
616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
617 pub struct VtableImplData<'tcx, N> {
618     pub impl_def_id: DefId,
619     pub substs: SubstsRef<'tcx>,
620     pub nested: Vec<N>
621 }
622
623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
624 pub struct VtableGeneratorData<'tcx, N> {
625     pub generator_def_id: DefId,
626     pub substs: SubstsRef<'tcx>,
627     /// Nested obligations. This can be non-empty if the generator
628     /// signature contains associated types.
629     pub nested: Vec<N>
630 }
631
632 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
633 pub struct VtableClosureData<'tcx, N> {
634     pub closure_def_id: DefId,
635     pub substs: SubstsRef<'tcx>,
636     /// Nested obligations. This can be non-empty if the closure
637     /// signature contains associated types.
638     pub nested: Vec<N>
639 }
640
641 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
642 pub struct VtableAutoImplData<N> {
643     pub trait_def_id: DefId,
644     pub nested: Vec<N>
645 }
646
647 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
648 pub struct VtableBuiltinData<N> {
649     pub nested: Vec<N>
650 }
651
652 /// A vtable for some object-safe trait `Foo` automatically derived
653 /// for the object type `Foo`.
654 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
655 pub struct VtableObjectData<'tcx, N> {
656     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
657     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
658
659     /// The vtable is formed by concatenating together the method lists of
660     /// the base object trait and all supertraits; this is the start of
661     /// `upcast_trait_ref`'s methods in that vtable.
662     pub vtable_base: usize,
663
664     pub nested: Vec<N>,
665 }
666
667 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
668 pub struct VtableFnPointerData<'tcx, N> {
669     pub fn_ty: Ty<'tcx>,
670     pub nested: Vec<N>
671 }
672
673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
674 pub struct VtableTraitAliasData<'tcx, N> {
675     pub alias_def_id: DefId,
676     pub substs: SubstsRef<'tcx>,
677     pub nested: Vec<N>,
678 }
679
680 /// Creates predicate obligations from the generic bounds.
681 pub fn predicates_for_generics<'tcx>(
682     cause: ObligationCause<'tcx>,
683     param_env: ty::ParamEnv<'tcx>,
684     generic_bounds: &ty::InstantiatedPredicates<'tcx>,
685 ) -> PredicateObligations<'tcx> {
686     util::predicates_for_generics(cause, 0, param_env, generic_bounds)
687 }
688
689 /// Determines whether the type `ty` is known to meet `bound` and
690 /// returns true if so. Returns false if `ty` either does not meet
691 /// `bound` or is not known to meet bound (note that this is
692 /// conservative towards *no impl*, which is the opposite of the
693 /// `evaluate` methods).
694 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
695     infcx: &InferCtxt<'a, 'tcx>,
696     param_env: ty::ParamEnv<'tcx>,
697     ty: Ty<'tcx>,
698     def_id: DefId,
699     span: Span,
700 ) -> bool {
701     debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
702            ty,
703            infcx.tcx.def_path_str(def_id));
704
705     let trait_ref = ty::TraitRef {
706         def_id,
707         substs: infcx.tcx.mk_substs_trait(ty, &[]),
708     };
709     let obligation = Obligation {
710         param_env,
711         cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
712         recursion_depth: 0,
713         predicate: trait_ref.to_predicate(),
714     };
715
716     let result = infcx.predicate_must_hold_modulo_regions(&obligation);
717     debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
718            ty, infcx.tcx.def_path_str(def_id), result);
719
720     if result && (ty.has_infer_types() || ty.has_closure_types()) {
721         // Because of inference "guessing", selection can sometimes claim
722         // to succeed while the success requires a guess. To ensure
723         // this function's result remains infallible, we must confirm
724         // that guess. While imperfect, I believe this is sound.
725
726         // The handling of regions in this area of the code is terrible,
727         // see issue #29149. We should be able to improve on this with
728         // NLL.
729         let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
730
731         // We can use a dummy node-id here because we won't pay any mind
732         // to region obligations that arise (there shouldn't really be any
733         // anyhow).
734         let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
735
736         fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
737
738         // Note: we only assume something is `Copy` if we can
739         // *definitively* show that it implements `Copy`. Otherwise,
740         // assume it is move; linear is always ok.
741         match fulfill_cx.select_all_or_error(infcx) {
742             Ok(()) => {
743                 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
744                        ty,
745                        infcx.tcx.def_path_str(def_id));
746                 true
747             }
748             Err(e) => {
749                 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
750                        ty,
751                        infcx.tcx.def_path_str(def_id),
752                        e);
753                 false
754             }
755         }
756     } else {
757         result
758     }
759 }
760
761 fn do_normalize_predicates<'tcx>(
762     tcx: TyCtxt<'tcx>,
763     region_context: DefId,
764     cause: ObligationCause<'tcx>,
765     elaborated_env: ty::ParamEnv<'tcx>,
766     predicates: Vec<ty::Predicate<'tcx>>,
767 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
768     debug!(
769         "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
770         predicates,
771         region_context,
772         cause,
773     );
774     let span = cause.span;
775     tcx.infer_ctxt().enter(|infcx| {
776         // FIXME. We should really... do something with these region
777         // obligations. But this call just continues the older
778         // behavior (i.e., doesn't cause any new bugs), and it would
779         // take some further refactoring to actually solve them. In
780         // particular, we would have to handle implied bounds
781         // properly, and that code is currently largely confined to
782         // regionck (though I made some efforts to extract it
783         // out). -nmatsakis
784         //
785         // @arielby: In any case, these obligations are checked
786         // by wfcheck anyway, so I'm not sure we have to check
787         // them here too, and we will remove this function when
788         // we move over to lazy normalization *anyway*.
789         let fulfill_cx = FulfillmentContext::new_ignoring_regions();
790         let predicates = match fully_normalize(
791             &infcx,
792             fulfill_cx,
793             cause,
794             elaborated_env,
795             &predicates,
796         ) {
797             Ok(predicates) => predicates,
798             Err(errors) => {
799                 infcx.report_fulfillment_errors(&errors, None, false);
800                 return Err(ErrorReported)
801             }
802         };
803
804         debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
805
806         let region_scope_tree = region::ScopeTree::default();
807
808         // We can use the `elaborated_env` here; the region code only
809         // cares about declarations like `'a: 'b`.
810         let outlives_env = OutlivesEnvironment::new(elaborated_env);
811
812         infcx.resolve_regions_and_report_errors(
813             region_context,
814             &region_scope_tree,
815             &outlives_env,
816             SuppressRegionErrors::default(),
817         );
818
819         let predicates = match infcx.fully_resolve(&predicates) {
820             Ok(predicates) => predicates,
821             Err(fixup_err) => {
822                 // If we encounter a fixup error, it means that some type
823                 // variable wound up unconstrained. I actually don't know
824                 // if this can happen, and I certainly don't expect it to
825                 // happen often, but if it did happen it probably
826                 // represents a legitimate failure due to some kind of
827                 // unconstrained variable, and it seems better not to ICE,
828                 // all things considered.
829                 tcx.sess.span_err(span, &fixup_err.to_string());
830                 return Err(ErrorReported)
831             }
832         };
833         if predicates.has_local_value() {
834             // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
835             Err(ErrorReported)
836         } else {
837             Ok(predicates)
838         }
839     })
840 }
841
842 // FIXME: this is gonna need to be removed ...
843 /// Normalizes the parameter environment, reporting errors if they occur.
844 pub fn normalize_param_env_or_error<'tcx>(
845     tcx: TyCtxt<'tcx>,
846     region_context: DefId,
847     unnormalized_env: ty::ParamEnv<'tcx>,
848     cause: ObligationCause<'tcx>,
849 ) -> ty::ParamEnv<'tcx> {
850     // I'm not wild about reporting errors here; I'd prefer to
851     // have the errors get reported at a defined place (e.g.,
852     // during typeck). Instead I have all parameter
853     // environments, in effect, going through this function
854     // and hence potentially reporting errors. This ensures of
855     // course that we never forget to normalize (the
856     // alternative seemed like it would involve a lot of
857     // manual invocations of this fn -- and then we'd have to
858     // deal with the errors at each of those sites).
859     //
860     // In any case, in practice, typeck constructs all the
861     // parameter environments once for every fn as it goes,
862     // and errors will get reported then; so after typeck we
863     // can be sure that no errors should occur.
864
865     debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
866            region_context, unnormalized_env, cause);
867
868     let mut predicates: Vec<_> =
869         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
870             .collect();
871
872     debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
873            predicates);
874
875     let elaborated_env = ty::ParamEnv::new(
876         tcx.intern_predicates(&predicates),
877         unnormalized_env.reveal,
878         unnormalized_env.def_id
879     );
880
881     // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
882     // normalization expects its param-env to be already normalized, which means we have
883     // a circularity.
884     //
885     // The way we handle this is by normalizing the param-env inside an unnormalized version
886     // of the param-env, which means that if the param-env contains unnormalized projections,
887     // we'll have some normalization failures. This is unfortunate.
888     //
889     // Lazy normalization would basically handle this by treating just the
890     // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
891     //
892     // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
893     // types, so to make the situation less bad, we normalize all the predicates *but*
894     // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
895     // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
896     //
897     // This works fairly well because trait matching  does not actually care about param-env
898     // TypeOutlives predicates - these are normally used by regionck.
899     let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
900         match predicate {
901             ty::Predicate::TypeOutlives(..) => true,
902             _ => false
903         }
904     }).collect();
905
906     debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
907            predicates, outlives_predicates);
908     let non_outlives_predicates =
909         match do_normalize_predicates(tcx, region_context, cause.clone(),
910                                       elaborated_env, predicates) {
911             Ok(predicates) => predicates,
912             // An unnormalized env is better than nothing.
913             Err(ErrorReported) => {
914                 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
915                 return elaborated_env
916             }
917         };
918
919     debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
920
921     // Not sure whether it is better to include the unnormalized TypeOutlives predicates
922     // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
923     // predicates here anyway. Keeping them here anyway because it seems safer.
924     let outlives_env: Vec<_> =
925         non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
926     let outlives_env = ty::ParamEnv::new(
927         tcx.intern_predicates(&outlives_env),
928         unnormalized_env.reveal,
929         None
930     );
931     let outlives_predicates =
932         match do_normalize_predicates(tcx, region_context, cause,
933                                       outlives_env, outlives_predicates) {
934             Ok(predicates) => predicates,
935             // An unnormalized env is better than nothing.
936             Err(ErrorReported) => {
937                 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
938                 return elaborated_env
939             }
940         };
941     debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
942
943     let mut predicates = non_outlives_predicates;
944     predicates.extend(outlives_predicates);
945     debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
946     ty::ParamEnv::new(
947         tcx.intern_predicates(&predicates),
948         unnormalized_env.reveal,
949         unnormalized_env.def_id
950     )
951 }
952
953 pub fn fully_normalize<'a, 'tcx, T>(
954     infcx: &InferCtxt<'a, 'tcx>,
955     mut fulfill_cx: FulfillmentContext<'tcx>,
956     cause: ObligationCause<'tcx>,
957     param_env: ty::ParamEnv<'tcx>,
958     value: &T,
959 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
960 where
961     T: TypeFoldable<'tcx>,
962 {
963     debug!("fully_normalize_with_fulfillcx(value={:?})", value);
964     let selcx = &mut SelectionContext::new(infcx);
965     let Normalized { value: normalized_value, obligations } =
966         project::normalize(selcx, param_env, cause, value);
967     debug!("fully_normalize: normalized_value={:?} obligations={:?}",
968            normalized_value,
969            obligations);
970     for obligation in obligations {
971         fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
972     }
973
974     debug!("fully_normalize: select_all_or_error start");
975     fulfill_cx.select_all_or_error(infcx)?;
976     debug!("fully_normalize: select_all_or_error complete");
977     let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
978     debug!("fully_normalize: resolved_value={:?}", resolved_value);
979     Ok(resolved_value)
980 }
981
982 /// Normalizes the predicates and checks whether they hold in an empty
983 /// environment. If this returns false, then either normalize
984 /// encountered an error or one of the predicates did not hold. Used
985 /// when creating vtables to check for unsatisfiable methods.
986 fn normalize_and_test_predicates<'tcx>(
987     tcx: TyCtxt<'tcx>,
988     predicates: Vec<ty::Predicate<'tcx>>,
989 ) -> bool {
990     debug!("normalize_and_test_predicates(predicates={:?})",
991            predicates);
992
993     let result = tcx.infer_ctxt().enter(|infcx| {
994         let param_env = ty::ParamEnv::reveal_all();
995         let mut selcx = SelectionContext::new(&infcx);
996         let mut fulfill_cx = FulfillmentContext::new();
997         let cause = ObligationCause::dummy();
998         let Normalized { value: predicates, obligations } =
999             normalize(&mut selcx, param_env, cause.clone(), &predicates);
1000         for obligation in obligations {
1001             fulfill_cx.register_predicate_obligation(&infcx, obligation);
1002         }
1003         for predicate in predicates {
1004             let obligation = Obligation::new(cause.clone(), param_env, predicate);
1005             fulfill_cx.register_predicate_obligation(&infcx, obligation);
1006         }
1007
1008         fulfill_cx.select_all_or_error(&infcx).is_ok()
1009     });
1010     debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
1011            predicates, result);
1012     result
1013 }
1014
1015 fn substitute_normalize_and_test_predicates<'tcx>(
1016     tcx: TyCtxt<'tcx>,
1017     key: (DefId, SubstsRef<'tcx>),
1018 ) -> bool {
1019     debug!("substitute_normalize_and_test_predicates(key={:?})",
1020            key);
1021
1022     let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1023     let result = normalize_and_test_predicates(tcx, predicates);
1024
1025     debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
1026            key, result);
1027     result
1028 }
1029
1030 /// Given a trait `trait_ref`, iterates the vtable entries
1031 /// that come from `trait_ref`, including its supertraits.
1032 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1033 fn vtable_methods<'tcx>(
1034     tcx: TyCtxt<'tcx>,
1035     trait_ref: ty::PolyTraitRef<'tcx>,
1036 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1037     debug!("vtable_methods({:?})", trait_ref);
1038
1039     tcx.arena.alloc_from_iter(
1040         supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1041             let trait_methods = tcx.associated_items(trait_ref.def_id())
1042                 .filter(|item| item.kind == ty::AssocKind::Method);
1043
1044             // Now list each method's DefId and InternalSubsts (for within its trait).
1045             // If the method can never be called from this object, produce None.
1046             trait_methods.map(move |trait_method| {
1047                 debug!("vtable_methods: trait_method={:?}", trait_method);
1048                 let def_id = trait_method.def_id;
1049
1050                 // Some methods cannot be called on an object; skip those.
1051                 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1052                     debug!("vtable_methods: not vtable safe");
1053                     return None;
1054                 }
1055
1056                 // The method may have some early-bound lifetimes; add regions for those.
1057                 let substs = trait_ref.map_bound(|trait_ref|
1058                     InternalSubsts::for_item(tcx, def_id, |param, _|
1059                         match param.kind {
1060                             GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1061                             GenericParamDefKind::Type { .. } |
1062                             GenericParamDefKind::Const => {
1063                                 trait_ref.substs[param.index as usize]
1064                             }
1065                         }
1066                     )
1067                 );
1068
1069                 // The trait type may have higher-ranked lifetimes in it;
1070                 // erase them if they appear, so that we get the type
1071                 // at some particular call site.
1072                 let substs = tcx.normalize_erasing_late_bound_regions(
1073                     ty::ParamEnv::reveal_all(),
1074                     &substs
1075                 );
1076
1077                 // It's possible that the method relies on where-clauses that
1078                 // do not hold for this particular set of type parameters.
1079                 // Note that this method could then never be called, so we
1080                 // do not want to try and codegen it, in that case (see #23435).
1081                 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1082                 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1083                     debug!("vtable_methods: predicates do not hold");
1084                     return None;
1085                 }
1086
1087                 Some((def_id, substs))
1088             })
1089         })
1090     )
1091 }
1092
1093 impl<'tcx, O> Obligation<'tcx, O> {
1094     pub fn new(cause: ObligationCause<'tcx>,
1095                param_env: ty::ParamEnv<'tcx>,
1096                predicate: O)
1097                -> Obligation<'tcx, O>
1098     {
1099         Obligation { cause, param_env, recursion_depth: 0, predicate }
1100     }
1101
1102     fn with_depth(cause: ObligationCause<'tcx>,
1103                   recursion_depth: usize,
1104                   param_env: ty::ParamEnv<'tcx>,
1105                   predicate: O)
1106                   -> Obligation<'tcx, O>
1107     {
1108         Obligation { cause, param_env, recursion_depth, predicate }
1109     }
1110
1111     pub fn misc(span: Span,
1112                 body_id: hir::HirId,
1113                 param_env: ty::ParamEnv<'tcx>,
1114                 trait_ref: O)
1115                 -> Obligation<'tcx, O> {
1116         Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1117     }
1118
1119     pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1120         Obligation { cause: self.cause.clone(),
1121                      param_env: self.param_env,
1122                      recursion_depth: self.recursion_depth,
1123                      predicate: value }
1124     }
1125 }
1126
1127 impl<'tcx> ObligationCause<'tcx> {
1128     #[inline]
1129     pub fn new(span: Span,
1130                body_id: hir::HirId,
1131                code: ObligationCauseCode<'tcx>)
1132                -> ObligationCause<'tcx> {
1133         ObligationCause { span, body_id, code }
1134     }
1135
1136     pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1137         ObligationCause { span, body_id, code: MiscObligation }
1138     }
1139
1140     pub fn dummy() -> ObligationCause<'tcx> {
1141         ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1142     }
1143 }
1144
1145 impl<'tcx, N> Vtable<'tcx, N> {
1146     pub fn nested_obligations(self) -> Vec<N> {
1147         match self {
1148             VtableImpl(i) => i.nested,
1149             VtableParam(n) => n,
1150             VtableBuiltin(i) => i.nested,
1151             VtableAutoImpl(d) => d.nested,
1152             VtableClosure(c) => c.nested,
1153             VtableGenerator(c) => c.nested,
1154             VtableObject(d) => d.nested,
1155             VtableFnPointer(d) => d.nested,
1156             VtableTraitAlias(d) => d.nested,
1157         }
1158     }
1159
1160     pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1161         match self {
1162             VtableImpl(i) => VtableImpl(VtableImplData {
1163                 impl_def_id: i.impl_def_id,
1164                 substs: i.substs,
1165                 nested: i.nested.into_iter().map(f).collect(),
1166             }),
1167             VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1168             VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1169                 nested: i.nested.into_iter().map(f).collect(),
1170             }),
1171             VtableObject(o) => VtableObject(VtableObjectData {
1172                 upcast_trait_ref: o.upcast_trait_ref,
1173                 vtable_base: o.vtable_base,
1174                 nested: o.nested.into_iter().map(f).collect(),
1175             }),
1176             VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1177                 trait_def_id: d.trait_def_id,
1178                 nested: d.nested.into_iter().map(f).collect(),
1179             }),
1180             VtableClosure(c) => VtableClosure(VtableClosureData {
1181                 closure_def_id: c.closure_def_id,
1182                 substs: c.substs,
1183                 nested: c.nested.into_iter().map(f).collect(),
1184             }),
1185             VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1186                 generator_def_id: c.generator_def_id,
1187                 substs: c.substs,
1188                 nested: c.nested.into_iter().map(f).collect(),
1189             }),
1190             VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1191                 fn_ty: p.fn_ty,
1192                 nested: p.nested.into_iter().map(f).collect(),
1193             }),
1194             VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1195                 alias_def_id: d.alias_def_id,
1196                 substs: d.substs,
1197                 nested: d.nested.into_iter().map(f).collect(),
1198             }),
1199         }
1200     }
1201 }
1202
1203 impl<'tcx> FulfillmentError<'tcx> {
1204     fn new(obligation: PredicateObligation<'tcx>,
1205            code: FulfillmentErrorCode<'tcx>)
1206            -> FulfillmentError<'tcx>
1207     {
1208         FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
1209     }
1210 }
1211
1212 impl<'tcx> TraitObligation<'tcx> {
1213     fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1214         self.predicate.map_bound(|p| p.self_ty())
1215     }
1216 }
1217
1218 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1219     *providers = ty::query::Providers {
1220         is_object_safe: object_safety::is_object_safe_provider,
1221         specialization_graph_of: specialize::specialization_graph_provider,
1222         specializes: specialize::specializes,
1223         codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1224         vtable_methods,
1225         substitute_normalize_and_test_predicates,
1226         ..*providers
1227     };
1228 }
1229
1230 pub trait ExClauseFold<'tcx>
1231 where
1232     Self: chalk_engine::context::Context + Clone,
1233 {
1234     fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1235         ex_clause: &chalk_engine::ExClause<Self>,
1236         folder: &mut F,
1237     ) -> chalk_engine::ExClause<Self>;
1238
1239     fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1240         ex_clause: &chalk_engine::ExClause<Self>,
1241         visitor: &mut V,
1242     ) -> bool;
1243 }
1244
1245 pub trait ChalkContextLift<'tcx>
1246 where
1247     Self: chalk_engine::context::Context + Clone,
1248 {
1249     type LiftedExClause: Debug + 'tcx;
1250     type LiftedDelayedLiteral: Debug + 'tcx;
1251     type LiftedLiteral: Debug + 'tcx;
1252
1253     fn lift_ex_clause_to_tcx(
1254         ex_clause: &chalk_engine::ExClause<Self>,
1255         tcx: TyCtxt<'tcx>,
1256     ) -> Option<Self::LiftedExClause>;
1257
1258     fn lift_delayed_literal_to_tcx(
1259         ex_clause: &chalk_engine::DelayedLiteral<Self>,
1260         tcx: TyCtxt<'tcx>,
1261     ) -> Option<Self::LiftedDelayedLiteral>;
1262
1263     fn lift_literal_to_tcx(
1264         ex_clause: &chalk_engine::Literal<Self>,
1265         tcx: TyCtxt<'tcx>,
1266     ) -> Option<Self::LiftedLiteral>;
1267 }