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