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