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