1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398

// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use middle::subst;
use middle::subst::{ParamSpace, Substs, VecPerParamSpace};
use middle::typeck::infer::InferCtxt;
use middle::ty::{mod, Ty};
use std::collections::HashSet;
use std::fmt;
use std::rc::Rc;
use syntax::ast;
use syntax::codemap::Span;
use util::common::ErrorReported;
use util::ppaux::Repr;

use super::{Obligation, ObligationCause, VtableImpl,
            VtableParam, VtableParamData, VtableImplData};

///////////////////////////////////////////////////////////////////////////
// Supertrait iterator

pub struct Supertraits<'cx, 'tcx:'cx> {
    tcx: &'cx ty::ctxt<'tcx>,
    stack: Vec<SupertraitEntry<'tcx>>,
    visited: HashSet<Rc<ty::TraitRef<'tcx>>>,
}

struct SupertraitEntry<'tcx> {
    position: uint,
    supertraits: Vec<Rc<ty::TraitRef<'tcx>>>,
}

pub fn supertraits<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
                              trait_ref: Rc<ty::TraitRef<'tcx>>)
                              -> Supertraits<'cx, 'tcx>
{
    /*!
     * Returns an iterator over the trait reference `T` and all of its
     * supertrait references. May contain duplicates. In general
     * the ordering is not defined.
     *
     * Example:
     *
     * ```
     * trait Foo { ... }
     * trait Bar : Foo { ... }
     * trait Baz : Bar+Foo { ... }
     * ```
     *
     * `supertraits(Baz)` yields `[Baz, Bar, Foo, Foo]` in some order.
     */

    transitive_bounds(tcx, &[trait_ref])
}

pub fn transitive_bounds<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
                                    bounds: &[Rc<ty::TraitRef<'tcx>>])
                                    -> Supertraits<'cx, 'tcx>
{
    let bounds = Vec::from_fn(bounds.len(), |i| bounds[i].clone());

    let visited: HashSet<Rc<ty::TraitRef>> =
        bounds.iter()
              .map(|b| (*b).clone())
              .collect();

    let entry = SupertraitEntry { position: 0, supertraits: bounds };
    Supertraits { tcx: tcx, stack: vec![entry], visited: visited }
}

impl<'cx, 'tcx> Supertraits<'cx, 'tcx> {
    fn push(&mut self, trait_ref: &ty::TraitRef<'tcx>) {
        let ty::ParamBounds { builtin_bounds, mut trait_bounds, .. } =
            ty::bounds_for_trait_ref(self.tcx, trait_ref);
        for builtin_bound in builtin_bounds.iter() {
            let bound_trait_ref = trait_ref_for_builtin_bound(self.tcx,
                                                              builtin_bound,
                                                              trait_ref.self_ty());
            bound_trait_ref.map(|trait_ref| trait_bounds.push(trait_ref));
        }

        // Only keep those bounds that we haven't already seen.  This
        // is necessary to prevent infinite recursion in some cases.
        // One common case is when people define `trait Sized { }`
        // rather than `trait Sized for Sized? { }`.
        trait_bounds.retain(|r| self.visited.insert((*r).clone()));

        let entry = SupertraitEntry { position: 0, supertraits: trait_bounds };
        self.stack.push(entry);
    }

    pub fn indices(&self) -> Vec<uint> {
        /*!
         * Returns the path taken through the trait supertraits to
         * reach the current point.
         */

        self.stack.iter().map(|e| e.position).collect()
    }
}

impl<'cx, 'tcx> Iterator<Rc<ty::TraitRef<'tcx>>> for Supertraits<'cx, 'tcx> {
    fn next(&mut self) -> Option<Rc<ty::TraitRef<'tcx>>> {
        loop {
            // Extract next item from top-most stack frame, if any.
            let next_trait = match self.stack.last_mut() {
                None => {
                    // No more stack frames. Done.
                    return None;
                }
                Some(entry) => {
                    let p = entry.position;
                    if p < entry.supertraits.len() {
                        // Still more supertraits left in the top stack frame.
                        entry.position += 1;

                        let next_trait = entry.supertraits[p].clone();
                        Some(next_trait)
                    } else {
                        None
                    }
                }
            };

            match next_trait {
                Some(next_trait) => {
                    self.push(&*next_trait);
                    return Some(next_trait);
                }

                None => {
                    // Top stack frame is exhausted, pop it.
                    self.stack.pop();
                }
            }
        }
    }
}

