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