2 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
3 // file at the top-level directory of this distribution and at
4 // http://rust-lang.org/COPYRIGHT.
6 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9 // option. This file may not be copied, modified, or distributed
10 // except according to those terms.
13 use middle::subst::{ParamSpace, Subst, Substs, VecPerParamSpace};
14 use middle::typeck::infer::InferCtxt;
16 use std::collections::HashSet;
20 use syntax::codemap::Span;
21 use util::ppaux::Repr;
23 use super::{Obligation, ObligationCause, VtableImpl, VtableParam, VtableParamData, VtableImplData};
25 ///////////////////////////////////////////////////////////////////////////
26 // Supertrait iterator
28 pub struct Supertraits<'cx, 'tcx:'cx> {
29 tcx: &'cx ty::ctxt<'tcx>,
30 stack: Vec<SupertraitEntry>,
31 visited: HashSet<Rc<ty::TraitRef>>,
34 struct SupertraitEntry {
36 supertraits: Vec<Rc<ty::TraitRef>>,
39 pub fn supertraits<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
40 trait_ref: Rc<ty::TraitRef>)
41 -> Supertraits<'cx, 'tcx>
44 * Returns an iterator over the trait reference `T` and all of its
45 * supertrait references. May contain duplicates. In general
46 * the ordering is not defined.
52 * trait Bar : Foo { ... }
53 * trait Baz : Bar+Foo { ... }
56 * `supertraits(Baz)` yields `[Baz, Bar, Foo, Foo]` in some order.
59 transitive_bounds(tcx, [trait_ref])
62 pub fn transitive_bounds<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
63 bounds: &[Rc<ty::TraitRef>])
64 -> Supertraits<'cx, 'tcx>
66 let bounds = Vec::from_fn(bounds.len(), |i| bounds[i].clone());
68 let visited: HashSet<Rc<ty::TraitRef>> =
70 .map(|b| (*b).clone())
73 let entry = SupertraitEntry { position: 0, supertraits: bounds };
74 Supertraits { tcx: tcx, stack: vec![entry], visited: visited }
77 impl<'cx, 'tcx> Supertraits<'cx, 'tcx> {
78 fn push(&mut self, trait_ref: &ty::TraitRef) {
79 let ty::ParamBounds { builtin_bounds, mut trait_bounds, .. } =
80 ty::bounds_for_trait_ref(self.tcx, trait_ref);
81 for builtin_bound in builtin_bounds.iter() {
82 let bound_trait_ref = trait_ref_for_builtin_bound(self.tcx,
85 trait_bounds.push(bound_trait_ref);
88 // Only keep those bounds that we haven't already seen. This
89 // is necessary to prevent infinite recursion in some cases.
90 // One common case is when people define `trait Sized { }`
91 // rather than `trait Sized for Sized? { }`.
92 trait_bounds.retain(|r| self.visited.insert((*r).clone()));
94 let entry = SupertraitEntry { position: 0, supertraits: trait_bounds };
95 self.stack.push(entry);
98 pub fn indices(&self) -> Vec<uint> {
100 * Returns the path taken through the trait supertraits to
101 * reach the current point.
104 self.stack.iter().map(|e| e.position).collect()
108 impl<'cx, 'tcx> Iterator<Rc<ty::TraitRef>> for Supertraits<'cx, 'tcx> {
109 fn next(&mut self) -> Option<Rc<ty::TraitRef>> {
111 // Extract next item from top-most stack frame, if any.
112 let next_trait = match self.stack.mut_last() {
114 // No more stack frames. Done.
118 let p = entry.position;
119 if p < entry.supertraits.len() {
120 // Still more supertraits left in the top stack frame.
124 (*entry.supertraits.get(p)).clone();
133 Some(next_trait) => {
134 self.push(&*next_trait);
135 return Some(next_trait);
139 // Top stack frame is exhausted, pop it.
147 // determine the `self` type, using fresh variables for all variables
148 // declared on the impl declaration e.g., `impl<A,B> for ~[(A,B)]`
149 // would return ($0, $1) where $0 and $1 are freshly instantiated type
151 pub fn fresh_substs_for_impl(infcx: &InferCtxt,
153 impl_def_id: ast::DefId)
157 let impl_generics = ty::lookup_item_type(tcx, impl_def_id).generics;
158 infcx.fresh_substs_for_generics(span, &impl_generics)
161 impl<N> fmt::Show for VtableImplData<N> {
162 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
163 write!(f, "VtableImpl({})", self.impl_def_id)
167 impl fmt::Show for VtableParamData {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169 write!(f, "VtableParam(...)")
173 pub fn obligations_for_generics(tcx: &ty::ctxt,
174 cause: ObligationCause,
175 recursion_depth: uint,
176 generics: &ty::Generics,
178 -> VecPerParamSpace<Obligation>
180 /*! See `super::obligations_for_generics` */
182 debug!("obligations_for_generics(generics={}, substs={})",
183 generics.repr(tcx), substs.repr(tcx));
185 let mut obligations = VecPerParamSpace::empty();
187 for def in generics.types.iter() {
188 push_obligations_for_param_bounds(tcx,
198 debug!("obligations() ==> {}", obligations.repr(tcx));
203 fn push_obligations_for_param_bounds(
205 cause: ObligationCause,
206 recursion_depth: uint,
207 space: subst::ParamSpace,
209 param_bounds: &ty::ParamBounds,
210 param_substs: &Substs,
211 obligations: &mut VecPerParamSpace<Obligation>)
213 let param_ty = *param_substs.types.get(space, index);
215 for builtin_bound in param_bounds.builtin_bounds.iter() {
218 obligation_for_builtin_bound(tcx,
225 for bound_trait_ref in param_bounds.trait_bounds.iter() {
226 let bound_trait_ref = bound_trait_ref.subst(tcx, param_substs);
229 Obligation { cause: cause,
230 recursion_depth: recursion_depth,
231 trait_ref: bound_trait_ref });
235 pub fn trait_ref_for_builtin_bound(
237 builtin_bound: ty::BuiltinBound,
241 match tcx.lang_items.from_builtin_kind(builtin_bound) {
243 Rc::new(ty::TraitRef {
245 substs: Substs::empty().with_self_ty(param_ty)
249 tcx.sess.bug(e.as_slice());
254 pub fn obligation_for_builtin_bound(
256 cause: ObligationCause,
257 builtin_bound: ty::BuiltinBound,
258 recursion_depth: uint,
262 let trait_ref = trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty);
265 recursion_depth: recursion_depth,
270 pub fn search_trait_and_supertraits_from_bound(tcx: &ty::ctxt,
271 caller_bound: Rc<ty::TraitRef>,
272 test: |ast::DefId| -> bool)
273 -> Option<VtableParamData>
276 * Starting from a caller obligation `caller_bound` (which has
277 * coordinates `space`/`i` in the list of caller obligations),
278 * search through the trait and supertraits to find one where
279 * `test(d)` is true, where `d` is the def-id of the
280 * trait/supertrait. If any is found, return `Some(p)` where `p`
281 * is the path to that trait/supertrait. Else `None`.
284 for bound in transitive_bounds(tcx, &[caller_bound]) {
285 if test(bound.def_id) {
286 let vtable_param = VtableParamData { bound: bound };
287 return Some(vtable_param);
294 impl Repr for super::Obligation {
295 fn repr(&self, tcx: &ty::ctxt) -> String {
296 format!("Obligation(trait_ref={},depth={})",
297 self.trait_ref.repr(tcx),
298 self.recursion_depth)
302 impl<N:Repr> Repr for super::Vtable<N> {
303 fn repr(&self, tcx: &ty::ctxt) -> String {
305 super::VtableImpl(ref v) =>
308 super::VtableUnboxedClosure(ref d) =>
309 format!("VtableUnboxedClosure({})",
312 super::VtableParam(ref v) =>
313 format!("VtableParam({})", v.repr(tcx)),
315 super::VtableBuiltin =>
321 impl<N:Repr> Repr for super::VtableImplData<N> {
322 fn repr(&self, tcx: &ty::ctxt) -> String {
323 format!("VtableImpl(impl_def_id={}, substs={}, nested={})",
324 self.impl_def_id.repr(tcx),
325 self.substs.repr(tcx),
326 self.nested.repr(tcx))
330 impl Repr for super::VtableParamData {
331 fn repr(&self, tcx: &ty::ctxt) -> String {
332 format!("VtableParam(bound={})",
333 self.bound.repr(tcx))
337 impl Repr for super::SelectionError {
338 fn repr(&self, tcx: &ty::ctxt) -> String {
340 super::Unimplemented =>
341 format!("Unimplemented"),
346 super::OutputTypeParameterMismatch(ref t, ref e) =>
347 format!("OutputTypeParameterMismatch({}, {})",
354 impl Repr for super::FulfillmentError {
355 fn repr(&self, tcx: &ty::ctxt) -> String {
356 format!("FulfillmentError({},{})",
357 self.obligation.repr(tcx),
362 impl Repr for super::FulfillmentErrorCode {
363 fn repr(&self, tcx: &ty::ctxt) -> String {
365 super::CodeSelectionError(ref o) => o.repr(tcx),
366 super::CodeAmbiguity => format!("Ambiguity")
371 impl fmt::Show for super::FulfillmentErrorCode {
372 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
374 super::CodeSelectionError(ref e) => write!(f, "{}", e),
375 super::CodeAmbiguity => write!(f, "Ambiguity")
380 impl Repr for ty::type_err {
381 fn repr(&self, tcx: &ty::ctxt) -> String {
382 ty::type_err_to_str(tcx, self)