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