-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
astconv.rs
2036 lines (1847 loc) · 85.2 KB
/
astconv.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
//! Conversion from AST representation of types to the `ty.rs` representation.
//! The main routine here is `ast_ty_to_ty()`; each use is is parameterized by
//! an instance of `AstConv`.
use errors::{Applicability, FatalError, DiagnosticId};
use hir::{self, GenericArg, GenericArgs};
use hir::def::Def;
use hir::def_id::DefId;
use hir::HirVec;
use lint;
use middle::resolve_lifetime as rl;
use namespace::Namespace;
use rustc::traits;
use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
use rustc::ty::{GenericParamDef, GenericParamDefKind};
use rustc::ty::subst::{Kind, Subst, Substs};
use rustc::ty::wf::object_region_bounds;
use rustc_data_structures::sync::Lrc;
use rustc_target::spec::abi;
use require_c_abi_if_variadic;
use smallvec::SmallVec;
use syntax::ast;
use syntax::feature_gate::{GateIssue, emit_feature_err};
use syntax::ptr::P;
use syntax::util::lev_distance::find_best_match_for_name;
use syntax_pos::{DUMMY_SP, Span, MultiSpan};
use util::common::ErrorReported;
use util::nodemap::FxHashMap;
use std::collections::BTreeSet;
use std::iter;
use std::slice;
use super::{check_type_alias_enum_variants_enabled};
use rustc_data_structures::fx::FxHashSet;
#[derive(Debug)]
pub struct PathSeg(pub DefId, pub usize);
pub trait AstConv<'gcx, 'tcx> {
fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
/// Returns the set of bounds in scope for the type parameter with
/// the given id.
fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
-> Lrc<ty::GenericPredicates<'tcx>>;
/// What lifetime should we use when a lifetime is omitted (and not elided)?
fn re_infer(&self, span: Span, _def: Option<&ty::GenericParamDef>)
-> Option<ty::Region<'tcx>>;
/// What type should we use when a type is omitted?
fn ty_infer(&self, span: Span) -> Ty<'tcx>;
/// Same as ty_infer, but with a known type parameter definition.
fn ty_infer_for_def(&self,
_def: &ty::GenericParamDef,
span: Span) -> Ty<'tcx> {
self.ty_infer(span)
}
/// Projecting an associated type from a (potentially)
/// higher-ranked trait reference is more complicated, because of
/// the possibility of late-bound regions appearing in the
/// associated type binding. This is not legal in function
/// signatures for that reason. In a function body, we can always
/// handle it because we can use inference variables to remove the
/// late-bound regions.
fn projected_ty_from_poly_trait_ref(&self,
span: Span,
item_def_id: DefId,
poly_trait_ref: ty::PolyTraitRef<'tcx>)
-> Ty<'tcx>;
/// Normalize an associated type coming from the user.
fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
/// Invoked when we encounter an error from some prior pass
/// (e.g., resolve) that is translated into a ty-error. This is
/// used to help suppress derived errors typeck might otherwise
/// report.
fn set_tainted_by_errors(&self);
fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
}
struct ConvertedBinding<'tcx> {
item_name: ast::Ident,
ty: Ty<'tcx>,
span: Span,
}
#[derive(PartialEq)]
enum GenericArgPosition {
Type,
Value, // e.g., functions
MethodCall,
}
/// Dummy type used for the `Self` of a `TraitRef` created for converting
/// a trait object, and which gets removed in `ExistentialTraitRef`.
/// This type must not appear anywhere in other converted types.
const TRAIT_OBJECT_DUMMY_SELF: ty::TyKind<'static> = ty::Infer(ty::FreshTy(0));
impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o {
pub fn ast_region_to_region(&self,
lifetime: &hir::Lifetime,
def: Option<&ty::GenericParamDef>)
-> ty::Region<'tcx>
{
let tcx = self.tcx();
let lifetime_name = |def_id| {
tcx.hir().name(tcx.hir().as_local_node_id(def_id).unwrap()).as_interned_str()
};
let hir_id = tcx.hir().node_to_hir_id(lifetime.id);
let r = match tcx.named_region(hir_id) {
Some(rl::Region::Static) => {
tcx.types.re_static
}
Some(rl::Region::LateBound(debruijn, id, _)) => {
let name = lifetime_name(id);
tcx.mk_region(ty::ReLateBound(debruijn,
ty::BrNamed(id, name)))
}
Some(rl::Region::LateBoundAnon(debruijn, index)) => {
tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
}
Some(rl::Region::EarlyBound(index, id, _)) => {
let name = lifetime_name(id);
tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
def_id: id,
index,
name,
}))
}
Some(rl::Region::Free(scope, id)) => {
let name = lifetime_name(id);
tcx.mk_region(ty::ReFree(ty::FreeRegion {
scope,
bound_region: ty::BrNamed(id, name)
}))
// (*) -- not late-bound, won't change
}
None => {
self.re_infer(lifetime.span, def)
.unwrap_or_else(|| {
// This indicates an illegal lifetime
// elision. `resolve_lifetime` should have
// reported an error in this case -- but if
// not, let's error out.
tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
// Supply some dummy value. We don't have an
// `re_error`, annoyingly, so use `'static`.
tcx.types.re_static
})
}
};
debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
lifetime,
r);
r
}
/// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
/// returns an appropriate set of substitutions for this particular reference to `I`.
pub fn ast_path_substs_for_ty(&self,
span: Span,
def_id: DefId,
item_segment: &hir::PathSegment)
-> &'tcx Substs<'tcx>
{
let (substs, assoc_bindings, _) = item_segment.with_generic_args(|generic_args| {
self.create_substs_for_ast_path(
span,
def_id,
generic_args,
item_segment.infer_types,
None,
)
});
assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
substs
}
/// Report error if there is an explicit type parameter when using `impl Trait`.
fn check_impl_trait(
tcx: TyCtxt,
span: Span,
seg: &hir::PathSegment,
generics: &ty::Generics,
) -> bool {
let explicit = !seg.infer_types;
let impl_trait = generics.params.iter().any(|param| match param.kind {
ty::GenericParamDefKind::Type {
synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
} => true,
_ => false,
});
if explicit && impl_trait {
let mut err = struct_span_err! {
tcx.sess,
span,
E0632,
"cannot provide explicit type parameters when `impl Trait` is \
used in argument position."
};
err.emit();
}
impl_trait
}
/// Check that the correct number of generic arguments have been provided.
/// Used specifically for function calls.
pub fn check_generic_arg_count_for_call(
tcx: TyCtxt,
span: Span,
def: &ty::Generics,
seg: &hir::PathSegment,
is_method_call: bool,
) -> bool {
let empty_args = P(hir::GenericArgs {
args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
});
let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def);
Self::check_generic_arg_count(
tcx,
span,
def,
if let Some(ref args) = seg.args {
args
} else {
&empty_args
},
if is_method_call {
GenericArgPosition::MethodCall
} else {
GenericArgPosition::Value
},
def.parent.is_none() && def.has_self, // `has_self`
seg.infer_types || suppress_mismatch, // `infer_types`
).0
}
/// Check that the correct number of generic arguments have been provided.
/// This is used both for datatypes and function calls.
fn check_generic_arg_count(
tcx: TyCtxt,
span: Span,
def: &ty::Generics,
args: &hir::GenericArgs,
position: GenericArgPosition,
has_self: bool,
infer_types: bool,
) -> (bool, Option<Vec<Span>>) {
// At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
// that lifetimes will proceed types. So it suffices to check the number of each generic
// arguments in order to validate them with respect to the generic parameters.
let param_counts = def.own_counts();
let arg_counts = args.own_counts();
let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
let mut defaults: ty::GenericParamCount = Default::default();
for param in &def.params {
match param.kind {
GenericParamDefKind::Lifetime => {}
GenericParamDefKind::Type { has_default, .. } => {
defaults.types += has_default as usize
}
};
}
if position != GenericArgPosition::Type && !args.bindings.is_empty() {
AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
}
// Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
if !infer_lifetimes {
if let Some(span_late) = def.has_late_bound_regions {
let msg = "cannot specify lifetime arguments explicitly \
if late bound lifetime parameters are present";
let note = "the late bound lifetime parameter is introduced here";
let span = args.args[0].span();
if position == GenericArgPosition::Value
&& arg_counts.lifetimes != param_counts.lifetimes {
let mut err = tcx.sess.struct_span_err(span, msg);
err.span_note(span_late, note);
err.emit();
return (true, None);
} else {
let mut multispan = MultiSpan::from_span(span);
multispan.push_span_label(span_late, note.to_string());
tcx.lint_node(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
args.args[0].id(), multispan, msg);
return (false, None);
}
}
}
let check_kind_count = |kind,
required,
permitted,
provided,
offset| {
// We enforce the following: `required` <= `provided` <= `permitted`.
// For kinds without defaults (i.e., lifetimes), `required == permitted`.
// For other kinds (i.e., types), `permitted` may be greater than `required`.
if required <= provided && provided <= permitted {
return (false, None);
}
// Unfortunately lifetime and type parameter mismatches are typically styled
// differently in diagnostics, which means we have a few cases to consider here.
let (bound, quantifier) = if required != permitted {
if provided < required {
(required, "at least ")
} else { // provided > permitted
(permitted, "at most ")
}
} else {
(required, "")
};
let mut potential_assoc_types: Option<Vec<Span>> = None;
let (spans, label) = if required == permitted && provided > permitted {
// In the case when the user has provided too many arguments,
// we want to point to the unexpected arguments.
let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
.iter()
.map(|arg| arg.span())
.collect();
potential_assoc_types = Some(spans.clone());
(spans, format!( "unexpected {} argument", kind))
} else {
(vec![span], format!(
"expected {}{} {} argument{}",
quantifier,
bound,
kind,
if bound != 1 { "s" } else { "" },
))
};
let mut err = tcx.sess.struct_span_err_with_code(
spans.clone(),
&format!(
"wrong number of {} arguments: expected {}{}, found {}",
kind,
quantifier,
bound,
provided,
),
DiagnosticId::Error("E0107".into())
);
for span in spans {
err.span_label(span, label.as_str());
}
err.emit();
(provided > required, // `suppress_error`
potential_assoc_types)
};
if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
check_kind_count(
"lifetime",
param_counts.lifetimes,
param_counts.lifetimes,
arg_counts.lifetimes,
0,
);
}
if !infer_types
|| arg_counts.types > param_counts.types - defaults.types - has_self as usize {
check_kind_count(
"type",
param_counts.types - defaults.types - has_self as usize,
param_counts.types - has_self as usize,
arg_counts.types,
arg_counts.lifetimes,
)
} else {
(false, None)
}
}
/// Creates the relevant generic argument substitutions
/// corresponding to a set of generic parameters. This is a
/// rather complex little function. Let me try to explain the
/// role of each of its parameters:
///
/// To start, we are given the `def_id` of the thing we are
/// creating the substitutions for, and a partial set of
/// substitutions `parent_substs`. In general, the substitutions
/// for an item begin with substitutions for all the "parents" of
/// that item -- e.g., for a method it might include the
/// parameters from the impl.
///
/// Therefore, the method begins by walking down these parents,
/// starting with the outermost parent and proceed inwards until
/// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
/// first to see if the parent's substitutions are listed in there. If so,
/// we can append those and move on. Otherwise, it invokes the
/// three callback functions:
///
/// - `args_for_def_id`: given the def-id `P`, supplies back the
/// generic arguments that were given to that parent from within
/// the path; so e.g., if you have `<T as Foo>::Bar`, the def-id
/// might refer to the trait `Foo`, and the arguments might be
/// `[T]`. The boolean value indicates whether to infer values
/// for arguments whose values were not explicitly provided.
/// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
/// instantiate a `Kind`.
/// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
/// creates a suitable inference variable.
pub fn create_substs_for_generic_args<'a, 'b>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
def_id: DefId,
parent_substs: &[Kind<'tcx>],
has_self: bool,
self_ty: Option<Ty<'tcx>>,
args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>,
) -> &'tcx Substs<'tcx> {
// Collect the segments of the path; we need to substitute arguments
// for parameters throughout the entire path (wherever there are
// generic parameters).
let mut parent_defs = tcx.generics_of(def_id);
let count = parent_defs.count();
let mut stack = vec![(def_id, parent_defs)];
while let Some(def_id) = parent_defs.parent {
parent_defs = tcx.generics_of(def_id);
stack.push((def_id, parent_defs));
}
// We manually build up the substitution, rather than using convenience
// methods in `subst.rs`, so that we can iterate over the arguments and
// parameters in lock-step linearly, instead of trying to match each pair.
let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
// Iterate over each segment of the path.
while let Some((def_id, defs)) = stack.pop() {
let mut params = defs.params.iter().peekable();
// If we have already computed substitutions for parents, we can use those directly.
while let Some(¶m) = params.peek() {
if let Some(&kind) = parent_substs.get(param.index as usize) {
substs.push(kind);
params.next();
} else {
break;
}
}
// `Self` is handled first, unless it's been handled in `parent_substs`.
if has_self {
if let Some(¶m) = params.peek() {
if param.index == 0 {
if let GenericParamDefKind::Type { .. } = param.kind {
substs.push(self_ty.map(|ty| ty.into())
.unwrap_or_else(|| inferred_kind(None, param, true)));
params.next();
}
}
}
}
// Check whether this segment takes generic arguments and the user has provided any.
let (generic_args, infer_types) = args_for_def_id(def_id);
let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
.peekable();
loop {
// We're going to iterate through the generic arguments that the user
// provided, matching them with the generic parameters we expect.
// Mismatches can occur as a result of elided lifetimes, or for malformed
// input. We try to handle both sensibly.
match (args.peek(), params.peek()) {
(Some(&arg), Some(¶m)) => {
match (arg, ¶m.kind) {
(GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
| (GenericArg::Type(_), GenericParamDefKind::Type { .. }) => {
substs.push(provided_kind(param, arg));
args.next();
params.next();
}
(GenericArg::Lifetime(_), GenericParamDefKind::Type { .. }) => {
// We expected a type argument, but got a lifetime
// argument. This is an error, but we need to handle it
// gracefully so we can report sensible errors. In this
// case, we're simply going to infer this argument.
args.next();
}
(GenericArg::Type(_), GenericParamDefKind::Lifetime) => {
// We expected a lifetime argument, but got a type
// argument. That means we're inferring the lifetimes.
substs.push(inferred_kind(None, param, infer_types));
params.next();
}
}
}
(Some(_), None) => {
// We should never be able to reach this point with well-formed input.
// Getting to this point means the user supplied more arguments than
// there are parameters.
args.next();
}
(None, Some(¶m)) => {
// If there are fewer arguments than parameters, it means
// we're inferring the remaining arguments.
match param.kind {
GenericParamDefKind::Lifetime | GenericParamDefKind::Type { .. } => {
let kind = inferred_kind(Some(&substs), param, infer_types);
substs.push(kind);
}
}
args.next();
params.next();
}
(None, None) => break,
}
}
}
tcx.intern_substs(&substs)
}
/// Given the type/region arguments provided to some path (along with
/// an implicit `Self`, if this is a trait reference) returns the complete
/// set of substitutions. This may involve applying defaulted type parameters.
///
/// Note that the type listing given here is *exactly* what the user provided.
fn create_substs_for_ast_path(&self,
span: Span,
def_id: DefId,
generic_args: &hir::GenericArgs,
infer_types: bool,
self_ty: Option<Ty<'tcx>>)
-> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>)
{
// If the type is parameterized by this region, then replace this
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
generic_args={:?})",
def_id, self_ty, generic_args);
let tcx = self.tcx();
let generic_params = tcx.generics_of(def_id);
// If a self-type was declared, one should be provided.
assert_eq!(generic_params.has_self, self_ty.is_some());
let has_self = generic_params.has_self;
let (_, potential_assoc_types) = Self::check_generic_arg_count(
tcx,
span,
&generic_params,
&generic_args,
GenericArgPosition::Type,
has_self,
infer_types,
);
let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
let default_needs_object_self = |param: &ty::GenericParamDef| {
if let GenericParamDefKind::Type { has_default, .. } = param.kind {
if is_object && has_default {
if tcx.at(span).type_of(param.def_id).has_self_ty() {
// There is no suitable inference default for a type parameter
// that references self, in an object type.
return true;
}
}
}
false
};
let substs = Self::create_substs_for_generic_args(
tcx,
def_id,
&[][..],
self_ty.is_some(),
self_ty,
// Provide the generic args, and whether types should be inferred.
|_| (Some(generic_args), infer_types),
// Provide substitutions for parameters for which (valid) arguments have been provided.
|param, arg| {
match (¶m.kind, arg) {
(GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
self.ast_region_to_region(<, Some(param)).into()
}
(GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
self.ast_ty_to_ty(&ty).into()
}
_ => unreachable!(),
}
},
// Provide substitutions for parameters for which arguments are inferred.
|substs, param, infer_types| {
match param.kind {
GenericParamDefKind::Lifetime => tcx.types.re_static.into(),
GenericParamDefKind::Type { has_default, .. } => {
if !infer_types && has_default {
// No type parameter provided, but a default exists.
// If we are converting an object type, then the
// `Self` parameter is unknown. However, some of the
// other type parameters may reference `Self` in their
// defaults. This will lead to an ICE if we are not
// careful!
if default_needs_object_self(param) {
struct_span_err!(tcx.sess, span, E0393,
"the type parameter `{}` must be explicitly \
specified",
param.name)
.span_label(span,
format!("missing reference to `{}`", param.name))
.note(&format!("because of the default `Self` reference, \
type parameters must be specified on object \
types"))
.emit();
tcx.types.err.into()
} else {
// This is a default type parameter.
self.normalize_ty(
span,
tcx.at(span).type_of(param.def_id)
.subst_spanned(tcx, substs.unwrap(), Some(span))
).into()
}
} else if infer_types {
// No type parameters were provided, we can infer all.
if !default_needs_object_self(param) {
self.ty_infer_for_def(param, span).into()
} else {
self.ty_infer(span).into()
}
} else {
// We've already errored above about the mismatch.
tcx.types.err.into()
}
}
}
},
);
let assoc_bindings = generic_args.bindings.iter().map(|binding| {
ConvertedBinding {
item_name: binding.ident,
ty: self.ast_ty_to_ty(&binding.ty),
span: binding.span,
}
}).collect();
debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
generic_params, self_ty, substs);
(substs, assoc_bindings, potential_assoc_types)
}
/// Instantiates the path for the given trait reference, assuming that it's
/// bound to a valid trait type. Returns the def_id for the defining trait.
/// The type _cannot_ be a type other than a trait type.
///
/// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
/// are disallowed. Otherwise, they are pushed onto the vector given.
pub fn instantiate_mono_trait_ref(&self,
trait_ref: &hir::TraitRef,
self_ty: Ty<'tcx>)
-> ty::TraitRef<'tcx>
{
self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
let trait_def_id = self.trait_def_id(trait_ref);
self.ast_path_to_mono_trait_ref(trait_ref.path.span,
trait_def_id,
self_ty,
trait_ref.path.segments.last().unwrap())
}
/// Get the `DefId` of the given trait ref. It _must_ actually be a trait.
fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
let path = &trait_ref.path;
match path.def {
Def::Trait(trait_def_id) => trait_def_id,
Def::TraitAlias(alias_def_id) => alias_def_id,
Def::Err => {
FatalError.raise();
}
_ => unreachable!(),
}
}
/// The given trait ref must actually be a trait.
pub(super) fn instantiate_poly_trait_ref_inner(&self,
trait_ref: &hir::TraitRef,
self_ty: Ty<'tcx>,
poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
speculative: bool)
-> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
{
let trait_def_id = self.trait_def_id(trait_ref);
debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
trait_ref.path.span,
trait_def_id,
self_ty,
trait_ref.path.segments.last().unwrap(),
);
let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
let mut dup_bindings = FxHashMap::default();
poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
// specify type to assert that error was already reported in Err case:
let predicate: Result<_, ErrorReported> =
self.ast_type_binding_to_poly_projection_predicate(
trait_ref.ref_id, poly_trait_ref, binding, speculative, &mut dup_bindings);
// okay to ignore Err because of ErrorReported (see above)
Some((predicate.ok()?, binding.span))
}));
debug!("instantiate_poly_trait_ref({:?}, projections={:?}) -> {:?}",
trait_ref, poly_projections, poly_trait_ref);
(poly_trait_ref, potential_assoc_types)
}
pub fn instantiate_poly_trait_ref(&self,
poly_trait_ref: &hir::PolyTraitRef,
self_ty: Ty<'tcx>,
poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>)
-> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
{
self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
poly_projections, false)
}
fn ast_path_to_mono_trait_ref(&self,
span: Span,
trait_def_id: DefId,
self_ty: Ty<'tcx>,
trait_segment: &hir::PathSegment)
-> ty::TraitRef<'tcx>
{
let (substs, assoc_bindings, _) =
self.create_substs_for_ast_trait_ref(span,
trait_def_id,
self_ty,
trait_segment);
assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
ty::TraitRef::new(trait_def_id, substs)
}
fn create_substs_for_ast_trait_ref(
&self,
span: Span,
trait_def_id: DefId,
self_ty: Ty<'tcx>,
trait_segment: &hir::PathSegment,
) -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>) {
debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
trait_segment);
let trait_def = self.tcx().trait_def(trait_def_id);
if !self.tcx().features().unboxed_closures &&
trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
!= trait_def.paren_sugar {
// For now, require that parenthetical notation be used only with `Fn()` etc.
let msg = if trait_def.paren_sugar {
"the precise format of `Fn`-family traits' type parameters is subject to change. \
Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
} else {
"parenthetical notation is only stable when used with `Fn`-family traits"
};
emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
span, GateIssue::Language, msg);
}
trait_segment.with_generic_args(|generic_args| {
self.create_substs_for_ast_path(span,
trait_def_id,
generic_args,
trait_segment.infer_types,
Some(self_ty))
})
}
fn trait_defines_associated_type_named(&self,
trait_def_id: DefId,
assoc_name: ast::Ident)
-> bool
{
self.tcx().associated_items(trait_def_id).any(|item| {
item.kind == ty::AssociatedKind::Type &&
self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
})
}
fn ast_type_binding_to_poly_projection_predicate(
&self,
ref_id: ast::NodeId,
trait_ref: ty::PolyTraitRef<'tcx>,
binding: &ConvertedBinding<'tcx>,
speculative: bool,
dup_bindings: &mut FxHashMap<DefId, Span>)
-> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
{
let tcx = self.tcx();
if !speculative {
// Given something like `U: SomeTrait<T = X>`, we want to produce a
// predicate like `<U as SomeTrait>::T = X`. This is somewhat
// subtle in the event that `T` is defined in a supertrait of
// `SomeTrait`, because in that case we need to upcast.
//
// That is, consider this case:
//
// ```
// trait SubTrait: SuperTrait<int> { }
// trait SuperTrait<A> { type T; }
//
// ... B : SubTrait<T=foo> ...
// ```
//
// We want to produce `<B as SuperTrait<int>>::T == foo`.
// Find any late-bound regions declared in `ty` that are not
// declared in the trait-ref. These are not wellformed.
//
// Example:
//
// for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
// for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
let late_bound_in_ty =
tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(binding.ty));
debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
let br_name = match *br {
ty::BrNamed(_, name) => name,
_ => {
span_bug!(
binding.span,
"anonymous bound region {:?} in binding but not trait ref",
br);
}
};
struct_span_err!(tcx.sess,
binding.span,
E0582,
"binding for associated type `{}` references lifetime `{}`, \
which does not appear in the trait input types",
binding.item_name, br_name)
.emit();
}
}
let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
binding.item_name) {
// Simple case: X is defined in the current trait.
Ok(trait_ref)
} else {
// Otherwise, we have to walk through the supertraits to find
// those that do.
let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
});
self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
binding.item_name, binding.span)
}?;
let (assoc_ident, def_scope) =
tcx.adjust_ident(binding.item_name, candidate.def_id(), ref_id);
let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
i.kind == ty::AssociatedKind::Type && i.ident.modern() == assoc_ident
}).expect("missing associated type");
if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
let msg = format!("associated type `{}` is private", binding.item_name);
tcx.sess.span_err(binding.span, &msg);
}
tcx.check_stability(assoc_ty.def_id, Some(ref_id), binding.span);
if !speculative {
dup_bindings.entry(assoc_ty.def_id)
.and_modify(|prev_span| {
struct_span_err!(self.tcx().sess, binding.span, E0719,
"the value of the associated type `{}` (from the trait `{}`) \
is already specified",
binding.item_name,
tcx.item_path_str(assoc_ty.container.id()))
.span_label(binding.span, "re-bound here")
.span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
.emit();
})
.or_insert(binding.span);
}
Ok(candidate.map_bound(|trait_ref| {
ty::ProjectionPredicate {
projection_ty: ty::ProjectionTy::from_ref_and_name(
tcx,
trait_ref,
binding.item_name,
),
ty: binding.ty,
}
}))
}
fn ast_path_to_ty(&self,
span: Span,
did: DefId,
item_segment: &hir::PathSegment)
-> Ty<'tcx>
{
let substs = self.ast_path_substs_for_ty(span, did, item_segment);
self.normalize_ty(
span,
self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
)
}
/// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
/// removing the dummy `Self` type (`TRAIT_OBJECT_DUMMY_SELF`).
fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
-> ty::ExistentialTraitRef<'tcx> {
assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
}
fn conv_object_ty_poly_trait_ref(&self,
span: Span,
trait_bounds: &[hir::PolyTraitRef],
lifetime: &hir::Lifetime)
-> Ty<'tcx>
{
let tcx = self.tcx();
if trait_bounds.is_empty() {
span_err!(tcx.sess, span, E0224,
"at least one non-builtin trait is required for an object type");
return tcx.types.err;
}
let mut projection_bounds = Vec::new();
let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
let (principal, potential_assoc_types) = self.instantiate_poly_trait_ref(
&trait_bounds[0],
dummy_self,
&mut projection_bounds,
);
debug!("principal: {:?}", principal);
for trait_bound in trait_bounds[1..].iter() {
// sanity check for non-principal trait bounds
self.instantiate_poly_trait_ref(trait_bound,
dummy_self,
&mut vec![]);
}
let (mut auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
if !trait_bounds.is_empty() {
let b = &trait_bounds[0];
let span = b.trait_ref.path.span;
struct_span_err!(self.tcx().sess, span, E0225,
"only auto traits can be used as additional traits in a trait object")
.span_label(span, "non-auto additional trait")
.emit();
}
// Check that there are no gross object safety violations;
// most importantly, that the supertraits don't contain `Self`,
// to avoid ICEs.
let object_safety_violations =
tcx.global_tcx().astconv_object_safety_violations(principal.def_id());