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