]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/mod.rs
avoid translating roots with predicates that do not hold
[rust.git] / src / librustc / traits / mod.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Trait Resolution. See README.md for an overview of how this works.
12
13 pub use self::SelectionError::*;
14 pub use self::FulfillmentErrorCode::*;
15 pub use self::Vtable::*;
16 pub use self::ObligationCauseCode::*;
17
18 use hir;
19 use hir::def_id::DefId;
20 use middle::region::RegionMaps;
21 use middle::free_region::FreeRegionMap;
22 use ty::subst::Substs;
23 use ty::{self, Ty, TyCtxt, TypeFoldable, ToPredicate};
24 use ty::error::{ExpectedFound, TypeError};
25 use infer::{InferCtxt};
26
27 use std::rc::Rc;
28 use syntax::ast;
29 use syntax_pos::{Span, DUMMY_SP};
30
31 pub use self::coherence::orphan_check;
32 pub use self::coherence::overlapping_impls;
33 pub use self::coherence::OrphanCheckErr;
34 pub use self::fulfill::{FulfillmentContext, GlobalFulfilledPredicates, RegionObligation};
35 pub use self::project::MismatchedProjectionTypes;
36 pub use self::project::{normalize, normalize_projection_type, Normalized};
37 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal};
38 pub use self::object_safety::ObjectSafetyViolation;
39 pub use self::object_safety::MethodViolationCode;
40 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
41 pub use self::specialize::{OverlapError, specialization_graph, specializes, translate_substs};
42 pub use self::specialize::{SpecializesCache, find_associated_item};
43 pub use self::util::elaborate_predicates;
44 pub use self::util::supertraits;
45 pub use self::util::Supertraits;
46 pub use self::util::supertrait_def_ids;
47 pub use self::util::SupertraitDefIds;
48 pub use self::util::transitive_bounds;
49
50 mod coherence;
51 mod error_reporting;
52 mod fulfill;
53 mod project;
54 mod object_safety;
55 mod select;
56 mod specialize;
57 mod structural_impls;
58 pub mod trans;
59 mod util;
60
61 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
62 /// which the vtable must be found.  The process of finding a vtable is
63 /// called "resolving" the `Obligation`. This process consists of
64 /// either identifying an `impl` (e.g., `impl Eq for int`) that
65 /// provides the required vtable, or else finding a bound that is in
66 /// scope. The eventual result is usually a `Selection` (defined below).
67 #[derive(Clone, PartialEq, Eq)]
68 pub struct Obligation<'tcx, T> {
69     pub cause: ObligationCause<'tcx>,
70     pub param_env: ty::ParamEnv<'tcx>,
71     pub recursion_depth: usize,
72     pub predicate: T,
73 }
74
75 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
76 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
77
78 /// Why did we incur this obligation? Used for error reporting.
79 #[derive(Clone, Debug, PartialEq, Eq)]
80 pub struct ObligationCause<'tcx> {
81     pub span: Span,
82
83     // The id of the fn body that triggered this obligation. This is
84     // used for region obligations to determine the precise
85     // environment in which the region obligation should be evaluated
86     // (in particular, closures can add new assumptions). See the
87     // field `region_obligations` of the `FulfillmentContext` for more
88     // information.
89     pub body_id: ast::NodeId,
90
91     pub code: ObligationCauseCode<'tcx>
92 }
93
94 #[derive(Clone, Debug, PartialEq, Eq)]
95 pub enum ObligationCauseCode<'tcx> {
96     /// Not well classified or should be obvious from span.
97     MiscObligation,
98
99     /// A slice or array is WF only if `T: Sized`
100     SliceOrArrayElem,
101
102     /// A tuple is WF only if its middle elements are Sized
103     TupleElem,
104
105     /// This is the trait reference from the given projection
106     ProjectionWf(ty::ProjectionTy<'tcx>),
107
108     /// In an impl of trait X for type Y, type Y must
109     /// also implement all supertraits of X.
110     ItemObligation(DefId),
111
112     /// A type like `&'a T` is WF only if `T: 'a`.
113     ReferenceOutlivesReferent(Ty<'tcx>),
114
115     /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
116     ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
117
118     /// Obligation incurred due to an object cast.
119     ObjectCastObligation(/* Object type */ Ty<'tcx>),
120
121     /// Various cases where expressions must be sized/copy/etc:
122     AssignmentLhsSized,        // L = X implies that L is Sized
123     StructInitializerSized,    // S { ... } must be Sized
124     VariableType(ast::NodeId), // Type of each variable must be Sized
125     ReturnType,                // Return type must be Sized
126     RepeatVec,                 // [T,..n] --> T must be Copy
127
128     // Types of fields (other than the last) in a struct must be sized.
129     FieldSized,
130
131     // Constant expressions must be sized.
132     ConstSized,
133
134     // static items must have `Sync` type
135     SharedStatic,
136
137     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
138
139     ImplDerivedObligation(DerivedObligationCause<'tcx>),
140
141     // error derived when matching traits/impls; see ObligationCause for more details
142     CompareImplMethodObligation {
143         item_name: ast::Name,
144         impl_item_def_id: DefId,
145         trait_item_def_id: DefId,
146         lint_id: Option<ast::NodeId>,
147     },
148
149     // Checking that this expression can be assigned where it needs to be
150     // FIXME(eddyb) #11161 is the original Expr required?
151     ExprAssignable,
152
153     // Computing common supertype in the arms of a match expression
154     MatchExpressionArm { arm_span: Span,
155                          source: hir::MatchSource },
156
157     // Computing common supertype in an if expression
158     IfExpression,
159
160     // Computing common supertype of an if expression with no else counter-part
161     IfExpressionWithNoElse,
162
163     // `where a == b`
164     EquatePredicate,
165
166     // `main` has wrong type
167     MainFunctionType,
168
169     // `start` has wrong type
170     StartFunctionType,
171
172     // intrinsic has wrong type
173     IntrinsicType,
174
175     // method receiver
176     MethodReceiver,
177
178     // `return` with no expression
179     ReturnNoExpression,
180 }
181
182 #[derive(Clone, Debug, PartialEq, Eq)]
183 pub struct DerivedObligationCause<'tcx> {
184     /// The trait reference of the parent obligation that led to the
185     /// current obligation. Note that only trait obligations lead to
186     /// derived obligations, so we just store the trait reference here
187     /// directly.
188     parent_trait_ref: ty::PolyTraitRef<'tcx>,
189
190     /// The parent trait had this cause
191     parent_code: Rc<ObligationCauseCode<'tcx>>
192 }
193
194 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
195 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
196 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
197
198 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
199
200 #[derive(Clone,Debug)]
201 pub enum SelectionError<'tcx> {
202     Unimplemented,
203     OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
204                                 ty::PolyTraitRef<'tcx>,
205                                 ty::error::TypeError<'tcx>),
206     TraitNotObjectSafe(DefId),
207 }
208
209 pub struct FulfillmentError<'tcx> {
210     pub obligation: PredicateObligation<'tcx>,
211     pub code: FulfillmentErrorCode<'tcx>
212 }
213
214 #[derive(Clone)]
215 pub enum FulfillmentErrorCode<'tcx> {
216     CodeSelectionError(SelectionError<'tcx>),
217     CodeProjectionError(MismatchedProjectionTypes<'tcx>),
218     CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
219                      TypeError<'tcx>), // always comes from a SubtypePredicate
220     CodeAmbiguity,
221 }
222
223 /// When performing resolution, it is typically the case that there
224 /// can be one of three outcomes:
225 ///
226 /// - `Ok(Some(r))`: success occurred with result `r`
227 /// - `Ok(None)`: could not definitely determine anything, usually due
228 ///   to inconclusive type inference.
229 /// - `Err(e)`: error `e` occurred
230 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
231
232 /// Given the successful resolution of an obligation, the `Vtable`
233 /// indicates where the vtable comes from. Note that while we call this
234 /// a "vtable", it does not necessarily indicate dynamic dispatch at
235 /// runtime. `Vtable` instances just tell the compiler where to find
236 /// methods, but in generic code those methods are typically statically
237 /// dispatched -- only when an object is constructed is a `Vtable`
238 /// instance reified into an actual vtable.
239 ///
240 /// For example, the vtable may be tied to a specific impl (case A),
241 /// or it may be relative to some bound that is in scope (case B).
242 ///
243 ///
244 /// ```
245 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
246 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
247 /// impl Clone for int { ... }             // Impl_3
248 ///
249 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
250 ///                 param: T,
251 ///                 mixed: Option<T>) {
252 ///
253 ///    // Case A: Vtable points at a specific impl. Only possible when
254 ///    // type is concretely known. If the impl itself has bounded
255 ///    // type parameters, Vtable will carry resolutions for those as well:
256 ///    concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
257 ///
258 ///    // Case B: Vtable must be provided by caller. This applies when
259 ///    // type is a type parameter.
260 ///    param.clone();    // VtableParam
261 ///
262 ///    // Case C: A mix of cases A and B.
263 ///    mixed.clone();    // Vtable(Impl_1, [VtableParam])
264 /// }
265 /// ```
266 ///
267 /// ### The type parameter `N`
268 ///
269 /// See explanation on `VtableImplData`.
270 #[derive(Clone)]
271 pub enum Vtable<'tcx, N> {
272     /// Vtable identifying a particular impl.
273     VtableImpl(VtableImplData<'tcx, N>),
274
275     /// Vtable for default trait implementations
276     /// This carries the information and nested obligations with regards
277     /// to a default implementation for a trait `Trait`. The nested obligations
278     /// ensure the trait implementation holds for all the constituent types.
279     VtableDefaultImpl(VtableDefaultImplData<N>),
280
281     /// Successful resolution to an obligation provided by the caller
282     /// for some type parameter. The `Vec<N>` represents the
283     /// obligations incurred from normalizing the where-clause (if
284     /// any).
285     VtableParam(Vec<N>),
286
287     /// Virtual calls through an object
288     VtableObject(VtableObjectData<'tcx, N>),
289
290     /// Successful resolution for a builtin trait.
291     VtableBuiltin(VtableBuiltinData<N>),
292
293     /// Vtable automatically generated for a closure. The def ID is the ID
294     /// of the closure expression. This is a `VtableImpl` in spirit, but the
295     /// impl is generated by the compiler and does not appear in the source.
296     VtableClosure(VtableClosureData<'tcx, N>),
297
298     /// Same as above, but for a fn pointer type with the given signature.
299     VtableFnPointer(VtableFnPointerData<'tcx, N>),
300 }
301
302 /// Identifies a particular impl in the source, along with a set of
303 /// substitutions from the impl's type/lifetime parameters. The
304 /// `nested` vector corresponds to the nested obligations attached to
305 /// the impl's type parameters.
306 ///
307 /// The type parameter `N` indicates the type used for "nested
308 /// obligations" that are required by the impl. During type check, this
309 /// is `Obligation`, as one might expect. During trans, however, this
310 /// is `()`, because trans only requires a shallow resolution of an
311 /// impl, and nested obligations are satisfied later.
312 #[derive(Clone, PartialEq, Eq)]
313 pub struct VtableImplData<'tcx, N> {
314     pub impl_def_id: DefId,
315     pub substs: &'tcx Substs<'tcx>,
316     pub nested: Vec<N>
317 }
318
319 #[derive(Clone, PartialEq, Eq)]
320 pub struct VtableClosureData<'tcx, N> {
321     pub closure_def_id: DefId,
322     pub substs: ty::ClosureSubsts<'tcx>,
323     /// Nested obligations. This can be non-empty if the closure
324     /// signature contains associated types.
325     pub nested: Vec<N>
326 }
327
328 #[derive(Clone)]
329 pub struct VtableDefaultImplData<N> {
330     pub trait_def_id: DefId,
331     pub nested: Vec<N>
332 }
333
334 #[derive(Clone)]
335 pub struct VtableBuiltinData<N> {
336     pub nested: Vec<N>
337 }
338
339 /// A vtable for some object-safe trait `Foo` automatically derived
340 /// for the object type `Foo`.
341 #[derive(PartialEq,Eq,Clone)]
342 pub struct VtableObjectData<'tcx, N> {
343     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
344     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
345
346     /// The vtable is formed by concatenating together the method lists of
347     /// the base object trait and all supertraits; this is the start of
348     /// `upcast_trait_ref`'s methods in that vtable.
349     pub vtable_base: usize,
350
351     pub nested: Vec<N>,
352 }
353
354 #[derive(Clone, PartialEq, Eq)]
355 pub struct VtableFnPointerData<'tcx, N> {
356     pub fn_ty: ty::Ty<'tcx>,
357     pub nested: Vec<N>
358 }
359
360 /// Creates predicate obligations from the generic bounds.
361 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
362                                      param_env: ty::ParamEnv<'tcx>,
363                                      generic_bounds: &ty::InstantiatedPredicates<'tcx>)
364                                      -> PredicateObligations<'tcx>
365 {
366     util::predicates_for_generics(cause, 0, param_env, generic_bounds)
367 }
368
369 /// Determines whether the type `ty` is known to meet `bound` and
370 /// returns true if so. Returns false if `ty` either does not meet
371 /// `bound` or is not known to meet bound (note that this is
372 /// conservative towards *no impl*, which is the opposite of the
373 /// `evaluate` methods).
374 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
375                                                 param_env: ty::ParamEnv<'tcx>,
376                                                 ty: Ty<'tcx>,
377                                                 def_id: DefId,
378                                                 span: Span)
379 -> bool
380 {
381     debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
382            ty,
383            infcx.tcx.item_path_str(def_id));
384
385     let trait_ref = ty::TraitRef {
386         def_id: def_id,
387         substs: infcx.tcx.mk_substs_trait(ty, &[]),
388     };
389     let obligation = Obligation {
390         param_env,
391         cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
392         recursion_depth: 0,
393         predicate: trait_ref.to_predicate(),
394     };
395
396     let result = SelectionContext::new(infcx)
397         .evaluate_obligation_conservatively(&obligation);
398     debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
399            ty, infcx.tcx.item_path_str(def_id), result);
400
401     if result && (ty.has_infer_types() || ty.has_closure_types()) {
402         // Because of inference "guessing", selection can sometimes claim
403         // to succeed while the success requires a guess. To ensure
404         // this function's result remains infallible, we must confirm
405         // that guess. While imperfect, I believe this is sound.
406
407         let mut fulfill_cx = FulfillmentContext::new();
408
409         // We can use a dummy node-id here because we won't pay any mind
410         // to region obligations that arise (there shouldn't really be any
411         // anyhow).
412         let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
413
414         fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
415
416         // Note: we only assume something is `Copy` if we can
417         // *definitively* show that it implements `Copy`. Otherwise,
418         // assume it is move; linear is always ok.
419         match fulfill_cx.select_all_or_error(infcx) {
420             Ok(()) => {
421                 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
422                        ty,
423                        infcx.tcx.item_path_str(def_id));
424                 true
425             }
426             Err(e) => {
427                 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
428                        ty,
429                        infcx.tcx.item_path_str(def_id),
430                        e);
431                 false
432             }
433         }
434     } else {
435         result
436     }
437 }
438
439 // FIXME: this is gonna need to be removed ...
440 /// Normalizes the parameter environment, reporting errors if they occur.
441 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
442                                               region_context: DefId,
443                                               unnormalized_env: ty::ParamEnv<'tcx>,
444                                               cause: ObligationCause<'tcx>)
445                                               -> ty::ParamEnv<'tcx>
446 {
447     // I'm not wild about reporting errors here; I'd prefer to
448     // have the errors get reported at a defined place (e.g.,
449     // during typeck). Instead I have all parameter
450     // environments, in effect, going through this function
451     // and hence potentially reporting errors. This ensurse of
452     // course that we never forget to normalize (the
453     // alternative seemed like it would involve a lot of
454     // manual invocations of this fn -- and then we'd have to
455     // deal with the errors at each of those sites).
456     //
457     // In any case, in practice, typeck constructs all the
458     // parameter environments once for every fn as it goes,
459     // and errors will get reported then; so after typeck we
460     // can be sure that no errors should occur.
461
462     let span = cause.span;
463
464     debug!("normalize_param_env_or_error(unnormalized_env={:?})",
465            unnormalized_env);
466
467     let predicates: Vec<_> =
468         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
469         .filter(|p| !p.is_global()) // (*)
470         .collect();
471
472     // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
473     // need to be in the *environment* to be proven, so screen those
474     // out. This is important for the soundness of inter-fn
475     // caching. Note though that we should probably check that these
476     // predicates hold at the point where the environment is
477     // constructed, but I am not currently doing so out of laziness.
478     // -nmatsakis
479
480     debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
481            predicates);
482
483     let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
484                                            unnormalized_env.reveal);
485
486     tcx.infer_ctxt().enter(|infcx| {
487         let predicates = match fully_normalize(
488             &infcx,
489             cause,
490             elaborated_env,
491             // You would really want to pass infcx.param_env.caller_bounds here,
492             // but that is an interned slice, and fully_normalize takes &T and returns T, so
493             // without further refactoring, a slice can't be used. Luckily, we still have the
494             // predicate vector from which we created the ParamEnv in infcx, so we
495             // can pass that instead. It's roundabout and a bit brittle, but this code path
496             // ought to be refactored anyway, and until then it saves us from having to copy.
497             &predicates,
498         ) {
499             Ok(predicates) => predicates,
500             Err(errors) => {
501                 infcx.report_fulfillment_errors(&errors);
502                 // An unnormalized env is better than nothing.
503                 return elaborated_env;
504             }
505         };
506
507         debug!("normalize_param_env_or_error: normalized predicates={:?}",
508             predicates);
509
510         let region_maps = RegionMaps::new();
511         let free_regions = FreeRegionMap::new();
512         infcx.resolve_regions_and_report_errors(region_context, &region_maps, &free_regions);
513         let predicates = match infcx.fully_resolve(&predicates) {
514             Ok(predicates) => predicates,
515             Err(fixup_err) => {
516                 // If we encounter a fixup error, it means that some type
517                 // variable wound up unconstrained. I actually don't know
518                 // if this can happen, and I certainly don't expect it to
519                 // happen often, but if it did happen it probably
520                 // represents a legitimate failure due to some kind of
521                 // unconstrained variable, and it seems better not to ICE,
522                 // all things considered.
523                 tcx.sess.span_err(span, &fixup_err.to_string());
524                 // An unnormalized env is better than nothing.
525                 return elaborated_env;
526             }
527         };
528
529         let predicates = match tcx.lift_to_global(&predicates) {
530             Some(predicates) => predicates,
531             None => return elaborated_env,
532         };
533
534         debug!("normalize_param_env_or_error: resolved predicates={:?}",
535                predicates);
536
537         ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal)
538     })
539 }
540
541 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
542                                           cause: ObligationCause<'tcx>,
543                                           param_env: ty::ParamEnv<'tcx>,
544                                           value: &T)
545                                           -> Result<T, Vec<FulfillmentError<'tcx>>>
546     where T : TypeFoldable<'tcx>
547 {
548     debug!("fully_normalize(value={:?})", value);
549
550     let mut selcx = &mut SelectionContext::new(infcx);
551     // FIXME (@jroesch) ISSUE 26721
552     // I'm not sure if this is a bug or not, needs further investigation.
553     // It appears that by reusing the fulfillment_cx here we incur more
554     // obligations and later trip an asssertion on regionck.rs line 337.
555     //
556     // The two possibilities I see is:
557     //      - normalization is not actually fully happening and we
558     //        have a bug else where
559     //      - we are adding a duplicate bound into the list causing
560     //        its size to change.
561     //
562     // I think we should probably land this refactor and then come
563     // back to this is a follow-up patch.
564     let mut fulfill_cx = FulfillmentContext::new();
565
566     let Normalized { value: normalized_value, obligations } =
567         project::normalize(selcx, param_env, cause, value);
568     debug!("fully_normalize: normalized_value={:?} obligations={:?}",
569            normalized_value,
570            obligations);
571     for obligation in obligations {
572         fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
573     }
574
575     debug!("fully_normalize: select_all_or_error start");
576     match fulfill_cx.select_all_or_error(infcx) {
577         Ok(()) => { }
578         Err(e) => {
579             debug!("fully_normalize: error={:?}", e);
580             return Err(e);
581         }
582     }
583     debug!("fully_normalize: select_all_or_error complete");
584     let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
585     debug!("fully_normalize: resolved_value={:?}", resolved_value);
586     Ok(resolved_value)
587 }
588
589 /// Normalizes the predicates and checks whether they hold in an empty
590 /// environment. If this returns false, then either normalize
591 /// encountered an error or one of the predicates did not hold. Used
592 /// when creating vtables to check for unsatisfiable methods.
593 pub fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
594                                                predicates: Vec<ty::Predicate<'tcx>>)
595                                                -> bool
596 {
597     debug!("normalize_and_test_predicates(predicates={:?})",
598            predicates);
599
600     let result = tcx.infer_ctxt().enter(|infcx| {
601         let param_env = ty::ParamEnv::empty(Reveal::All);
602         let mut selcx = SelectionContext::new(&infcx);
603         let mut fulfill_cx = FulfillmentContext::new();
604         let cause = ObligationCause::dummy();
605         let Normalized { value: predicates, obligations } =
606             normalize(&mut selcx, param_env, cause.clone(), &predicates);
607         for obligation in obligations {
608             fulfill_cx.register_predicate_obligation(&infcx, obligation);
609         }
610         for predicate in predicates {
611             let obligation = Obligation::new(cause.clone(), param_env, predicate);
612             fulfill_cx.register_predicate_obligation(&infcx, obligation);
613         }
614
615         fulfill_cx.select_all_or_error(&infcx).is_ok()
616     });
617     debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
618            predicates, result);
619     result
620 }
621
622 /// Given a trait `trait_ref`, iterates the vtable entries
623 /// that come from `trait_ref`, including its supertraits.
624 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
625 pub fn get_vtable_methods<'a, 'tcx>(
626     tcx: TyCtxt<'a, 'tcx, 'tcx>,
627     trait_ref: ty::PolyTraitRef<'tcx>)
628     -> impl Iterator<Item=Option<(DefId, &'tcx Substs<'tcx>)>> + 'a
629 {
630     debug!("get_vtable_methods({:?})", trait_ref);
631
632     supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
633         let trait_methods = tcx.associated_items(trait_ref.def_id())
634             .filter(|item| item.kind == ty::AssociatedKind::Method);
635
636         // Now list each method's DefId and Substs (for within its trait).
637         // If the method can never be called from this object, produce None.
638         trait_methods.map(move |trait_method| {
639             debug!("get_vtable_methods: trait_method={:?}", trait_method);
640             let def_id = trait_method.def_id;
641
642             // Some methods cannot be called on an object; skip those.
643             if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
644                 debug!("get_vtable_methods: not vtable safe");
645                 return None;
646             }
647
648             // the method may have some early-bound lifetimes, add
649             // regions for those
650             let substs = Substs::for_item(tcx, def_id,
651                                           |_, _| tcx.types.re_erased,
652                                           |def, _| trait_ref.substs().type_for_def(def));
653
654             // the trait type may have higher-ranked lifetimes in it;
655             // so erase them if they appear, so that we get the type
656             // at some particular call site
657             let substs = tcx.erase_late_bound_regions_and_normalize(&ty::Binder(substs));
658
659             // It's possible that the method relies on where clauses that
660             // do not hold for this particular set of type parameters.
661             // Note that this method could then never be called, so we
662             // do not want to try and trans it, in that case (see #23435).
663             let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
664             if !normalize_and_test_predicates(tcx, predicates.predicates) {
665                 debug!("get_vtable_methods: predicates do not hold");
666                 return None;
667             }
668
669             Some((def_id, substs))
670         })
671     })
672 }
673
674 impl<'tcx,O> Obligation<'tcx,O> {
675     pub fn new(cause: ObligationCause<'tcx>,
676                param_env: ty::ParamEnv<'tcx>,
677                predicate: O)
678                -> Obligation<'tcx, O>
679     {
680         Obligation { cause, param_env, recursion_depth: 0, predicate }
681     }
682
683     fn with_depth(cause: ObligationCause<'tcx>,
684                   recursion_depth: usize,
685                   param_env: ty::ParamEnv<'tcx>,
686                   predicate: O)
687                   -> Obligation<'tcx, O>
688     {
689         Obligation { cause, param_env, recursion_depth, predicate }
690     }
691
692     pub fn misc(span: Span,
693                 body_id: ast::NodeId,
694                 param_env: ty::ParamEnv<'tcx>,
695                 trait_ref: O)
696                 -> Obligation<'tcx, O> {
697         Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
698     }
699
700     pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
701         Obligation { cause: self.cause.clone(),
702                      param_env: self.param_env,
703                      recursion_depth: self.recursion_depth,
704                      predicate: value }
705     }
706 }
707
708 impl<'tcx> ObligationCause<'tcx> {
709     pub fn new(span: Span,
710                body_id: ast::NodeId,
711                code: ObligationCauseCode<'tcx>)
712                -> ObligationCause<'tcx> {
713         ObligationCause { span: span, body_id: body_id, code: code }
714     }
715
716     pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
717         ObligationCause { span: span, body_id: body_id, code: MiscObligation }
718     }
719
720     pub fn dummy() -> ObligationCause<'tcx> {
721         ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
722     }
723 }
724
725 impl<'tcx, N> Vtable<'tcx, N> {
726     pub fn nested_obligations(self) -> Vec<N> {
727         match self {
728             VtableImpl(i) => i.nested,
729             VtableParam(n) => n,
730             VtableBuiltin(i) => i.nested,
731             VtableDefaultImpl(d) => d.nested,
732             VtableClosure(c) => c.nested,
733             VtableObject(d) => d.nested,
734             VtableFnPointer(d) => d.nested,
735         }
736     }
737
738     fn nested_obligations_mut(&mut self) -> &mut Vec<N> {
739         match self {
740             &mut VtableImpl(ref mut i) => &mut i.nested,
741             &mut VtableParam(ref mut n) => n,
742             &mut VtableBuiltin(ref mut i) => &mut i.nested,
743             &mut VtableDefaultImpl(ref mut d) => &mut d.nested,
744             &mut VtableClosure(ref mut c) => &mut c.nested,
745             &mut VtableObject(ref mut d) => &mut d.nested,
746             &mut VtableFnPointer(ref mut d) => &mut d.nested,
747         }
748     }
749
750     pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
751         match self {
752             VtableImpl(i) => VtableImpl(VtableImplData {
753                 impl_def_id: i.impl_def_id,
754                 substs: i.substs,
755                 nested: i.nested.into_iter().map(f).collect(),
756             }),
757             VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
758             VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
759                 nested: i.nested.into_iter().map(f).collect(),
760             }),
761             VtableObject(o) => VtableObject(VtableObjectData {
762                 upcast_trait_ref: o.upcast_trait_ref,
763                 vtable_base: o.vtable_base,
764                 nested: o.nested.into_iter().map(f).collect(),
765             }),
766             VtableDefaultImpl(d) => VtableDefaultImpl(VtableDefaultImplData {
767                 trait_def_id: d.trait_def_id,
768                 nested: d.nested.into_iter().map(f).collect(),
769             }),
770             VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
771                 fn_ty: p.fn_ty,
772                 nested: p.nested.into_iter().map(f).collect(),
773             }),
774             VtableClosure(c) => VtableClosure(VtableClosureData {
775                 closure_def_id: c.closure_def_id,
776                 substs: c.substs,
777                 nested: c.nested.into_iter().map(f).collect(),
778             })
779         }
780     }
781 }
782
783 impl<'tcx> FulfillmentError<'tcx> {
784     fn new(obligation: PredicateObligation<'tcx>,
785            code: FulfillmentErrorCode<'tcx>)
786            -> FulfillmentError<'tcx>
787     {
788         FulfillmentError { obligation: obligation, code: code }
789     }
790 }
791
792 impl<'tcx> TraitObligation<'tcx> {
793     fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
794         ty::Binder(self.predicate.skip_binder().self_ty())
795     }
796 }
797
798 pub fn provide(providers: &mut ty::maps::Providers) {
799     *providers = ty::maps::Providers {
800         is_object_safe: object_safety::is_object_safe_provider,
801         specialization_graph_of: specialize::specialization_graph_provider,
802         ..*providers
803     };
804 }
805
806 pub fn provide_extern(providers: &mut ty::maps::Providers) {
807     *providers = ty::maps::Providers {
808         is_object_safe: object_safety::is_object_safe_provider,
809         specialization_graph_of: specialize::specialization_graph_provider,
810         ..*providers
811     };
812 }