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