// determine the `self` type, using fresh variables for all variables
// declared on the impl declaration e.g., `impl<A,B> for ~[(A,B)]`
// would return ($0, $1) where $0 and $1 are freshly instantiated type
// variables.
pub fn fresh_substs_for_impl<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
                                       span: Span,
                                       impl_def_id: ast::DefId)
                                       -> Substs<'tcx>
{
    let tcx = infcx.tcx;
    let impl_generics = ty::lookup_item_type(tcx, impl_def_id).generics;
    infcx.fresh_substs_for_generics(span, &impl_generics)
}

impl<'tcx, N> fmt::Show for VtableImplData<'tcx, N> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "VtableImpl({})", self.impl_def_id)
    }
}

impl<'tcx> fmt::Show for VtableParamData<'tcx> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "VtableParam(...)")
    }
}

pub fn obligations_for_generics<'tcx>(tcx: &ty::ctxt<'tcx>,
                                      cause: ObligationCause<'tcx>,
                                      recursion_depth: uint,
                                      generic_bounds: &ty::GenericBounds<'tcx>,
                                      type_substs: &VecPerParamSpace<Ty<'tcx>>)
                                      -> VecPerParamSpace<Obligation<'tcx>>
{
    /*! See `super::obligations_for_generics` */

    debug!("obligations_for_generics(generic_bounds={}, type_substs={})",
           generic_bounds.repr(tcx), type_substs.repr(tcx));

    let mut obligations = VecPerParamSpace::empty();

    for (space, index, bounds) in generic_bounds.types.iter_enumerated() {
        push_obligations_for_param_bounds(tcx,
                                          cause,
                                          recursion_depth,
                                          space,
                                          index,
                                          bounds,
                                          type_substs,
                                          &mut obligations);
    }

    debug!("obligations() ==> {}", obligations.repr(tcx));

    return obligations;
}

fn push_obligations_for_param_bounds<'tcx>(
    tcx: &ty::ctxt<'tcx>,
    cause: ObligationCause<'tcx>,
    recursion_depth: uint,
    space: subst::ParamSpace,
    index: uint,
    param_bounds: &ty::ParamBounds<'tcx>,
    param_type_substs: &VecPerParamSpace<Ty<'tcx>>,
    obligations: &mut VecPerParamSpace<Obligation<'tcx>>)
{
    let param_ty = *param_type_substs.get(space, index);
    for builtin_bound in param_bounds.builtin_bounds.iter() {
        let obligation = obligation_for_builtin_bound(tcx,
                                                      cause,
                                                      builtin_bound,
                                                      recursion_depth,
                                                      param_ty);
        match obligation {
            Ok(ob) => obligations.push(space, ob),
            _ => {}
        }
    }

    for bound_trait_ref in param_bounds.trait_bounds.iter() {
        obligations.push(
            space,
            Obligation { cause: cause,
                         recursion_depth: recursion_depth,
                         trait_ref: (*bound_trait_ref).clone() });
    }
}

pub fn trait_ref_for_builtin_bound<'tcx>(
    tcx: &ty::ctxt<'tcx>,
    builtin_bound: ty::BuiltinBound,
    param_ty: Ty<'tcx>)
    -> Option<Rc<ty::TraitRef<'tcx>>>
{
    match tcx.lang_items.from_builtin_kind(builtin_bound) {
        Ok(def_id) => {
            Some(Rc::new(ty::TraitRef {
                def_id: def_id,
                substs: Substs::empty().with_self_ty(param_ty)
            }))
        }
        Err(e) => {
            tcx.sess.err(e.as_slice());
            None
        }
    }
}

