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