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