pub fn obligation_for_builtin_bound<'tcx>(
    tcx: &ty::ctxt<'tcx>,
    cause: ObligationCause<'tcx>,
    builtin_bound: ty::BuiltinBound,
    recursion_depth: uint,
    param_ty: Ty<'tcx>)
    -> Result<Obligation<'tcx>, ErrorReported>
{
    let trait_ref = trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty);
    match trait_ref {
        Some(trait_ref) => Ok(Obligation {
                cause: cause,
                recursion_depth: recursion_depth,
                trait_ref: trait_ref
            }),
        None => Err(ErrorReported)
    }
}

pub fn search_trait_and_supertraits_from_bound<'tcx>(tcx: &ty::ctxt<'tcx>,
                                                     caller_bound: Rc<ty::TraitRef<'tcx>>,
                                                     test: |ast::DefId| -> bool)
                                                     -> Option<VtableParamData<'tcx>>
{
    /*!
     * Starting from a caller obligation `caller_bound` (which has
     * coordinates `space`/`i` in the list of caller obligations),
     * search through the trait and supertraits to find one where
     * `test(d)` is true, where `d` is the def-id of the
     * trait/supertrait.  If any is found, return `Some(p)` where `p`
     * is the path to that trait/supertrait. Else `None`.
     */

    for bound in transitive_bounds(tcx, &[caller_bound]) {
        if test(bound.def_id) {
            let vtable_param = VtableParamData { bound: bound };
            return Some(vtable_param);
        }
    }

    return None;
}

impl<'tcx> Repr<'tcx> for super::Obligation<'tcx> {
    fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
        format!("Obligation(trait_ref={},depth={})",
                self.trait_ref.repr(tcx),
                self.recursion_depth)
    }
}

impl<'tcx, N:Repr<'tcx>> Repr<'tcx> for super::Vtable<'tcx, N> {
    fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
        match *self {
            super::VtableImpl(ref v) =>
                v.repr(tcx),

            super::VtableUnboxedClosure(ref d, ref s) =>
                format!("VtableUnboxedClosure({},{})",
                        d.repr(tcx),
                        s.repr(tcx)),

            super::VtableParam(ref v) =>
                format!("VtableParam({})", v.repr(tcx)),

            super::VtableBuiltin(ref d) =>
                d.repr(tcx)
        }
    }
}

impl<'tcx, N:Repr<'tcx>> Repr<'tcx> for super::VtableImplData<'tcx, N> {
    fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
        format!("VtableImpl(impl_def_id={}, substs={}, nested={})",
                self.impl_def_id.repr(tcx),
                self.substs.repr(tcx),
                self.nested.repr(tcx))
    }
}

impl<'tcx, N:Repr<'tcx>> Repr<'tcx> for super::VtableBuiltinData<N> {
    fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
        format!("VtableBuiltin(nested={})",
                self.nested.repr(tcx))
    }
}

impl<'tcx> Repr<'tcx> for super::VtableParamData<'tcx> {
    fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
        format!("VtableParam(bound={})",
                self.bound.repr(tcx))
    }
}

impl<'tcx> Repr<'tcx> for super::SelectionError<'tcx> {
    fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
        match *self {
            super::Overflow =>
                format!("Overflow"),

            super::Unimplemented =>
                format!("Unimplemented"),

            super::OutputTypeParameterMismatch(ref t, ref e) =>
                format!("OutputTypeParameterMismatch({}, {})",
                        t.repr(tcx),
                        e.repr(tcx)),
        }
    }
}

impl<'tcx> Repr<'tcx> for super::FulfillmentError<'tcx> {
    fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
        format!("FulfillmentError({},{})",
                self.obligation.repr(tcx),
                self.code.repr(tcx))
    }
}

impl<'tcx> Repr<'tcx> for super::FulfillmentErrorCode<'tcx> {
    fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
        match *self {
            super::CodeSelectionError(ref o) => o.repr(tcx),
            super::CodeAmbiguity => format!("Ambiguity")
        }
    }
}

impl<'tcx> fmt::Show for super::FulfillmentErrorCode<'tcx> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            super::CodeSelectionError(ref e) => write!(f, "{}", e),
            super::CodeAmbiguity => write!(f, "Ambiguity")
        }
    }
}

impl<'tcx> Repr<'tcx> for ty::type_err<'tcx> {
    fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
        ty::type_err_to_str(tcx, self)
    }
}