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