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