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