-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
Copy pathproject.rs
1178 lines (1064 loc) · 44.4 KB
/
project.rs
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
//! Code for projecting associated types out of trait references.
use super::elaborate_predicates;
use super::report_overflow_error;
use super::specialization_graph;
use super::translate_substs;
use super::Obligation;
use super::ObligationCause;
use super::PredicateObligation;
use super::SelectionContext;
use super::SelectionError;
use super::VtableClosureData;
use super::VtableImplData;
use super::util;
use hir::def_id::DefId;
use infer::{self, InferOk, TypeOrigin};
use ty::subst::Subst;
use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt};
use ty::fold::{TypeFoldable, TypeFolder};
use syntax::parse::token;
use syntax::ast;
use util::common::FN_OUTPUT_NAME;
use std::rc::Rc;
/// Depending on the stage of compilation, we want projection to be
/// more or less conservative.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ProjectionMode {
/// FIXME (#32205)
/// At coherence-checking time, we're still constructing the
/// specialization graph, and thus we only project project
/// non-`default` associated types that are defined directly in
/// the applicable impl. (This behavior should be improved over
/// time, to allow for successful projections modulo cycles
/// between different impls).
///
/// Here's an example that will fail due to the restriction:
///
/// ```
/// trait Assoc {
/// type Output;
/// }
///
/// impl<T> Assoc for T {
/// type Output = bool;
/// }
///
/// impl Assoc for u8 {} // <- inherits the non-default type from above
///
/// trait Foo {}
/// impl Foo for u32 {}
/// impl Foo for <u8 as Assoc>::Output {} // <- this projection will fail
/// ```
///
/// The projection would succeed if `Output` had been defined
/// directly in the impl for `u8`.
Topmost,
/// At type-checking time, we refuse to project any associated
/// type that is marked `default`. Non-`default` ("final") types
/// are always projected. This is necessary in general for
/// soundness of specialization. However, we *could* allow
/// projections in fully-monomorphic cases. We choose not to,
/// because we prefer for `default type` to force the type
/// definition to be treated abstractly by any consumers of the
/// impl. Concretely, that means that the following example will
/// fail to compile:
///
/// ```
/// trait Assoc {
/// type Output;
/// }
///
/// impl<T> Assoc for T {
/// default type Output = bool;
/// }
///
/// fn main() {
/// let <() as Assoc>::Output = true;
/// }
AnyFinal,
/// At trans time, all projections will succeed.
Any,
}
impl ProjectionMode {
pub fn is_topmost(&self) -> bool {
match *self {
ProjectionMode::Topmost => true,
_ => false,
}
}
pub fn is_any_final(&self) -> bool {
match *self {
ProjectionMode::AnyFinal => true,
_ => false,
}
}
pub fn is_any(&self) -> bool {
match *self {
ProjectionMode::Any => true,
_ => false,
}
}
}
pub type PolyProjectionObligation<'tcx> =
Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>;
pub type ProjectionObligation<'tcx> =
Obligation<'tcx, ty::ProjectionPredicate<'tcx>>;
pub type ProjectionTyObligation<'tcx> =
Obligation<'tcx, ty::ProjectionTy<'tcx>>;
/// When attempting to resolve `<T as TraitRef>::Name` ...
#[derive(Debug)]
pub enum ProjectionTyError<'tcx> {
/// ...we found multiple sources of information and couldn't resolve the ambiguity.
TooManyCandidates,
/// ...an error occurred matching `T : TraitRef`
TraitSelectionError(SelectionError<'tcx>),
}
#[derive(Clone)]
pub struct MismatchedProjectionTypes<'tcx> {
pub err: ty::error::TypeError<'tcx>
}
#[derive(PartialEq, Eq, Debug)]
enum ProjectionTyCandidate<'tcx> {
// from a where-clause in the env or object type
ParamEnv(ty::PolyProjectionPredicate<'tcx>),
// from the definition of `Trait` when you have something like <<A as Trait>::B as Trait2>::C
TraitDef(ty::PolyProjectionPredicate<'tcx>),
// defined in an impl
Impl(VtableImplData<'tcx, PredicateObligation<'tcx>>),
// closure return type
Closure(VtableClosureData<'tcx, PredicateObligation<'tcx>>),
// fn pointer return type
FnPointer(Ty<'tcx>),
}
struct ProjectionTyCandidateSet<'tcx> {
vec: Vec<ProjectionTyCandidate<'tcx>>,
ambiguous: bool
}
/// Evaluates constraints of the form:
///
/// for<...> <T as Trait>::U == V
///
/// If successful, this may result in additional obligations.
pub fn poly_project_and_unify_type<'cx,'tcx>(
selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &PolyProjectionObligation<'tcx>)
-> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>>
{
debug!("poly_project_and_unify_type(obligation={:?})",
obligation);
let infcx = selcx.infcx();
infcx.commit_if_ok(|snapshot| {
let (skol_predicate, skol_map) =
infcx.skolemize_late_bound_regions(&obligation.predicate, snapshot);
let skol_obligation = obligation.with(skol_predicate);
match project_and_unify_type(selcx, &skol_obligation) {
Ok(result) => {
match infcx.leak_check(&skol_map, snapshot) {
Ok(()) => Ok(infcx.plug_leaks(skol_map, snapshot, &result)),
Err(e) => Err(MismatchedProjectionTypes { err: e }),
}
}
Err(e) => {
Err(e)
}
}
})
}
/// Evaluates constraints of the form:
///
/// <T as Trait>::U == V
///
/// If successful, this may result in additional obligations.
fn project_and_unify_type<'cx,'tcx>(
selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &ProjectionObligation<'tcx>)
-> Result<Option<Vec<PredicateObligation<'tcx>>>, MismatchedProjectionTypes<'tcx>>
{
debug!("project_and_unify_type(obligation={:?})",
obligation);
let Normalized { value: normalized_ty, obligations } =
match opt_normalize_projection_type(selcx,
obligation.predicate.projection_ty.clone(),
obligation.cause.clone(),
obligation.recursion_depth) {
Some(n) => n,
None => {
consider_unification_despite_ambiguity(selcx, obligation);
return Ok(None);
}
};
debug!("project_and_unify_type: normalized_ty={:?} obligations={:?}",
normalized_ty,
obligations);
let infcx = selcx.infcx();
let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
match infer::mk_eqty(infcx, true, origin, normalized_ty, obligation.predicate.ty) {
Ok(InferOk { obligations: inferred_obligations, .. }) => {
// FIXME(#32730) propagate obligations
assert!(inferred_obligations.is_empty());
Ok(Some(obligations))
},
Err(err) => Err(MismatchedProjectionTypes { err: err }),
}
}
fn consider_unification_despite_ambiguity<'cx,'tcx>(selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &ProjectionObligation<'tcx>) {
debug!("consider_unification_despite_ambiguity(obligation={:?})",
obligation);
let def_id = obligation.predicate.projection_ty.trait_ref.def_id;
match selcx.tcx().lang_items.fn_trait_kind(def_id) {
Some(_) => { }
None => { return; }
}
let infcx = selcx.infcx();
let self_ty = obligation.predicate.projection_ty.trait_ref.self_ty();
let self_ty = infcx.shallow_resolve(self_ty);
debug!("consider_unification_despite_ambiguity: self_ty.sty={:?}",
self_ty.sty);
match self_ty.sty {
ty::TyClosure(closure_def_id, ref substs) => {
let closure_typer = selcx.closure_typer();
let closure_type = closure_typer.closure_type(closure_def_id, substs);
let ty::Binder((_, ret_type)) =
util::closure_trait_ref_and_return_type(infcx.tcx,
def_id,
self_ty,
&closure_type.sig,
util::TupleArgumentsFlag::No);
// We don't have to normalize the return type here - this is only
// reached for TyClosure: Fn inputs where the closure kind is
// still unknown, which should only occur in typeck where the
// closure type is already normalized.
let (ret_type, _) =
infcx.replace_late_bound_regions_with_fresh_var(
obligation.cause.span,
infer::AssocTypeProjection(obligation.predicate.projection_ty.item_name),
&ty::Binder(ret_type));
debug!("consider_unification_despite_ambiguity: ret_type={:?}",
ret_type);
let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
let obligation_ty = obligation.predicate.ty;
match infer::mk_eqty(infcx, true, origin, obligation_ty, ret_type) {
Ok(InferOk { obligations, .. }) => {
// FIXME(#32730) propagate obligations
assert!(obligations.is_empty());
}
Err(_) => { /* ignore errors */ }
}
}
_ => { }
}
}
/// Normalizes any associated type projections in `value`, replacing
/// them with a fully resolved type where possible. The return value
/// combines the normalized result and any additional obligations that
/// were incurred as result.
pub fn normalize<'a,'b,'tcx,T>(selcx: &'a mut SelectionContext<'b,'tcx>,
cause: ObligationCause<'tcx>,
value: &T)
-> Normalized<'tcx, T>
where T : TypeFoldable<'tcx>
{
normalize_with_depth(selcx, cause, 0, value)
}
/// As `normalize`, but with a custom depth.
pub fn normalize_with_depth<'a,'b,'tcx,T>(selcx: &'a mut SelectionContext<'b,'tcx>,
cause: ObligationCause<'tcx>,
depth: usize,
value: &T)
-> Normalized<'tcx, T>
where T : TypeFoldable<'tcx>
{
let mut normalizer = AssociatedTypeNormalizer::new(selcx, cause, depth);
let result = normalizer.fold(value);
Normalized {
value: result,
obligations: normalizer.obligations,
}
}
struct AssociatedTypeNormalizer<'a,'b:'a,'tcx:'b> {
selcx: &'a mut SelectionContext<'b,'tcx>,
cause: ObligationCause<'tcx>,
obligations: Vec<PredicateObligation<'tcx>>,
depth: usize,
}
impl<'a,'b,'tcx> AssociatedTypeNormalizer<'a,'b,'tcx> {
fn new(selcx: &'a mut SelectionContext<'b,'tcx>,
cause: ObligationCause<'tcx>,
depth: usize)
-> AssociatedTypeNormalizer<'a,'b,'tcx>
{
AssociatedTypeNormalizer {
selcx: selcx,
cause: cause,
obligations: vec!(),
depth: depth,
}
}
fn fold<T:TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
let value = self.selcx.infcx().resolve_type_vars_if_possible(value);
if !value.has_projection_types() {
value.clone()
} else {
value.fold_with(self)
}
}
}
impl<'a,'b,'tcx> TypeFolder<'tcx> for AssociatedTypeNormalizer<'a,'b,'tcx> {
fn tcx(&self) -> &TyCtxt<'tcx> {
self.selcx.tcx()
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
// We don't want to normalize associated types that occur inside of region
// binders, because they may contain bound regions, and we can't cope with that.
//
// Example:
//
// for<'a> fn(<T as Foo<&'a>>::A)
//
// Instead of normalizing `<T as Foo<&'a>>::A` here, we'll
// normalize it when we instantiate those bound regions (which
// should occur eventually).
let ty = ty.super_fold_with(self);
match ty.sty {
ty::TyProjection(ref data) if !data.has_escaping_regions() => { // (*)
// (*) This is kind of hacky -- we need to be able to
// handle normalization within binders because
// otherwise we wind up a need to normalize when doing
// trait matching (since you can have a trait
// obligation like `for<'a> T::B : Fn(&'a int)`), but
// we can't normalize with bound regions in scope. So
// far now we just ignore binders but only normalize
// if all bound regions are gone (and then we still
// have to renormalize whenever we instantiate a
// binder). It would be better to normalize in a
// binding-aware fashion.
let Normalized { value: ty, obligations } =
normalize_projection_type(self.selcx,
data.clone(),
self.cause.clone(),
self.depth);
self.obligations.extend(obligations);
ty
}
_ => {
ty
}
}
}
}
#[derive(Clone)]
pub struct Normalized<'tcx,T> {
pub value: T,
pub obligations: Vec<PredicateObligation<'tcx>>,
}
pub type NormalizedTy<'tcx> = Normalized<'tcx, Ty<'tcx>>;
impl<'tcx,T> Normalized<'tcx,T> {
pub fn with<U>(self, value: U) -> Normalized<'tcx,U> {
Normalized { value: value, obligations: self.obligations }
}
}
/// The guts of `normalize`: normalize a specific projection like `<T
/// as Trait>::Item`. The result is always a type (and possibly
/// additional obligations). If ambiguity arises, which implies that
/// there are unresolved type variables in the projection, we will
/// substitute a fresh type variable `$X` and generate a new
/// obligation `<T as Trait>::Item == $X` for later.
pub fn normalize_projection_type<'a,'b,'tcx>(
selcx: &'a mut SelectionContext<'b,'tcx>,
projection_ty: ty::ProjectionTy<'tcx>,
cause: ObligationCause<'tcx>,
depth: usize)
-> NormalizedTy<'tcx>
{
opt_normalize_projection_type(selcx, projection_ty.clone(), cause.clone(), depth)
.unwrap_or_else(move || {
// if we bottom out in ambiguity, create a type variable
// and a deferred predicate to resolve this when more type
// information is available.
let ty_var = selcx.infcx().next_ty_var();
let projection = ty::Binder(ty::ProjectionPredicate {
projection_ty: projection_ty,
ty: ty_var
});
let obligation = Obligation::with_depth(
cause, depth + 1, projection.to_predicate());
Normalized {
value: ty_var,
obligations: vec!(obligation)
}
})
}
/// The guts of `normalize`: normalize a specific projection like `<T
/// as Trait>::Item`. The result is always a type (and possibly
/// additional obligations). Returns `None` in the case of ambiguity,
/// which indicates that there are unbound type variables.
fn opt_normalize_projection_type<'a,'b,'tcx>(
selcx: &'a mut SelectionContext<'b,'tcx>,
projection_ty: ty::ProjectionTy<'tcx>,
cause: ObligationCause<'tcx>,
depth: usize)
-> Option<NormalizedTy<'tcx>>
{
debug!("normalize_projection_type(\
projection_ty={:?}, \
depth={})",
projection_ty,
depth);
let obligation = Obligation::with_depth(cause.clone(), depth, projection_ty.clone());
match project_type(selcx, &obligation) {
Ok(ProjectedTy::Progress(projected_ty, mut obligations)) => {
// if projection succeeded, then what we get out of this
// is also non-normalized (consider: it was derived from
// an impl, where-clause etc) and hence we must
// re-normalize it
debug!("normalize_projection_type: projected_ty={:?} depth={} obligations={:?}",
projected_ty,
depth,
obligations);
if projected_ty.has_projection_types() {
let mut normalizer = AssociatedTypeNormalizer::new(selcx, cause, depth+1);
let normalized_ty = normalizer.fold(&projected_ty);
debug!("normalize_projection_type: normalized_ty={:?} depth={}",
normalized_ty,
depth);
obligations.extend(normalizer.obligations);
Some(Normalized {
value: normalized_ty,
obligations: obligations,
})
} else {
Some(Normalized {
value: projected_ty,
obligations: obligations,
})
}
}
Ok(ProjectedTy::NoProgress(projected_ty)) => {
debug!("normalize_projection_type: projected_ty={:?} no progress",
projected_ty);
Some(Normalized {
value: projected_ty,
obligations: vec!()
})
}
Err(ProjectionTyError::TooManyCandidates) => {
debug!("normalize_projection_type: too many candidates");
None
}
Err(ProjectionTyError::TraitSelectionError(_)) => {
debug!("normalize_projection_type: ERROR");
// if we got an error processing the `T as Trait` part,
// just return `ty::err` but add the obligation `T :
// Trait`, which when processed will cause the error to be
// reported later
Some(normalize_to_error(selcx, projection_ty, cause, depth))
}
}
}
/// If we are projecting `<T as Trait>::Item`, but `T: Trait` does not
/// hold. In various error cases, we cannot generate a valid
/// normalized projection. Therefore, we create an inference variable
/// return an associated obligation that, when fulfilled, will lead to
/// an error.
///
/// Note that we used to return `TyError` here, but that was quite
/// dubious -- the premise was that an error would *eventually* be
/// reported, when the obligation was processed. But in general once
/// you see a `TyError` you are supposed to be able to assume that an
/// error *has been* reported, so that you can take whatever heuristic
/// paths you want to take. To make things worse, it was possible for
/// cycles to arise, where you basically had a setup like `<MyType<$0>
/// as Trait>::Foo == $0`. Here, normalizing `<MyType<$0> as
/// Trait>::Foo> to `[type error]` would lead to an obligation of
/// `<MyType<[type error]> as Trait>::Foo`. We are supposed to report
/// an error for this obligation, but we legitimately should not,
/// because it contains `[type error]`. Yuck! (See issue #29857 for
/// one case where this arose.)
fn normalize_to_error<'a,'tcx>(selcx: &mut SelectionContext<'a,'tcx>,
projection_ty: ty::ProjectionTy<'tcx>,
cause: ObligationCause<'tcx>,
depth: usize)
-> NormalizedTy<'tcx>
{
let trait_ref = projection_ty.trait_ref.to_poly_trait_ref();
let trait_obligation = Obligation { cause: cause,
recursion_depth: depth,
predicate: trait_ref.to_predicate() };
let new_value = selcx.infcx().next_ty_var();
Normalized {
value: new_value,
obligations: vec!(trait_obligation)
}
}
enum ProjectedTy<'tcx> {
Progress(Ty<'tcx>, Vec<PredicateObligation<'tcx>>),
NoProgress(Ty<'tcx>),
}
/// Compute the result of a projection type (if we can).
fn project_type<'cx,'tcx>(
selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &ProjectionTyObligation<'tcx>)
-> Result<ProjectedTy<'tcx>, ProjectionTyError<'tcx>>
{
debug!("project(obligation={:?})",
obligation);
let recursion_limit = selcx.tcx().sess.recursion_limit.get();
if obligation.recursion_depth >= recursion_limit {
debug!("project: overflow!");
report_overflow_error(selcx.infcx(), &obligation, true);
}
let obligation_trait_ref =
selcx.infcx().resolve_type_vars_if_possible(&obligation.predicate.trait_ref);
debug!("project: obligation_trait_ref={:?}", obligation_trait_ref);
if obligation_trait_ref.references_error() {
return Ok(ProjectedTy::Progress(selcx.tcx().types.err, vec!()));
}
let mut candidates = ProjectionTyCandidateSet {
vec: Vec::new(),
ambiguous: false,
};
assemble_candidates_from_param_env(selcx,
obligation,
&obligation_trait_ref,
&mut candidates);
assemble_candidates_from_trait_def(selcx,
obligation,
&obligation_trait_ref,
&mut candidates);
if let Err(e) = assemble_candidates_from_impls(selcx,
obligation,
&obligation_trait_ref,
&mut candidates) {
return Err(ProjectionTyError::TraitSelectionError(e));
}
debug!("{} candidates, ambiguous={}",
candidates.vec.len(),
candidates.ambiguous);
// Inherent ambiguity that prevents us from even enumerating the
// candidates.
if candidates.ambiguous {
return Err(ProjectionTyError::TooManyCandidates);
}
// Drop duplicates.
//
// Note: `candidates.vec` seems to be on the critical path of the
// compiler. Replacing it with an hash set was also tried, which would
// render the following dedup unnecessary. It led to cleaner code but
// prolonged compiling time of `librustc` from 5m30s to 6m in one test, or
// ~9% performance lost.
if candidates.vec.len() > 1 {
let mut i = 0;
while i < candidates.vec.len() {
let has_dup = (0..i).any(|j| candidates.vec[i] == candidates.vec[j]);
if has_dup {
candidates.vec.swap_remove(i);
} else {
i += 1;
}
}
}
// Prefer where-clauses. As in select, if there are multiple
// candidates, we prefer where-clause candidates over impls. This
// may seem a bit surprising, since impls are the source of
// "truth" in some sense, but in fact some of the impls that SEEM
// applicable are not, because of nested obligations. Where
// clauses are the safer choice. See the comment on
// `select::SelectionCandidate` and #21974 for more details.
if candidates.vec.len() > 1 {
debug!("retaining param-env candidates only from {:?}", candidates.vec);
candidates.vec.retain(|c| match *c {
ProjectionTyCandidate::ParamEnv(..) => true,
ProjectionTyCandidate::Impl(..) |
ProjectionTyCandidate::Closure(..) |
ProjectionTyCandidate::TraitDef(..) |
ProjectionTyCandidate::FnPointer(..) => false,
});
debug!("resulting candidate set: {:?}", candidates.vec);
if candidates.vec.len() != 1 {
return Err(ProjectionTyError::TooManyCandidates);
}
}
assert!(candidates.vec.len() <= 1);
let possible_candidate = candidates.vec.pop().and_then(|candidate| {
// In Any (i.e. trans) mode, all projections succeed;
// otherwise, we need to be sensitive to `default` and
// specialization.
if !selcx.projection_mode().is_any() {
if let ProjectionTyCandidate::Impl(ref impl_data) = candidate {
if let Some(node_item) = assoc_ty_def(selcx,
impl_data.impl_def_id,
obligation.predicate.item_name) {
if node_item.node.is_from_trait() {
if node_item.item.ty.is_some() {
// If the associated type has a default from the
// trait, that should be considered `default` and
// hence not projected.
//
// Note, however, that we allow a projection from
// the trait specifically in the case that the trait
// does *not* give a default. This is purely to
// avoid spurious errors: the situation can only
// arise when *no* impl in the specialization chain
// has provided a definition for the type. When we
// confirm the candidate, we'll turn the projection
// into a TyError, since the actual error will be
// reported in `check_impl_items_against_trait`.
return None;
}
} else if node_item.item.defaultness.is_default() {
return None;
}
} else {
// Normally this situation could only arise througha
// compiler bug, but at coherence-checking time we only look
// at the topmost impl (we don't even consider the trait
// itself) for the definition -- so we can fail to find a
// definition of the type even if it exists.
// For now, we just unconditionally ICE, because otherwise,
// examples like the following will succeed:
//
// ```
// trait Assoc {
// type Output;
// }
//
// impl<T> Assoc for T {
// default type Output = bool;
// }
//
// impl Assoc for u8 {}
// impl Assoc for u16 {}
//
// trait Foo {}
// impl Foo for <u8 as Assoc>::Output {}
// impl Foo for <u16 as Assoc>::Output {}
// return None;
// }
// ```
//
// The essential problem here is that the projection fails,
// leaving two unnormalized types, which appear not to unify
// -- so the overlap check succeeds, when it should fail.
bug!("Tried to project an inherited associated type during \
coherence checking, which is currently not supported.");
}
}
}
Some(candidate)
});
match possible_candidate {
Some(candidate) => {
let (ty, obligations) = confirm_candidate(selcx, obligation, candidate);
Ok(ProjectedTy::Progress(ty, obligations))
}
None => {
Ok(ProjectedTy::NoProgress(selcx.tcx().mk_projection(
obligation.predicate.trait_ref.clone(),
obligation.predicate.item_name)))
}
}
}
/// The first thing we have to do is scan through the parameter
/// environment to see whether there are any projection predicates
/// there that can answer this question.
fn assemble_candidates_from_param_env<'cx,'tcx>(
selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation_trait_ref: &ty::TraitRef<'tcx>,
candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
{
debug!("assemble_candidates_from_param_env(..)");
let env_predicates = selcx.param_env().caller_bounds.iter().cloned();
assemble_candidates_from_predicates(selcx,
obligation,
obligation_trait_ref,
candidate_set,
ProjectionTyCandidate::ParamEnv,
env_predicates);
}
/// In the case of a nested projection like <<A as Foo>::FooT as Bar>::BarT, we may find
/// that the definition of `Foo` has some clues:
///
/// ```
/// trait Foo {
/// type FooT : Bar<BarT=i32>
/// }
/// ```
///
/// Here, for example, we could conclude that the result is `i32`.
fn assemble_candidates_from_trait_def<'cx,'tcx>(
selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation_trait_ref: &ty::TraitRef<'tcx>,
candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
{
debug!("assemble_candidates_from_trait_def(..)");
// Check whether the self-type is itself a projection.
let trait_ref = match obligation_trait_ref.self_ty().sty {
ty::TyProjection(ref data) => data.trait_ref.clone(),
ty::TyInfer(ty::TyVar(_)) => {
// If the self-type is an inference variable, then it MAY wind up
// being a projected type, so induce an ambiguity.
candidate_set.ambiguous = true;
return;
}
_ => { return; }
};
// If so, extract what we know from the trait and try to come up with a good answer.
let trait_predicates = selcx.tcx().lookup_predicates(trait_ref.def_id);
let bounds = trait_predicates.instantiate(selcx.tcx(), trait_ref.substs);
let bounds = elaborate_predicates(selcx.tcx(), bounds.predicates.into_vec());
assemble_candidates_from_predicates(selcx,
obligation,
obligation_trait_ref,
candidate_set,
ProjectionTyCandidate::TraitDef,
bounds)
}
fn assemble_candidates_from_predicates<'cx,'tcx,I>(
selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation_trait_ref: &ty::TraitRef<'tcx>,
candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>,
env_predicates: I)
where I: Iterator<Item=ty::Predicate<'tcx>>
{
debug!("assemble_candidates_from_predicates(obligation={:?})",
obligation);
let infcx = selcx.infcx();
for predicate in env_predicates {
debug!("assemble_candidates_from_predicates: predicate={:?}",
predicate);
match predicate {
ty::Predicate::Projection(ref data) => {
let same_name = data.item_name() == obligation.predicate.item_name;
let is_match = same_name && infcx.probe(|_| {
let origin = TypeOrigin::Misc(obligation.cause.span);
let data_poly_trait_ref =
data.to_poly_trait_ref();
let obligation_poly_trait_ref =
obligation_trait_ref.to_poly_trait_ref();
infcx.sub_poly_trait_refs(false,
origin,
data_poly_trait_ref,
obligation_poly_trait_ref)
// FIXME(#32730) propagate obligations
.map(|InferOk { obligations, .. }| assert!(obligations.is_empty()))
.is_ok()
});
debug!("assemble_candidates_from_predicates: candidate={:?} \
is_match={} same_name={}",
data, is_match, same_name);
if is_match {
candidate_set.vec.push(ctor(data.clone()));
}
}
_ => { }
}
}
}
fn assemble_candidates_from_object_type<'cx,'tcx>(
selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation_trait_ref: &ty::TraitRef<'tcx>,
candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
{
let self_ty = obligation_trait_ref.self_ty();
let object_ty = selcx.infcx().shallow_resolve(self_ty);
debug!("assemble_candidates_from_object_type(object_ty={:?})",
object_ty);
let data = match object_ty.sty {
ty::TyTrait(ref data) => data,
_ => {
span_bug!(
obligation.cause.span,
"assemble_candidates_from_object_type called with non-object: {:?}",
object_ty);
}
};
let projection_bounds = data.projection_bounds_with_self_ty(selcx.tcx(), object_ty);
let env_predicates = projection_bounds.iter()
.map(|p| p.to_predicate())
.collect();
let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
assemble_candidates_from_predicates(selcx,
obligation,
obligation_trait_ref,
candidate_set,
ProjectionTyCandidate::ParamEnv,
env_predicates)
}
fn assemble_candidates_from_impls<'cx,'tcx>(
selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
obligation_trait_ref: &ty::TraitRef<'tcx>,
candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
-> Result<(), SelectionError<'tcx>>
{
// If we are resolving `<T as TraitRef<...>>::Item == Type`,
// start out by selecting the predicate `T as TraitRef<...>`:
let poly_trait_ref = obligation_trait_ref.to_poly_trait_ref();
let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate());
let vtable = match selcx.select(&trait_obligation) {
Ok(Some(vtable)) => vtable,
Ok(None) => {
candidate_set.ambiguous = true;
return Ok(());
}
Err(e) => {
debug!("assemble_candidates_from_impls: selection error {:?}",
e);
return Err(e);
}
};
match vtable {
super::VtableImpl(data) => {
debug!("assemble_candidates_from_impls: impl candidate {:?}",
data);
candidate_set.vec.push(
ProjectionTyCandidate::Impl(data));
}
super::VtableObject(_) => {
assemble_candidates_from_object_type(
selcx, obligation, obligation_trait_ref, candidate_set);
}
super::VtableClosure(data) => {
candidate_set.vec.push(
ProjectionTyCandidate::Closure(data));
}
super::VtableFnPointer(fn_type) => {
candidate_set.vec.push(
ProjectionTyCandidate::FnPointer(fn_type));
}
super::VtableParam(..) => {
// This case tell us nothing about the value of an
// associated type. Consider:
//
// ```
// trait SomeTrait { type Foo; }
// fn foo<T:SomeTrait>(...) { }
// ```
//
// If the user writes `<T as SomeTrait>::Foo`, then the `T
// : SomeTrait` binding does not help us decide what the
// type `Foo` is (at least, not more specifically than
// what we already knew).
//
// But wait, you say! What about an example like this:
//
// ```
// fn bar<T:SomeTrait<Foo=usize>>(...) { ... }
// ```
//
// Doesn't the `T : Sometrait<Foo=usize>` predicate help
// resolve `T::Foo`? And of course it does, but in fact
// that single predicate is desugared into two predicates
// in the compiler: a trait predicate (`T : SomeTrait`) and a
// projection. And the projection where clause is handled
// in `assemble_candidates_from_param_env`.
}
super::VtableDefaultImpl(..) |
super::VtableBuiltin(..) => {
// These traits have no associated types.
span_bug!(
obligation.cause.span,
"Cannot project an associated type from `{:?}`",
vtable);
}
}
Ok(())
}
fn confirm_candidate<'cx,'tcx>(
selcx: &mut SelectionContext<'cx,'tcx>,
obligation: &ProjectionTyObligation<'tcx>,
candidate: ProjectionTyCandidate<'tcx>)
-> (Ty<'tcx>, Vec<PredicateObligation<'tcx>>)
{
debug!("confirm_candidate(candidate={:?}, obligation={:?})",
candidate,
obligation);
match candidate {
ProjectionTyCandidate::ParamEnv(poly_projection) |
ProjectionTyCandidate::TraitDef(poly_projection) => {
confirm_param_env_candidate(selcx, obligation, poly_projection)
}
ProjectionTyCandidate::Impl(impl_vtable) => {
confirm_impl_candidate(selcx, obligation, impl_vtable)
}
ProjectionTyCandidate::Closure(closure_vtable) => {
confirm_closure_candidate(selcx, obligation, closure_vtable)
}
ProjectionTyCandidate::FnPointer(fn_type) => {
confirm_fn_pointer_candidate(selcx, obligation, fn_type)
}