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