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.
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.
11 use middle::subst::Substs;
12 use middle::infer::InferCtxt;
13 use middle::ty::{self, Ty, ToPredicate, ToPolyTraitRef};
16 use syntax::codemap::Span;
17 use util::common::ErrorReported;
18 use util::nodemap::FnvHashSet;
20 use super::{Obligation, ObligationCause, PredicateObligation,
21 VtableImpl, VtableParam, VtableImplData, VtableDefaultImplData};
23 struct PredicateSet<'a,'tcx:'a> {
24 tcx: &'a ty::ctxt<'tcx>,
25 set: FnvHashSet<ty::Predicate<'tcx>>,
28 impl<'a,'tcx> PredicateSet<'a,'tcx> {
29 fn new(tcx: &'a ty::ctxt<'tcx>) -> PredicateSet<'a,'tcx> {
30 PredicateSet { tcx: tcx, set: FnvHashSet() }
33 fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
34 // We have to be careful here because we want
36 // for<'a> Foo<&'a int>
40 // for<'b> Foo<&'b int>
42 // to be considered equivalent. So normalize all late-bound
43 // regions before we throw things into the underlying set.
44 let normalized_pred = match *pred {
45 ty::Predicate::Trait(ref data) =>
46 ty::Predicate::Trait(self.tcx.anonymize_late_bound_regions(data)),
48 ty::Predicate::Equate(ref data) =>
49 ty::Predicate::Equate(self.tcx.anonymize_late_bound_regions(data)),
51 ty::Predicate::RegionOutlives(ref data) =>
52 ty::Predicate::RegionOutlives(self.tcx.anonymize_late_bound_regions(data)),
54 ty::Predicate::TypeOutlives(ref data) =>
55 ty::Predicate::TypeOutlives(self.tcx.anonymize_late_bound_regions(data)),
57 ty::Predicate::Projection(ref data) =>
58 ty::Predicate::Projection(self.tcx.anonymize_late_bound_regions(data)),
60 self.set.insert(normalized_pred)
64 ///////////////////////////////////////////////////////////////////////////
65 // `Elaboration` iterator
66 ///////////////////////////////////////////////////////////////////////////
68 /// "Elaboration" is the process of identifying all the predicates that
69 /// are implied by a source predicate. Currently this basically means
70 /// walking the "supertraits" and other similar assumptions. For
71 /// example, if we know that `T : Ord`, the elaborator would deduce
72 /// that `T : PartialOrd` holds as well. Similarly, if we have `trait
73 /// Foo : 'static`, and we know that `T : Foo`, then we know that `T :
75 pub struct Elaborator<'cx, 'tcx:'cx> {
76 tcx: &'cx ty::ctxt<'tcx>,
77 stack: Vec<ty::Predicate<'tcx>>,
78 visited: PredicateSet<'cx,'tcx>,
81 pub fn elaborate_trait_ref<'cx, 'tcx>(
82 tcx: &'cx ty::ctxt<'tcx>,
83 trait_ref: ty::PolyTraitRef<'tcx>)
84 -> Elaborator<'cx, 'tcx>
86 elaborate_predicates(tcx, vec![trait_ref.to_predicate()])
89 pub fn elaborate_trait_refs<'cx, 'tcx>(
90 tcx: &'cx ty::ctxt<'tcx>,
91 trait_refs: &[ty::PolyTraitRef<'tcx>])
92 -> Elaborator<'cx, 'tcx>
94 let predicates = trait_refs.iter()
95 .map(|trait_ref| trait_ref.to_predicate())
97 elaborate_predicates(tcx, predicates)
100 pub fn elaborate_predicates<'cx, 'tcx>(
101 tcx: &'cx ty::ctxt<'tcx>,
102 mut predicates: Vec<ty::Predicate<'tcx>>)
103 -> Elaborator<'cx, 'tcx>
105 let mut visited = PredicateSet::new(tcx);
106 predicates.retain(|pred| visited.insert(pred));
107 Elaborator { tcx: tcx, stack: predicates, visited: visited }
110 impl<'cx, 'tcx> Elaborator<'cx, 'tcx> {
111 pub fn filter_to_traits(self) -> FilterToTraits<Elaborator<'cx, 'tcx>> {
112 FilterToTraits::new(self)
115 fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
117 ty::Predicate::Trait(ref data) => {
118 // Predicates declared on the trait.
119 let predicates = self.tcx.lookup_super_predicates(data.def_id());
121 let mut predicates: Vec<_> =
122 predicates.predicates
124 .map(|p| p.subst_supertrait(self.tcx, &data.to_poly_trait_ref()))
127 debug!("super_predicates: data={:?} predicates={:?}",
130 // Only keep those bounds that we haven't already
131 // seen. This is necessary to prevent infinite
132 // recursion in some cases. One common case is when
133 // people define `trait Sized: Sized { }` rather than `trait
135 predicates.retain(|r| self.visited.insert(r));
137 self.stack.extend(predicates);
139 ty::Predicate::Equate(..) => {
140 // Currently, we do not "elaborate" predicates like
141 // `X == Y`, though conceivably we might. For example,
142 // `&X == &Y` implies that `X == Y`.
144 ty::Predicate::Projection(..) => {
145 // Nothing to elaborate in a projection predicate.
147 ty::Predicate::RegionOutlives(..) |
148 ty::Predicate::TypeOutlives(..) => {
149 // Currently, we do not "elaborate" predicates like
150 // `'a : 'b` or `T : 'a`. We could conceivably do
151 // more here. For example,
159 // and we could get even more if we took WF
160 // constraints into account. For example,
173 impl<'cx, 'tcx> Iterator for Elaborator<'cx, 'tcx> {
174 type Item = ty::Predicate<'tcx>;
176 fn next(&mut self) -> Option<ty::Predicate<'tcx>> {
177 // Extract next item from top-most stack frame, if any.
178 let next_predicate = match self.stack.pop() {
179 Some(predicate) => predicate,
181 // No more stack frames. Done.
185 self.push(&next_predicate);
186 return Some(next_predicate);
190 ///////////////////////////////////////////////////////////////////////////
191 // Supertrait iterator
192 ///////////////////////////////////////////////////////////////////////////
194 pub type Supertraits<'cx, 'tcx> = FilterToTraits<Elaborator<'cx, 'tcx>>;
196 pub fn supertraits<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
197 trait_ref: ty::PolyTraitRef<'tcx>)
198 -> Supertraits<'cx, 'tcx>
200 elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
203 pub fn transitive_bounds<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
204 bounds: &[ty::PolyTraitRef<'tcx>])
205 -> Supertraits<'cx, 'tcx>
207 elaborate_trait_refs(tcx, bounds).filter_to_traits()
210 ///////////////////////////////////////////////////////////////////////////
211 // Iterator over def-ids of supertraits
213 pub struct SupertraitDefIds<'cx, 'tcx:'cx> {
214 tcx: &'cx ty::ctxt<'tcx>,
215 stack: Vec<ast::DefId>,
216 visited: FnvHashSet<ast::DefId>,
219 pub fn supertrait_def_ids<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
220 trait_def_id: ast::DefId)
221 -> SupertraitDefIds<'cx, 'tcx>
225 stack: vec![trait_def_id],
226 visited: Some(trait_def_id).into_iter().collect(),
230 impl<'cx, 'tcx> Iterator for SupertraitDefIds<'cx, 'tcx> {
231 type Item = ast::DefId;
233 fn next(&mut self) -> Option<ast::DefId> {
234 let def_id = match self.stack.pop() {
235 Some(def_id) => def_id,
236 None => { return None; }
239 let predicates = self.tcx.lookup_super_predicates(def_id);
240 let visited = &mut self.visited;
242 predicates.predicates
244 .filter_map(|p| p.to_opt_poly_trait_ref())
246 .filter(|&super_def_id| visited.insert(super_def_id)));
251 ///////////////////////////////////////////////////////////////////////////
253 ///////////////////////////////////////////////////////////////////////////
255 /// A filter around an iterator of predicates that makes it yield up
256 /// just trait references.
257 pub struct FilterToTraits<I> {
261 impl<I> FilterToTraits<I> {
262 fn new(base: I) -> FilterToTraits<I> {
263 FilterToTraits { base_iterator: base }
267 impl<'tcx,I:Iterator<Item=ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
268 type Item = ty::PolyTraitRef<'tcx>;
270 fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
272 match self.base_iterator.next() {
276 Some(ty::Predicate::Trait(data)) => {
277 return Some(data.to_poly_trait_ref());
286 ///////////////////////////////////////////////////////////////////////////
288 ///////////////////////////////////////////////////////////////////////////
290 // determine the `self` type, using fresh variables for all variables
291 // declared on the impl declaration e.g., `impl<A,B> for Box<[(A,B)]>`
292 // would return ($0, $1) where $0 and $1 are freshly instantiated type
294 pub fn fresh_type_vars_for_impl<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
296 impl_def_id: ast::DefId)
300 let impl_generics = tcx.lookup_item_type(impl_def_id).generics;
301 infcx.fresh_substs_for_generics(span, &impl_generics)
304 /// See `super::obligations_for_generics`
305 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
306 recursion_depth: usize,
307 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
308 -> Vec<PredicateObligation<'tcx>>
310 debug!("predicates_for_generics(generic_bounds={:?})",
313 generic_bounds.predicates.iter().map(|predicate| {
314 Obligation { cause: cause.clone(),
315 recursion_depth: recursion_depth,
316 predicate: predicate.clone() }
320 pub fn trait_ref_for_builtin_bound<'tcx>(
321 tcx: &ty::ctxt<'tcx>,
322 builtin_bound: ty::BuiltinBound,
324 -> Result<ty::TraitRef<'tcx>, ErrorReported>
326 match tcx.lang_items.from_builtin_kind(builtin_bound) {
330 substs: tcx.mk_substs(Substs::empty().with_self_ty(param_ty))
341 pub fn predicate_for_trait_ref<'tcx>(
342 cause: ObligationCause<'tcx>,
343 trait_ref: ty::TraitRef<'tcx>,
344 recursion_depth: usize)
345 -> PredicateObligation<'tcx>
349 recursion_depth: recursion_depth,
350 predicate: trait_ref.to_predicate(),
354 pub fn predicate_for_trait_def<'tcx>(
355 tcx: &ty::ctxt<'tcx>,
356 cause: ObligationCause<'tcx>,
357 trait_def_id: ast::DefId,
358 recursion_depth: usize,
360 ty_params: Vec<Ty<'tcx>>)
361 -> PredicateObligation<'tcx>
363 let trait_ref = ty::TraitRef {
364 def_id: trait_def_id,
365 substs: tcx.mk_substs(Substs::new_trait(ty_params, vec![], param_ty))
367 predicate_for_trait_ref(cause, trait_ref, recursion_depth)
370 pub fn predicate_for_builtin_bound<'tcx>(
371 tcx: &ty::ctxt<'tcx>,
372 cause: ObligationCause<'tcx>,
373 builtin_bound: ty::BuiltinBound,
374 recursion_depth: usize,
376 -> Result<PredicateObligation<'tcx>, ErrorReported>
378 let trait_ref = try!(trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty));
379 Ok(predicate_for_trait_ref(cause, trait_ref, recursion_depth))
382 /// Cast a trait reference into a reference to one of its super
383 /// traits; returns `None` if `target_trait_def_id` is not a
385 pub fn upcast<'tcx>(tcx: &ty::ctxt<'tcx>,
386 source_trait_ref: ty::PolyTraitRef<'tcx>,
387 target_trait_def_id: ast::DefId)
388 -> Vec<ty::PolyTraitRef<'tcx>>
390 if source_trait_ref.def_id() == target_trait_def_id {
391 return vec![source_trait_ref]; // shorcut the most common case
394 supertraits(tcx, source_trait_ref)
395 .filter(|r| r.def_id() == target_trait_def_id)
399 /// Given an trait `trait_ref`, returns the number of vtable entries
400 /// that come from `trait_ref`, excluding its supertraits. Used in
401 /// computing the vtable base for an upcast trait of a trait object.
402 pub fn count_own_vtable_entries<'tcx>(tcx: &ty::ctxt<'tcx>,
403 trait_ref: ty::PolyTraitRef<'tcx>)
406 // Count number of methods and add them to the total offset.
407 // Skip over associated types and constants.
408 for trait_item in &tcx.trait_items(trait_ref.def_id())[..] {
409 if let ty::MethodTraitItem(_) = *trait_item {
416 /// Given an upcast trait object described by `object`, returns the
417 /// index of the method `method_def_id` (which should be part of
418 /// `object.upcast_trait_ref`) within the vtable for `object`.
419 pub fn get_vtable_index_of_object_method<'tcx>(tcx: &ty::ctxt<'tcx>,
420 object: &super::VtableObjectData<'tcx>,
421 method_def_id: ast::DefId) -> usize {
422 // Count number of methods preceding the one we are selecting and
423 // add them to the total offset.
424 // Skip over associated types and constants.
425 let mut entries = object.vtable_base;
426 for trait_item in &tcx.trait_items(object.upcast_trait_ref.def_id())[..] {
427 if trait_item.def_id() == method_def_id {
428 // The item with the ID we were given really ought to be a method.
429 assert!(match *trait_item {
430 ty::MethodTraitItem(_) => true,
436 if let ty::MethodTraitItem(_) = *trait_item {
441 tcx.sess.bug(&format!("get_vtable_index_of_object_method: {:?} was not found",
445 pub enum TupleArgumentsFlag { Yes, No }
447 pub fn closure_trait_ref_and_return_type<'tcx>(
448 tcx: &ty::ctxt<'tcx>,
449 fn_trait_def_id: ast::DefId,
451 sig: &ty::PolyFnSig<'tcx>,
452 tuple_arguments: TupleArgumentsFlag)
453 -> ty::Binder<(ty::TraitRef<'tcx>, Ty<'tcx>)>
455 let arguments_tuple = match tuple_arguments {
456 TupleArgumentsFlag::No => sig.0.inputs[0],
457 TupleArgumentsFlag::Yes => tcx.mk_tup(sig.0.inputs.to_vec()),
459 let trait_substs = Substs::new_trait(vec![arguments_tuple], vec![], self_ty);
460 let trait_ref = ty::TraitRef {
461 def_id: fn_trait_def_id,
462 substs: tcx.mk_substs(trait_substs),
464 ty::Binder((trait_ref, sig.0.output.unwrap_or(tcx.mk_nil())))
467 impl<'tcx,O:fmt::Debug> fmt::Debug for super::Obligation<'tcx, O> {
468 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
469 write!(f, "Obligation(predicate={:?},depth={})",
471 self.recursion_depth)
475 impl<'tcx, N:fmt::Debug> fmt::Debug for super::Vtable<'tcx, N> {
476 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
478 super::VtableImpl(ref v) =>
479 write!(f, "{:?}", v),
481 super::VtableDefaultImpl(ref t) =>
482 write!(f, "{:?}", t),
484 super::VtableClosure(ref d) =>
485 write!(f, "{:?}", d),
487 super::VtableFnPointer(ref d) =>
488 write!(f, "VtableFnPointer({:?})", d),
490 super::VtableObject(ref d) =>
491 write!(f, "{:?}", d),
493 super::VtableParam(ref n) =>
494 write!(f, "VtableParam({:?})", n),
496 super::VtableBuiltin(ref d) =>
502 impl<'tcx, N:fmt::Debug> fmt::Debug for super::VtableImplData<'tcx, N> {
503 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
504 write!(f, "VtableImpl(impl_def_id={:?}, substs={:?}, nested={:?})",
511 impl<'tcx, N:fmt::Debug> fmt::Debug for super::VtableClosureData<'tcx, N> {
512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
513 write!(f, "VtableClosure(closure_def_id={:?}, substs={:?}, nested={:?})",
520 impl<'tcx, N:fmt::Debug> fmt::Debug for super::VtableBuiltinData<N> {
521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522 write!(f, "VtableBuiltin(nested={:?})", self.nested)
526 impl<'tcx, N:fmt::Debug> fmt::Debug for super::VtableDefaultImplData<N> {
527 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
528 write!(f, "VtableDefaultImplData(trait_def_id={:?}, nested={:?})",
534 impl<'tcx> fmt::Debug for super::VtableObjectData<'tcx> {
535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
536 write!(f, "VtableObject(upcast={:?}, vtable_base={})",
537 self.upcast_trait_ref,
542 impl<'tcx> fmt::Debug for super::FulfillmentError<'tcx> {
543 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
544 write!(f, "FulfillmentError({:?},{:?})",
550 impl<'tcx> fmt::Debug for super::FulfillmentErrorCode<'tcx> {
551 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
553 super::CodeSelectionError(ref e) => write!(f, "{:?}", e),
554 super::CodeProjectionError(ref e) => write!(f, "{:?}", e),
555 super::CodeAmbiguity => write!(f, "Ambiguity")
560 impl<'tcx> fmt::Debug for super::MismatchedProjectionTypes<'tcx> {
561 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
562 write!(f, "MismatchedProjectionTypes({:?})", self.err)