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