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