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