]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/traits/mod.rs
Merge pull request #20510 from tshepang/patch-6
[rust.git] / src / librustc / middle / 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 doc.rs.
12
13 pub use self::SelectionError::*;
14 pub use self::FulfillmentErrorCode::*;
15 pub use self::Vtable::*;
16 pub use self::ObligationCauseCode::*;
17
18 use middle::mem_categorization::Typer;
19 use middle::subst;
20 use middle::ty::{self, Ty};
21 use middle::infer::InferCtxt;
22 use std::slice::Iter;
23 use std::rc::Rc;
24 use syntax::ast;
25 use syntax::codemap::{Span, DUMMY_SP};
26 use util::ppaux::{Repr, UserString};
27
28 pub use self::error_reporting::report_fulfillment_errors;
29 pub use self::error_reporting::suggest_new_overflow_limit;
30 pub use self::coherence::orphan_check;
31 pub use self::coherence::OrphanCheckErr;
32 pub use self::fulfill::{FulfillmentContext, RegionObligation};
33 pub use self::project::MismatchedProjectionTypes;
34 pub use self::project::normalize;
35 pub use self::project::Normalized;
36 pub use self::object_safety::is_object_safe;
37 pub use self::object_safety::object_safety_violations;
38 pub use self::object_safety::ObjectSafetyViolation;
39 pub use self::object_safety::MethodViolationCode;
40 pub use self::select::SelectionContext;
41 pub use self::select::SelectionCache;
42 pub use self::select::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch};
43 pub use self::select::{MethodMatchedData}; // intentionally don't export variants
44 pub use self::util::elaborate_predicates;
45 pub use self::util::get_vtable_index_of_object_method;
46 pub use self::util::trait_ref_for_builtin_bound;
47 pub use self::util::supertraits;
48 pub use self::util::Supertraits;
49 pub use self::util::transitive_bounds;
50 pub use self::util::upcast;
51
52 mod coherence;
53 mod error_reporting;
54 mod fulfill;
55 mod project;
56 mod object_safety;
57 mod select;
58 mod util;
59
60 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
61 /// which the vtable must be found.  The process of finding a vtable is
62 /// called "resolving" the `Obligation`. This process consists of
63 /// either identifying an `impl` (e.g., `impl Eq for int`) that
64 /// provides the required vtable, or else finding a bound that is in
65 /// scope. The eventual result is usually a `Selection` (defined below).
66 #[derive(Clone)]
67 pub struct Obligation<'tcx, T> {
68     pub cause: ObligationCause<'tcx>,
69     pub recursion_depth: uint,
70     pub predicate: T,
71 }
72
73 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
74 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
75
76 /// Why did we incur this obligation? Used for error reporting.
77 #[derive(Clone)]
78 pub struct ObligationCause<'tcx> {
79     pub span: Span,
80
81     // The id of the fn body that triggered this obligation. This is
82     // used for region obligations to determine the precise
83     // environment in which the region obligation should be evaluated
84     // (in particular, closures can add new assumptions). See the
85     // field `region_obligations` of the `FulfillmentContext` for more
86     // information.
87     pub body_id: ast::NodeId,
88
89     pub code: ObligationCauseCode<'tcx>
90 }
91
92 #[derive(Clone)]
93 pub enum ObligationCauseCode<'tcx> {
94     /// Not well classified or should be obvious from span.
95     MiscObligation,
96
97     /// In an impl of trait X for type Y, type Y must
98     /// also implement all supertraits of X.
99     ItemObligation(ast::DefId),
100
101     /// Obligation incurred due to an object cast.
102     ObjectCastObligation(/* Object type */ Ty<'tcx>),
103
104     /// Various cases where expressions must be sized/copy/etc:
105     AssignmentLhsSized,        // L = X implies that L is Sized
106     StructInitializerSized,    // S { ... } must be Sized
107     VariableType(ast::NodeId), // Type of each variable must be Sized
108     ReturnType,                // Return type must be Sized
109     RepeatVec,                 // [T,..n] --> T must be Copy
110
111     // Captures of variable the given id by a closure (span is the
112     // span of the closure)
113     ClosureCapture(ast::NodeId, Span, ty::BuiltinBound),
114
115     // Types of fields (other than the last) in a struct must be sized.
116     FieldSized,
117
118     // Only Sized types can be made into objects
119     ObjectSized,
120
121     // static items must have `Sync` type
122     SharedStatic,
123
124     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
125
126     ImplDerivedObligation(DerivedObligationCause<'tcx>),
127 }
128
129 #[derive(Clone)]
130 pub struct DerivedObligationCause<'tcx> {
131     /// The trait reference of the parent obligation that led to the
132     /// current obligation. Note that only trait obligations lead to
133     /// derived obligations, so we just store the trait reference here
134     /// directly.
135     parent_trait_ref: ty::PolyTraitRef<'tcx>,
136
137     /// The parent trait had this cause
138     parent_code: Rc<ObligationCauseCode<'tcx>>
139 }
140
141 pub type Obligations<'tcx, O> = subst::VecPerParamSpace<Obligation<'tcx, O>>;
142 pub type PredicateObligations<'tcx> = subst::VecPerParamSpace<PredicateObligation<'tcx>>;
143 pub type TraitObligations<'tcx> = subst::VecPerParamSpace<TraitObligation<'tcx>>;
144
145 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
146
147 #[derive(Clone,Show)]
148 pub enum SelectionError<'tcx> {
149     Unimplemented,
150     Overflow,
151     OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
152                                 ty::PolyTraitRef<'tcx>,
153                                 ty::type_err<'tcx>),
154 }
155
156 pub struct FulfillmentError<'tcx> {
157     pub obligation: PredicateObligation<'tcx>,
158     pub code: FulfillmentErrorCode<'tcx>
159 }
160
161 #[derive(Clone)]
162 pub enum FulfillmentErrorCode<'tcx> {
163     CodeSelectionError(SelectionError<'tcx>),
164     CodeProjectionError(MismatchedProjectionTypes<'tcx>),
165     CodeAmbiguity,
166 }
167
168 /// When performing resolution, it is typically the case that there
169 /// can be one of three outcomes:
170 ///
171 /// - `Ok(Some(r))`: success occurred with result `r`
172 /// - `Ok(None)`: could not definitely determine anything, usually due
173 ///   to inconclusive type inference.
174 /// - `Err(e)`: error `e` occurred
175 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
176
177 /// Given the successful resolution of an obligation, the `Vtable`
178 /// indicates where the vtable comes from. Note that while we call this
179 /// a "vtable", it does not necessarily indicate dynamic dispatch at
180 /// runtime. `Vtable` instances just tell the compiler where to find
181 /// methods, but in generic code those methods are typically statically
182 /// dispatched -- only when an object is constructed is a `Vtable`
183 /// instance reified into an actual vtable.
184 ///
185 /// For example, the vtable may be tied to a specific impl (case A),
186 /// or it may be relative to some bound that is in scope (case B).
187 ///
188 ///
189 /// ```
190 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
191 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
192 /// impl Clone for int { ... }             // Impl_3
193 ///
194 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
195 ///                 param: T,
196 ///                 mixed: Option<T>) {
197 ///
198 ///    // Case A: Vtable points at a specific impl. Only possible when
199 ///    // type is concretely known. If the impl itself has bounded
200 ///    // type parameters, Vtable will carry resolutions for those as well:
201 ///    concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
202 ///
203 ///    // Case B: Vtable must be provided by caller. This applies when
204 ///    // type is a type parameter.
205 ///    param.clone();    // VtableParam
206 ///
207 ///    // Case C: A mix of cases A and B.
208 ///    mixed.clone();    // Vtable(Impl_1, [VtableParam])
209 /// }
210 /// ```
211 ///
212 /// ### The type parameter `N`
213 ///
214 /// See explanation on `VtableImplData`.
215 #[derive(Show,Clone)]
216 pub enum Vtable<'tcx, N> {
217     /// Vtable identifying a particular impl.
218     VtableImpl(VtableImplData<'tcx, N>),
219
220     /// Successful resolution to an obligation provided by the caller
221     /// for some type parameter.
222     VtableParam,
223
224     /// Virtual calls through an object
225     VtableObject(VtableObjectData<'tcx>),
226
227     /// Successful resolution for a builtin trait.
228     VtableBuiltin(VtableBuiltinData<N>),
229
230     /// Vtable automatically generated for an unboxed closure. The def
231     /// ID is the ID of the closure expression. This is a `VtableImpl`
232     /// in spirit, but the impl is generated by the compiler and does
233     /// not appear in the source.
234     VtableUnboxedClosure(ast::DefId, subst::Substs<'tcx>),
235
236     /// Same as above, but for a fn pointer type with the given signature.
237     VtableFnPointer(ty::Ty<'tcx>),
238 }
239
240 /// Identifies a particular impl in the source, along with a set of
241 /// substitutions from the impl's type/lifetime parameters. The
242 /// `nested` vector corresponds to the nested obligations attached to
243 /// the impl's type parameters.
244 ///
245 /// The type parameter `N` indicates the type used for "nested
246 /// obligations" that are required by the impl. During type check, this
247 /// is `Obligation`, as one might expect. During trans, however, this
248 /// is `()`, because trans only requires a shallow resolution of an
249 /// impl, and nested obligations are satisfied later.
250 #[derive(Clone)]
251 pub struct VtableImplData<'tcx, N> {
252     pub impl_def_id: ast::DefId,
253     pub substs: subst::Substs<'tcx>,
254     pub nested: subst::VecPerParamSpace<N>
255 }
256
257 #[derive(Show,Clone)]
258 pub struct VtableBuiltinData<N> {
259     pub nested: subst::VecPerParamSpace<N>
260 }
261
262 /// A vtable for some object-safe trait `Foo` automatically derived
263 /// for the object type `Foo`.
264 #[derive(PartialEq,Eq,Clone)]
265 pub struct VtableObjectData<'tcx> {
266     pub object_ty: Ty<'tcx>,
267 }
268
269 /// True if there exist types that satisfy both of the two given impls.
270 pub fn overlapping_impls(infcx: &InferCtxt,
271                          impl1_def_id: ast::DefId,
272                          impl2_def_id: ast::DefId)
273                          -> bool
274 {
275     coherence::impl_can_satisfy(infcx, impl1_def_id, impl2_def_id) &&
276     coherence::impl_can_satisfy(infcx, impl2_def_id, impl1_def_id)
277 }
278
279 /// Creates predicate obligations from the generic bounds.
280 pub fn predicates_for_generics<'tcx>(tcx: &ty::ctxt<'tcx>,
281                                      cause: ObligationCause<'tcx>,
282                                      generic_bounds: &ty::GenericBounds<'tcx>)
283                                      -> PredicateObligations<'tcx>
284 {
285     util::predicates_for_generics(tcx, cause, 0, generic_bounds)
286 }
287
288 /// Determines whether the type `ty` is known to meet `bound` and
289 /// returns true if so. Returns false if `ty` either does not meet
290 /// `bound` or is not known to meet bound (note that this is
291 /// conservative towards *no impl*, which is the opposite of the
292 /// `evaluate` methods).
293 pub fn evaluate_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
294                                        typer: &ty::UnboxedClosureTyper<'tcx>,
295                                        ty: Ty<'tcx>,
296                                        bound: ty::BuiltinBound,
297                                        span: Span)
298                                        -> SelectionResult<'tcx, ()>
299 {
300     debug!("type_known_to_meet_builtin_bound(ty={}, bound={})",
301            ty.repr(infcx.tcx),
302            bound);
303
304     let mut fulfill_cx = FulfillmentContext::new();
305
306     // We can use a dummy node-id here because we won't pay any mind
307     // to region obligations that arise (there shouldn't really be any
308     // anyhow).
309     let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
310
311     fulfill_cx.register_builtin_bound(infcx, ty, bound, cause);
312
313     // Note: we only assume something is `Copy` if we can
314     // *definitively* show that it implements `Copy`. Otherwise,
315     // assume it is move; linear is always ok.
316     let result = match fulfill_cx.select_all_or_error(infcx, typer) {
317         Ok(()) => Ok(Some(())), // Success, we know it implements Copy.
318         Err(errors) => {
319             // Check if overflow occurred anywhere and propagate that.
320             if errors.iter().any(
321                 |err| match err.code { CodeSelectionError(Overflow) => true, _ => false })
322             {
323                 return Err(Overflow);
324             }
325
326             // Otherwise, if there were any hard errors, propagate an
327             // arbitrary one of those. If no hard errors at all,
328             // report ambiguity.
329             let sel_error =
330                 errors.iter()
331                       .filter_map(|err| {
332                           match err.code {
333                               CodeAmbiguity => None,
334                               CodeSelectionError(ref e) => Some(e.clone()),
335                               CodeProjectionError(_) => {
336                                   infcx.tcx.sess.span_bug(
337                                       span,
338                                       "projection error while selecting?")
339                               }
340                           }
341                       })
342                       .next();
343             match sel_error {
344                 None => { Ok(None) }
345                 Some(e) => { Err(e) }
346             }
347         }
348     };
349
350     debug!("type_known_to_meet_builtin_bound: ty={} bound={} result={}",
351            ty.repr(infcx.tcx),
352            bound,
353            result);
354
355     result
356 }
357
358 pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
359                                                  typer: &ty::UnboxedClosureTyper<'tcx>,
360                                                  ty: Ty<'tcx>,
361                                                  bound: ty::BuiltinBound,
362                                                  span: Span)
363                                                  -> bool
364 {
365     match evaluate_builtin_bound(infcx, typer, ty, bound, span) {
366         Ok(Some(())) => {
367             // definitely impl'd
368             true
369         }
370         Ok(None) => {
371             // ambiguous: if coherence check was successful, shouldn't
372             // happen, but we might have reported an error and been
373             // soldering on, so just treat this like not implemented
374             false
375         }
376         Err(Overflow) => {
377             infcx.tcx.sess.span_err(
378                 span,
379                 format!("overflow evaluating whether `{}` is `{}`",
380                         ty.user_string(infcx.tcx),
381                         bound.user_string(infcx.tcx))[]);
382             suggest_new_overflow_limit(infcx.tcx, span);
383             false
384         }
385         Err(_) => {
386             // other errors: not implemented.
387             false
388         }
389     }
390 }
391
392 impl<'tcx,O> Obligation<'tcx,O> {
393     pub fn new(cause: ObligationCause<'tcx>,
394                trait_ref: O)
395                -> Obligation<'tcx, O>
396     {
397         Obligation { cause: cause,
398                      recursion_depth: 0,
399                      predicate: trait_ref }
400     }
401
402     fn with_depth(cause: ObligationCause<'tcx>,
403                   recursion_depth: uint,
404                   trait_ref: O)
405                   -> Obligation<'tcx, O>
406     {
407         Obligation { cause: cause,
408                      recursion_depth: recursion_depth,
409                      predicate: trait_ref }
410     }
411
412     pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> {
413         Obligation::new(ObligationCause::misc(span, body_id), trait_ref)
414     }
415
416     pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
417         Obligation { cause: self.cause.clone(),
418                      recursion_depth: self.recursion_depth,
419                      predicate: value }
420     }
421 }
422
423 impl<'tcx> ObligationCause<'tcx> {
424     pub fn new(span: Span,
425                body_id: ast::NodeId,
426                code: ObligationCauseCode<'tcx>)
427                -> ObligationCause<'tcx> {
428         ObligationCause { span: span, body_id: body_id, code: code }
429     }
430
431     pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
432         ObligationCause { span: span, body_id: body_id, code: MiscObligation }
433     }
434
435     pub fn dummy() -> ObligationCause<'tcx> {
436         ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation }
437     }
438 }
439
440 impl<'tcx, N> Vtable<'tcx, N> {
441     pub fn iter_nested(&self) -> Iter<N> {
442         match *self {
443             VtableImpl(ref i) => i.iter_nested(),
444             VtableFnPointer(..) => (&[]).iter(),
445             VtableUnboxedClosure(..) => (&[]).iter(),
446             VtableParam => (&[]).iter(),
447             VtableObject(_) => (&[]).iter(),
448             VtableBuiltin(ref i) => i.iter_nested(),
449         }
450     }
451
452     pub fn map_nested<M, F>(&self, op: F) -> Vtable<'tcx, M> where F: FnMut(&N) -> M {
453         match *self {
454             VtableImpl(ref i) => VtableImpl(i.map_nested(op)),
455             VtableFnPointer(ref sig) => VtableFnPointer((*sig).clone()),
456             VtableUnboxedClosure(d, ref s) => VtableUnboxedClosure(d, s.clone()),
457             VtableParam => VtableParam,
458             VtableObject(ref p) => VtableObject(p.clone()),
459             VtableBuiltin(ref b) => VtableBuiltin(b.map_nested(op)),
460         }
461     }
462
463     pub fn map_move_nested<M, F>(self, op: F) -> Vtable<'tcx, M> where
464         F: FnMut(N) -> M,
465     {
466         match self {
467             VtableImpl(i) => VtableImpl(i.map_move_nested(op)),
468             VtableFnPointer(sig) => VtableFnPointer(sig),
469             VtableUnboxedClosure(d, s) => VtableUnboxedClosure(d, s),
470             VtableParam => VtableParam,
471             VtableObject(p) => VtableObject(p),
472             VtableBuiltin(no) => VtableBuiltin(no.map_move_nested(op)),
473         }
474     }
475 }
476
477 impl<'tcx, N> VtableImplData<'tcx, N> {
478     pub fn iter_nested(&self) -> Iter<N> {
479         self.nested.iter()
480     }
481
482     pub fn map_nested<M, F>(&self, op: F) -> VtableImplData<'tcx, M> where
483         F: FnMut(&N) -> M,
484     {
485         VtableImplData {
486             impl_def_id: self.impl_def_id,
487             substs: self.substs.clone(),
488             nested: self.nested.map(op)
489         }
490     }
491
492     pub fn map_move_nested<M, F>(self, op: F) -> VtableImplData<'tcx, M> where
493         F: FnMut(N) -> M,
494     {
495         let VtableImplData { impl_def_id, substs, nested } = self;
496         VtableImplData {
497             impl_def_id: impl_def_id,
498             substs: substs,
499             nested: nested.map_move(op)
500         }
501     }
502 }
503
504 impl<N> VtableBuiltinData<N> {
505     pub fn iter_nested(&self) -> Iter<N> {
506         self.nested.iter()
507     }
508
509     pub fn map_nested<M, F>(&self, op: F) -> VtableBuiltinData<M> where F: FnMut(&N) -> M {
510         VtableBuiltinData {
511             nested: self.nested.map(op)
512         }
513     }
514
515     pub fn map_move_nested<M, F>(self, op: F) -> VtableBuiltinData<M> where
516         F: FnMut(N) -> M,
517     {
518         VtableBuiltinData {
519             nested: self.nested.map_move(op)
520         }
521     }
522 }
523
524 impl<'tcx> FulfillmentError<'tcx> {
525     fn new(obligation: PredicateObligation<'tcx>,
526            code: FulfillmentErrorCode<'tcx>)
527            -> FulfillmentError<'tcx>
528     {
529         FulfillmentError { obligation: obligation, code: code }
530     }
531
532     pub fn is_overflow(&self) -> bool {
533         match self.code {
534             CodeAmbiguity => false,
535             CodeSelectionError(Overflow) => true,
536             CodeSelectionError(_) => false,
537             CodeProjectionError(_) => false,
538         }
539     }
540 }
541
542 impl<'tcx> TraitObligation<'tcx> {
543     fn self_ty(&self) -> Ty<'tcx> {
544         self.predicate.0.self_ty()
545     }
546 }