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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
use middle::subst::{Substs, VecPerParamSpace};
use middle::infer::InferCtxt;
use middle::ty::{self, Ty, AsPredicate, ToPolyTraitRef};
use std::fmt;
use std::rc::Rc;
use syntax::ast;
use syntax::codemap::Span;
use util::common::ErrorReported;
use util::nodemap::FnvHashSet;
use util::ppaux::Repr;
use super::{Obligation, ObligationCause, PredicateObligation,
VtableImpl, VtableParam, VtableImplData, VtableDefaultImplData};
struct PredicateSet<'a,'tcx:'a> {
tcx: &'a ty::ctxt<'tcx>,
set: FnvHashSet<ty::Predicate<'tcx>>,
}
impl<'a,'tcx> PredicateSet<'a,'tcx> {
fn new(tcx: &'a ty::ctxt<'tcx>) -> PredicateSet<'a,'tcx> {
PredicateSet { tcx: tcx, set: FnvHashSet() }
}
fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
let normalized_pred = match *pred {
ty::Predicate::Trait(ref data) =>
ty::Predicate::Trait(ty::anonymize_late_bound_regions(self.tcx, data)),
ty::Predicate::Equate(ref data) =>
ty::Predicate::Equate(ty::anonymize_late_bound_regions(self.tcx, data)),
ty::Predicate::RegionOutlives(ref data) =>
ty::Predicate::RegionOutlives(ty::anonymize_late_bound_regions(self.tcx, data)),
ty::Predicate::TypeOutlives(ref data) =>
ty::Predicate::TypeOutlives(ty::anonymize_late_bound_regions(self.tcx, data)),
ty::Predicate::Projection(ref data) =>
ty::Predicate::Projection(ty::anonymize_late_bound_regions(self.tcx, data)),
};
self.set.insert(normalized_pred)
}
}
pub struct Elaborator<'cx, 'tcx:'cx> {
tcx: &'cx ty::ctxt<'tcx>,
stack: Vec<ty::Predicate<'tcx>>,
visited: PredicateSet<'cx,'tcx>,
}
pub fn elaborate_trait_ref<'cx, 'tcx>(
tcx: &'cx ty::ctxt<'tcx>,
trait_ref: ty::PolyTraitRef<'tcx>)
-> Elaborator<'cx, 'tcx>
{
elaborate_predicates(tcx, vec![trait_ref.as_predicate()])
}
pub fn elaborate_trait_refs<'cx, 'tcx>(
tcx: &'cx ty::ctxt<'tcx>,
trait_refs: &[ty::PolyTraitRef<'tcx>])
-> Elaborator<'cx, 'tcx>
{
let predicates = trait_refs.iter()
.map(|trait_ref| trait_ref.as_predicate())
.collect();
elaborate_predicates(tcx, predicates)
}
pub fn elaborate_predicates<'cx, 'tcx>(
tcx: &'cx ty::ctxt<'tcx>,
mut predicates: Vec<ty::Predicate<'tcx>>)
-> Elaborator<'cx, 'tcx>
{
let mut visited = PredicateSet::new(tcx);
predicates.retain(|pred| visited.insert(pred));
Elaborator { tcx: tcx, stack: predicates, visited: visited }
}
impl<'cx, 'tcx> Elaborator<'cx, 'tcx> {
pub fn filter_to_traits(self) -> FilterToTraits<Elaborator<'cx, 'tcx>> {
FilterToTraits::new(self)
}
fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
match *predicate {
ty::Predicate::Trait(ref data) => {
let predicates = ty::lookup_super_predicates(self.tcx, data.def_id());
let mut predicates: Vec<_> =
predicates.predicates
.iter()
.map(|p| p.subst_supertrait(self.tcx, &data.to_poly_trait_ref()))
.collect();
debug!("super_predicates: data={} predicates={}",
data.repr(self.tcx), predicates.repr(self.tcx));
predicates.retain(|r| self.visited.insert(r));
self.stack.extend(predicates.into_iter());
}
ty::Predicate::Equate(..) => {
}
ty::Predicate::Projection(..) => {
}
ty::Predicate::RegionOutlives(..) |
ty::Predicate::TypeOutlives(..) => {
}
}
}
}
impl<'cx, 'tcx> Iterator for Elaborator<'cx, 'tcx> {
type Item = ty::Predicate<'tcx>;
fn next(&mut self) -> Option<ty::Predicate<'tcx>> {
let next_predicate = match self.stack.pop() {
Some(predicate) => predicate,
None => {
return None;
}
};
self.push(&next_predicate);
return Some(next_predicate);
}
}
pub type Supertraits<'cx, 'tcx> = FilterToTraits<Elaborator<'cx, 'tcx>>;
pub fn supertraits<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
trait_ref: ty::PolyTraitRef<'tcx>)
-> Supertraits<'cx, 'tcx>
{
elaborate_trait_ref(tcx, trait_ref).filter_to_traits()
}
pub fn transitive_bounds<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
bounds: &[ty::PolyTraitRef<'tcx>])
-> Supertraits<'cx, 'tcx>
{
elaborate_trait_refs(tcx, bounds).filter_to_traits()
}
pub struct SupertraitDefIds<'cx, 'tcx:'cx> {
tcx: &'cx ty::ctxt<'tcx>,
stack: Vec<ast::DefId>,
visited: FnvHashSet<ast::DefId>,
}
pub fn supertrait_def_ids<'cx, 'tcx>(tcx: &'cx ty::ctxt<'tcx>,
trait_def_id: ast::DefId)
-> SupertraitDefIds<'cx, 'tcx>
{
SupertraitDefIds {
tcx: tcx,
stack: vec![trait_def_id],
visited: Some(trait_def_id).into_iter().collect(),
}
}
impl<'cx, 'tcx> Iterator for SupertraitDefIds<'cx, 'tcx> {
type Item = ast::DefId;
fn next(&mut self) -> Option<ast::DefId> {
let def_id = match self.stack.pop() {
Some(def_id) => def_id,
None => { return None; }
};
let predicates = ty::lookup_super_predicates(self.tcx, def_id);
let visited = &mut self.visited;
self.stack.extend(
predicates.predicates
.iter()
.filter_map(|p| p.to_opt_poly_trait_ref())
.map(|t| t.def_id())
.filter(|&super_def_id| visited.insert(super_def_id)));
Some(def_id)
}
}
pub struct FilterToTraits<I> {
base_iterator: I
}
impl<I> FilterToTraits<I> {
fn new(base: I) -> FilterToTraits<I> {
FilterToTraits { base_iterator: base }
}
}
impl<'tcx,I:Iterator<Item=ty::Predicate<'tcx>>> Iterator for FilterToTraits<I> {
type Item = ty::PolyTraitRef<'tcx>;
fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
loop {
match self.base_iterator.next() {
None => {
return None;
}
Some(ty::Predicate::Trait(data)) => {
return Some(data.to_poly_trait_ref());
}
Some(_) => {
}
}
}
}
}
pub fn fresh_type_vars_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::Debug for VtableImplData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "VtableImpl({:?})", self.impl_def_id)
}
}
impl<'tcx> fmt::Debug for super::VtableObjectData<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "VtableObject(...)")
}
}
pub fn predicates_for_generics<'tcx>(tcx: &ty::ctxt<'tcx>,
cause: ObligationCause<'tcx>,
recursion_depth: usize,
generic_bounds: &ty::InstantiatedPredicates<'tcx>)
-> VecPerParamSpace<PredicateObligation<'tcx>>
{
debug!("predicates_for_generics(generic_bounds={})",
generic_bounds.repr(tcx));
generic_bounds.predicates.map(|predicate| {
Obligation { cause: cause.clone(),
recursion_depth: recursion_depth,
predicate: predicate.clone() }
})
}
pub fn trait_ref_for_builtin_bound<'tcx>(
tcx: &ty::ctxt<'tcx>,
builtin_bound: ty::BuiltinBound,
param_ty: Ty<'tcx>)
-> Result<Rc<ty::TraitRef<'tcx>>, ErrorReported>
{
match tcx.lang_items.from_builtin_kind(builtin_bound) {
Ok(def_id) => {
Ok(Rc::new(ty::TraitRef {
def_id: def_id,
substs: tcx.mk_substs(Substs::empty().with_self_ty(param_ty))
}))
}
Err(e) => {
tcx.sess.err(&e);
Err(ErrorReported)
}
}
}
pub fn predicate_for_trait_ref<'tcx>(
cause: ObligationCause<'tcx>,
trait_ref: Rc<ty::TraitRef<'tcx>>,
recursion_depth: usize)
-> Result<PredicateObligation<'tcx>, ErrorReported>
{
Ok(Obligation {
cause: cause,
recursion_depth: recursion_depth,
predicate: trait_ref.as_predicate(),
})
}
pub fn predicate_for_trait_def<'tcx>(
tcx: &ty::ctxt<'tcx>,
cause: ObligationCause<'tcx>,
trait_def_id: ast::DefId,
recursion_depth: usize,
param_ty: Ty<'tcx>)
-> Result<PredicateObligation<'tcx>, ErrorReported>
{
let trait_ref = Rc::new(ty::TraitRef {
def_id: trait_def_id,
substs: tcx.mk_substs(Substs::empty().with_self_ty(param_ty))
});
predicate_for_trait_ref(cause, trait_ref, recursion_depth)
}
pub fn predicate_for_builtin_bound<'tcx>(
tcx: &ty::ctxt<'tcx>,
cause: ObligationCause<'tcx>,
builtin_bound: ty::BuiltinBound,
recursion_depth: usize,
param_ty: Ty<'tcx>)
-> Result<PredicateObligation<'tcx>, ErrorReported>
{
let trait_ref = try!(trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty));
predicate_for_trait_ref(cause, trait_ref, recursion_depth)
}
pub fn upcast<'tcx>(tcx: &ty::ctxt<'tcx>,
source_trait_ref: ty::PolyTraitRef<'tcx>,
target_trait_def_id: ast::DefId)
-> Vec<ty::PolyTraitRef<'tcx>>
{
if source_trait_ref.def_id() == target_trait_def_id {
return vec![source_trait_ref];
}
supertraits(tcx, source_trait_ref)
.filter(|r| r.def_id() == target_trait_def_id)
.collect()
}
pub fn get_vtable_index_of_object_method<'tcx>(tcx: &ty::ctxt<'tcx>,
object_trait_ref: ty::PolyTraitRef<'tcx>,
trait_def_id: ast::DefId,
method_offset_in_trait: usize) -> usize {
let mut method_count = 0;
for bound_ref in transitive_bounds(tcx, &[object_trait_ref]) {
if bound_ref.def_id() == trait_def_id {
break;
}
let trait_items = ty::trait_items(tcx, bound_ref.def_id());
for trait_item in &**trait_items {
match *trait_item {
ty::MethodTraitItem(_) => method_count += 1,
ty::TypeTraitItem(_) => {}
}
}
}
let trait_items = ty::trait_items(tcx, trait_def_id);
for trait_item in trait_items.iter().take(method_offset_in_trait) {
match *trait_item {
ty::MethodTraitItem(_) => method_count += 1,
ty::TypeTraitItem(_) => {}
}
}
assert!(match trait_items[method_offset_in_trait] {
ty::MethodTraitItem(_) => true,
ty::TypeTraitItem(_) => false
});
method_count
}
pub enum TupleArgumentsFlag { Yes, No }
pub fn closure_trait_ref_and_return_type<'tcx>(
tcx: &ty::ctxt<'tcx>,
fn_trait_def_id: ast::DefId,
self_ty: Ty<'tcx>,
sig: &ty::PolyFnSig<'tcx>,
tuple_arguments: TupleArgumentsFlag)
-> ty::Binder<(Rc<ty::TraitRef<'tcx>>, Ty<'tcx>)>
{
let arguments_tuple = match tuple_arguments {
TupleArgumentsFlag::No => sig.0.inputs[0],
TupleArgumentsFlag::Yes => ty::mk_tup(tcx, sig.0.inputs.to_vec()),
};
let trait_substs = Substs::new_trait(vec![arguments_tuple], vec![], self_ty);
let trait_ref = Rc::new(ty::TraitRef {
def_id: fn_trait_def_id,
substs: tcx.mk_substs(trait_substs),
});
ty::Binder((trait_ref, sig.0.output.unwrap_or(ty::mk_nil(tcx))))
}
impl<'tcx,O:Repr<'tcx>> Repr<'tcx> for super::Obligation<'tcx, O> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
format!("Obligation(predicate={},depth={})",
self.predicate.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::VtableDefaultImpl(ref t) =>
t.repr(tcx),
super::VtableClosure(ref d, ref s) =>
format!("VtableClosure({},{})",
d.repr(tcx),
s.repr(tcx)),
super::VtableFnPointer(ref d) =>
format!("VtableFnPointer({})",
d.repr(tcx)),
super::VtableObject(ref d) =>
format!("VtableObject({})",
d.repr(tcx)),
super::VtableParam(ref n) =>
format!("VtableParam({})",
n.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, N:Repr<'tcx>> Repr<'tcx> for super::VtableDefaultImplData<N> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
format!("VtableDefaultImplData(trait_def_id={}, nested={})",
self.trait_def_id.repr(tcx),
self.nested.repr(tcx))
}
}
impl<'tcx> Repr<'tcx> for super::VtableObjectData<'tcx> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
format!("VtableObject(object_ty={})",
self.object_ty.repr(tcx))
}
}
impl<'tcx> Repr<'tcx> for super::SelectionError<'tcx> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
match *self {
super::Unimplemented =>
format!("Unimplemented"),
super::OutputTypeParameterMismatch(ref a, ref b, ref c) =>
format!("OutputTypeParameterMismatch({},{},{})",
a.repr(tcx),
b.repr(tcx),
c.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::CodeProjectionError(ref o) => o.repr(tcx),
super::CodeAmbiguity => format!("Ambiguity")
}
}
}
impl<'tcx> fmt::Debug for super::FulfillmentErrorCode<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
super::CodeSelectionError(ref e) => write!(f, "{:?}", e),
super::CodeProjectionError(ref e) => write!(f, "{:?}", e),
super::CodeAmbiguity => write!(f, "Ambiguity")
}
}
}
impl<'tcx> Repr<'tcx> for super::MismatchedProjectionTypes<'tcx> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
self.err.repr(tcx)
}
}
impl<'tcx> fmt::Debug for super::MismatchedProjectionTypes<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "MismatchedProjectionTypes(..)")
}
}