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