-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
collect.rs
1700 lines (1500 loc) · 61.2 KB
/
collect.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 2012-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.
//! "Collection" is the process of determining the type and other external
//! details of each item in Rust. Collection is specifically concerned
//! with *interprocedural* things -- for example, for a function
//! definition, collection will figure out the type and signature of the
//! function, but it will not visit the *body* of the function in any way,
//! nor examine type annotations on local variables (that's the job of
//! type *checking*).
//!
//! Collecting is ultimately defined by a bundle of queries that
//! inquire after various facts about the items in the crate (e.g.,
//! `type_of`, `generics_of`, `predicates_of`, etc). See the `provide` function
//! for the full set.
//!
//! At present, however, we do run collection across all items in the
//! crate as a kind of pass. This should eventually be factored away.
use astconv::{AstConv, Bounds};
use lint;
use constrained_type_params as ctp;
use middle::lang_items::SizedTraitLangItem;
use middle::const_val::ConstVal;
use middle::resolve_lifetime as rl;
use rustc::traits::Reveal;
use rustc::ty::subst::Substs;
use rustc::ty::{ToPredicate, ReprOptions};
use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
use rustc::ty::maps::Providers;
use rustc::ty::util::IntTypeExt;
use util::nodemap::FxHashMap;
use rustc_const_math::ConstInt;
use std::collections::BTreeMap;
use syntax::{abi, ast};
use syntax::codemap::Spanned;
use syntax::symbol::{Symbol, keywords};
use syntax_pos::{Span, DUMMY_SP};
use rustc::hir::{self, map as hir_map};
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::def::{Def, CtorKind};
use rustc::hir::def_id::DefId;
///////////////////////////////////////////////////////////////////////////
// Main entry point
pub fn collect_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
let mut visitor = CollectItemTypesVisitor { tcx: tcx };
tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
}
pub fn provide(providers: &mut Providers) {
*providers = Providers {
type_of,
generics_of,
predicates_of,
super_predicates_of,
type_param_predicates,
trait_def,
adt_def,
fn_sig,
impl_trait_ref,
impl_polarity,
is_foreign_item,
is_default_impl,
..*providers
};
}
///////////////////////////////////////////////////////////////////////////
/// Context specific to some particular item. This is what implements
/// AstConv. It has information about the predicates that are defined
/// on the trait. Unfortunately, this predicate information is
/// available in various different forms at various points in the
/// process. So we can't just store a pointer to e.g. the AST or the
/// parsed ty form, we have to be more flexible. To this end, the
/// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy
/// `get_type_parameter_bounds` requests, drawing the information from
/// the AST (`hir::Generics`), recursively.
pub struct ItemCtxt<'a,'tcx:'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
item_def_id: DefId,
}
///////////////////////////////////////////////////////////////////////////
struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>
}
impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
NestedVisitorMap::OnlyBodies(&self.tcx.hir)
}
fn visit_item(&mut self, item: &'tcx hir::Item) {
convert_item(self.tcx, item.id);
intravisit::walk_item(self, item);
}
fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
for param in &generics.ty_params {
if param.default.is_some() {
let def_id = self.tcx.hir.local_def_id(param.id);
self.tcx.type_of(def_id);
}
}
intravisit::walk_generics(self, generics);
}
fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
if let hir::ExprClosure(..) = expr.node {
let def_id = self.tcx.hir.local_def_id(expr.id);
self.tcx.generics_of(def_id);
self.tcx.type_of(def_id);
}
intravisit::walk_expr(self, expr);
}
fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
if let hir::TyImplTrait(..) = ty.node {
let def_id = self.tcx.hir.local_def_id(ty.id);
self.tcx.generics_of(def_id);
self.tcx.predicates_of(def_id);
}
intravisit::walk_ty(self, ty);
}
fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
convert_trait_item(self.tcx, trait_item.id);
intravisit::walk_trait_item(self, trait_item);
}
fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
convert_impl_item(self.tcx, impl_item.id);
intravisit::walk_impl_item(self, impl_item);
}
}
///////////////////////////////////////////////////////////////////////////
// Utility types and common code for the above passes.
impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId)
-> ItemCtxt<'a,'tcx> {
ItemCtxt {
tcx,
item_def_id,
}
}
}
impl<'a,'tcx> ItemCtxt<'a,'tcx> {
pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
AstConv::ast_ty_to_ty(self, ast_ty)
}
}
impl<'a, 'tcx> AstConv<'tcx, 'tcx> for ItemCtxt<'a, 'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> { self.tcx }
fn get_type_parameter_bounds(&self,
span: Span,
def_id: DefId)
-> ty::GenericPredicates<'tcx>
{
self.tcx.at(span).type_param_predicates((self.item_def_id, def_id))
}
fn re_infer(&self, _span: Span, _def: Option<&ty::RegionParameterDef>)
-> Option<ty::Region<'tcx>> {
None
}
fn ty_infer(&self, span: Span) -> Ty<'tcx> {
struct_span_err!(
self.tcx().sess,
span,
E0121,
"the type placeholder `_` is not allowed within types on item signatures"
).span_label(span, "not allowed in type signatures")
.emit();
self.tcx().types.err
}
fn projected_ty_from_poly_trait_ref(&self,
span: Span,
item_def_id: DefId,
poly_trait_ref: ty::PolyTraitRef<'tcx>)
-> Ty<'tcx>
{
if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) {
self.tcx().mk_projection(item_def_id, trait_ref.substs)
} else {
// no late-bound regions, we can just ignore the binder
span_err!(self.tcx().sess, span, E0212,
"cannot extract an associated type from a higher-ranked trait bound \
in this context");
self.tcx().types.err
}
}
fn normalize_ty(&self, _span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
// types in item signatures are not normalized, to avoid undue
// dependencies.
ty
}
fn set_tainted_by_errors(&self) {
// no obvious place to track this, just let it go
}
fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
// no place to record types from signatures?
}
}
fn type_param_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
(item_def_id, def_id): (DefId, DefId))
-> ty::GenericPredicates<'tcx> {
use rustc::hir::map::*;
use rustc::hir::*;
// In the AST, bounds can derive from two places. Either
// written inline like `<T:Foo>` or in a where clause like
// `where T:Foo`.
let param_id = tcx.hir.as_local_node_id(def_id).unwrap();
let param_owner = tcx.hir.ty_param_owner(param_id);
let param_owner_def_id = tcx.hir.local_def_id(param_owner);
let generics = tcx.generics_of(param_owner_def_id);
let index = generics.type_param_to_index[&def_id.index];
let ty = tcx.mk_param(index, tcx.hir.ty_param_name(param_id));
// Don't look for bounds where the type parameter isn't in scope.
let parent = if item_def_id == param_owner_def_id {
None
} else {
tcx.generics_of(item_def_id).parent
};
let mut result = parent.map_or(ty::GenericPredicates {
parent: None,
predicates: vec![]
}, |parent| {
let icx = ItemCtxt::new(tcx, parent);
icx.get_type_parameter_bounds(DUMMY_SP, def_id)
});
let item_node_id = tcx.hir.as_local_node_id(item_def_id).unwrap();
let ast_generics = match tcx.hir.get(item_node_id) {
NodeTraitItem(item) => {
match item.node {
TraitItemKind::Method(ref sig, _) => &sig.generics,
_ => return result
}
}
NodeImplItem(item) => {
match item.node {
ImplItemKind::Method(ref sig, _) => &sig.generics,
_ => return result
}
}
NodeItem(item) => {
match item.node {
ItemFn(.., ref generics, _) |
ItemImpl(_, _, _, ref generics, ..) |
ItemTy(_, ref generics) |
ItemEnum(_, ref generics) |
ItemStruct(_, ref generics) |
ItemUnion(_, ref generics) => generics,
ItemTrait(_, ref generics, ..) => {
// Implied `Self: Trait` and supertrait bounds.
if param_id == item_node_id {
result.predicates.push(ty::TraitRef {
def_id: item_def_id,
substs: Substs::identity_for_item(tcx, item_def_id)
}.to_predicate());
}
generics
}
_ => return result
}
}
NodeForeignItem(item) => {
match item.node {
ForeignItemFn(_, _, ref generics) => generics,
_ => return result
}
}
_ => return result
};
let icx = ItemCtxt::new(tcx, item_def_id);
result.predicates.extend(
icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty));
result
}
impl<'a, 'tcx> ItemCtxt<'a, 'tcx> {
/// Find bounds from hir::Generics. This requires scanning through the
/// AST. We do this to avoid having to convert *all* the bounds, which
/// would create artificial cycles. Instead we can only convert the
/// bounds for a type parameter `X` if `X::Foo` is used.
fn type_parameter_bounds_in_generics(&self,
ast_generics: &hir::Generics,
param_id: ast::NodeId,
ty: Ty<'tcx>)
-> Vec<ty::Predicate<'tcx>>
{
let from_ty_params =
ast_generics.ty_params
.iter()
.filter(|p| p.id == param_id)
.flat_map(|p| p.bounds.iter())
.flat_map(|b| predicates_from_bound(self, ty, b));
let from_where_clauses =
ast_generics.where_clause
.predicates
.iter()
.filter_map(|wp| match *wp {
hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
_ => None
})
.filter(|bp| is_param(self.tcx, &bp.bounded_ty, param_id))
.flat_map(|bp| bp.bounds.iter())
.flat_map(|b| predicates_from_bound(self, ty, b));
from_ty_params.chain(from_where_clauses).collect()
}
}
/// Tests whether this is the AST for a reference to the type
/// parameter with id `param_id`. We use this so as to avoid running
/// `ast_ty_to_ty`, because we want to avoid triggering an all-out
/// conversion of the type to avoid inducing unnecessary cycles.
fn is_param<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
ast_ty: &hir::Ty,
param_id: ast::NodeId)
-> bool
{
if let hir::TyPath(hir::QPath::Resolved(None, ref path)) = ast_ty.node {
match path.def {
Def::SelfTy(Some(def_id), None) |
Def::TyParam(def_id) => {
def_id == tcx.hir.local_def_id(param_id)
}
_ => false
}
} else {
false
}
}
fn ensure_no_ty_param_bounds(tcx: TyCtxt,
span: Span,
generics: &hir::Generics,
thing: &'static str) {
let mut warn = false;
for ty_param in generics.ty_params.iter() {
for bound in ty_param.bounds.iter() {
match *bound {
hir::TraitTyParamBound(..) => {
warn = true;
}
hir::RegionTyParamBound(..) => { }
}
}
}
for predicate in generics.where_clause.predicates.iter() {
match *predicate {
hir::WherePredicate::BoundPredicate(..) => {
warn = true;
}
hir::WherePredicate::RegionPredicate(..) => { }
hir::WherePredicate::EqPredicate(..) => { }
}
}
if warn {
// According to accepted RFC #XXX, we should
// eventually accept these, but it will not be
// part of this PR. Still, convert to warning to
// make bootstrapping easier.
span_warn!(tcx.sess, span, E0122,
"trait bounds are not (yet) enforced \
in {} definitions",
thing);
}
}
fn convert_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId) {
let it = tcx.hir.expect_item(item_id);
debug!("convert: item {} with id {}", it.name, it.id);
let def_id = tcx.hir.local_def_id(item_id);
match it.node {
// These don't define types.
hir::ItemExternCrate(_) |
hir::ItemUse(..) |
hir::ItemMod(_) |
hir::ItemGlobalAsm(_) => {}
hir::ItemForeignMod(ref foreign_mod) => {
for item in &foreign_mod.items {
let def_id = tcx.hir.local_def_id(item.id);
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
if let hir::ForeignItemFn(..) = item.node {
tcx.fn_sig(def_id);
}
}
}
hir::ItemEnum(ref enum_definition, _) => {
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
convert_enum_variant_types(tcx, def_id, &enum_definition.variants);
},
hir::ItemDefaultImpl(..) => {
tcx.impl_trait_ref(def_id);
}
hir::ItemImpl(..) => {
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.impl_trait_ref(def_id);
tcx.predicates_of(def_id);
},
hir::ItemTrait(..) => {
tcx.generics_of(def_id);
tcx.trait_def(def_id);
tcx.at(it.span).super_predicates_of(def_id);
tcx.predicates_of(def_id);
},
hir::ItemStruct(ref struct_def, _) |
hir::ItemUnion(ref struct_def, _) => {
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
for f in struct_def.fields() {
let def_id = tcx.hir.local_def_id(f.id);
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
}
if !struct_def.is_struct() {
convert_variant_ctor(tcx, struct_def.id());
}
},
hir::ItemTy(_, ref generics) => {
ensure_no_ty_param_bounds(tcx, it.span, generics, "type");
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
}
hir::ItemStatic(..) | hir::ItemConst(..) | hir::ItemFn(..) => {
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
if let hir::ItemFn(..) = it.node {
tcx.fn_sig(def_id);
}
}
}
}
fn convert_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_item_id: ast::NodeId) {
let trait_item = tcx.hir.expect_trait_item(trait_item_id);
let def_id = tcx.hir.local_def_id(trait_item.id);
tcx.generics_of(def_id);
match trait_item.node {
hir::TraitItemKind::Const(..) |
hir::TraitItemKind::Type(_, Some(_)) |
hir::TraitItemKind::Method(..) => {
tcx.type_of(def_id);
if let hir::TraitItemKind::Method(..) = trait_item.node {
tcx.fn_sig(def_id);
}
}
hir::TraitItemKind::Type(_, None) => {}
};
tcx.predicates_of(def_id);
}
fn convert_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item_id: ast::NodeId) {
let def_id = tcx.hir.local_def_id(impl_item_id);
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
if let hir::ImplItemKind::Method(..) = tcx.hir.expect_impl_item(impl_item_id).node {
tcx.fn_sig(def_id);
}
}
fn convert_variant_ctor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
ctor_id: ast::NodeId) {
let def_id = tcx.hir.local_def_id(ctor_id);
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
}
fn convert_enum_variant_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId,
variants: &[hir::Variant]) {
let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
let def = tcx.adt_def(def_id);
let repr_type = def.repr.discr_type();
let initial = repr_type.initial_discriminant(tcx);
let mut prev_discr = None::<ConstInt>;
// fill the discriminant values and field types
for variant in variants {
let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr());
prev_discr = Some(if let Some(e) = variant.node.disr_expr {
let expr_did = tcx.hir.local_def_id(e.node_id);
let substs = Substs::identity_for_item(tcx, expr_did);
let result = tcx.at(variant.span).const_eval(param_env.and((expr_did, substs)));
// enum variant evaluation happens before the global constant check
// so we need to report the real error
if let Err(ref err) = result {
err.report(tcx, variant.span, "enum discriminant");
}
match result {
Ok(&ty::Const { val: ConstVal::Integral(x), .. }) => Some(x),
_ => None
}
} else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
Some(discr)
} else {
struct_span_err!(tcx.sess, variant.span, E0370,
"enum discriminant overflowed")
.span_label(variant.span, format!("overflowed on value after {}",
prev_discr.unwrap()))
.note(&format!("explicitly set `{} = {}` if that is desired outcome",
variant.node.name, wrapped_discr))
.emit();
None
}.unwrap_or(wrapped_discr));
for f in variant.node.data.fields() {
let def_id = tcx.hir.local_def_id(f.id);
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
}
// Convert the ctor, if any. This also registers the variant as
// an item.
convert_variant_ctor(tcx, variant.node.data.id());
}
}
fn convert_struct_variant<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
did: DefId,
name: ast::Name,
discr: ty::VariantDiscr,
def: &hir::VariantData)
-> ty::VariantDef {
let mut seen_fields: FxHashMap<ast::Name, Span> = FxHashMap();
let node_id = tcx.hir.as_local_node_id(did).unwrap();
let fields = def.fields().iter().map(|f| {
let fid = tcx.hir.local_def_id(f.id);
let dup_span = seen_fields.get(&f.name).cloned();
if let Some(prev_span) = dup_span {
struct_span_err!(tcx.sess, f.span, E0124,
"field `{}` is already declared",
f.name)
.span_label(f.span, "field already declared")
.span_label(prev_span, format!("`{}` first declared here", f.name))
.emit();
} else {
seen_fields.insert(f.name, f.span);
}
ty::FieldDef {
did: fid,
name: f.name,
vis: ty::Visibility::from_hir(&f.vis, node_id, tcx)
}
}).collect();
ty::VariantDef {
did,
name,
discr,
fields,
ctor_kind: CtorKind::from_hir(def),
}
}
fn adt_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId)
-> &'tcx ty::AdtDef {
use rustc::hir::map::*;
use rustc::hir::*;
let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
let item = match tcx.hir.get(node_id) {
NodeItem(item) => item,
_ => bug!()
};
let repr = ReprOptions::new(tcx, def_id);
let (kind, variants) = match item.node {
ItemEnum(ref def, _) => {
let mut distance_from_explicit = 0;
(AdtKind::Enum, def.variants.iter().map(|v| {
let did = tcx.hir.local_def_id(v.node.data.id());
let discr = if let Some(e) = v.node.disr_expr {
distance_from_explicit = 0;
ty::VariantDiscr::Explicit(tcx.hir.local_def_id(e.node_id))
} else {
ty::VariantDiscr::Relative(distance_from_explicit)
};
distance_from_explicit += 1;
convert_struct_variant(tcx, did, v.node.name, discr, &v.node.data)
}).collect())
}
ItemStruct(ref def, _) => {
// Use separate constructor id for unit/tuple structs and reuse did for braced structs.
let ctor_id = if !def.is_struct() {
Some(tcx.hir.local_def_id(def.id()))
} else {
None
};
(AdtKind::Struct, vec![
convert_struct_variant(tcx, ctor_id.unwrap_or(def_id), item.name,
ty::VariantDiscr::Relative(0), def)
])
}
ItemUnion(ref def, _) => {
(AdtKind::Union, vec![
convert_struct_variant(tcx, def_id, item.name,
ty::VariantDiscr::Relative(0), def)
])
}
_ => bug!()
};
tcx.alloc_adt_def(def_id, kind, variants, repr)
}
/// Ensures that the super-predicates of the trait with def-id
/// trait_def_id are converted and stored. This also ensures that
/// the transitive super-predicates are converted;
fn super_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
trait_def_id: DefId)
-> ty::GenericPredicates<'tcx> {
debug!("super_predicates(trait_def_id={:?})", trait_def_id);
let trait_node_id = tcx.hir.as_local_node_id(trait_def_id).unwrap();
let item = match tcx.hir.get(trait_node_id) {
hir_map::NodeItem(item) => item,
_ => bug!("trait_node_id {} is not an item", trait_node_id)
};
let (generics, bounds) = match item.node {
hir::ItemTrait(_, ref generics, ref supertraits, _) => (generics, supertraits),
_ => span_bug!(item.span,
"super_predicates invoked on non-trait"),
};
let icx = ItemCtxt::new(tcx, trait_def_id);
// Convert the bounds that follow the colon, e.g. `Bar+Zed` in `trait Foo : Bar+Zed`.
let self_param_ty = tcx.mk_self_type();
let superbounds1 = compute_bounds(&icx,
self_param_ty,
bounds,
SizedByDefault::No,
item.span);
let superbounds1 = superbounds1.predicates(tcx, self_param_ty);
// Convert any explicit superbounds in the where clause,
// e.g. `trait Foo where Self : Bar`:
let superbounds2 = icx.type_parameter_bounds_in_generics(generics, item.id, self_param_ty);
// Combine the two lists to form the complete set of superbounds:
let superbounds: Vec<_> = superbounds1.into_iter().chain(superbounds2).collect();
// Now require that immediate supertraits are converted,
// which will, in turn, reach indirect supertraits.
for bound in superbounds.iter().filter_map(|p| p.to_opt_poly_trait_ref()) {
tcx.at(item.span).super_predicates_of(bound.def_id());
}
ty::GenericPredicates {
parent: None,
predicates: superbounds
}
}
fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId)
-> &'tcx ty::TraitDef {
let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
let item = tcx.hir.expect_item(node_id);
let unsafety = match item.node {
hir::ItemTrait(unsafety, ..) => unsafety,
_ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
};
let paren_sugar = tcx.has_attr(def_id, "rustc_paren_sugar");
if paren_sugar && !tcx.sess.features.borrow().unboxed_closures {
let mut err = tcx.sess.struct_span_err(
item.span,
"the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
which traits can use parenthetical notation");
help!(&mut err,
"add `#![feature(unboxed_closures)]` to \
the crate attributes to use it");
err.emit();
}
let def_path_hash = tcx.def_path_hash(def_id);
let has_default_impl = tcx.hir.trait_is_auto(def_id);
let def = ty::TraitDef::new(def_id,
unsafety,
paren_sugar,
has_default_impl,
def_path_hash);
tcx.alloc_trait_def(def)
}
fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
node: hir_map::Node<'tcx>)
-> Option<Span> {
struct LateBoundRegionsDetector<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
binder_depth: u32,
has_late_bound_regions: Option<Span>,
}
impl<'a, 'tcx> Visitor<'tcx> for LateBoundRegionsDetector<'a, 'tcx> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
NestedVisitorMap::None
}
fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
if self.has_late_bound_regions.is_some() { return }
match ty.node {
hir::TyBareFn(..) => {
self.binder_depth += 1;
intravisit::walk_ty(self, ty);
self.binder_depth -= 1;
}
_ => intravisit::walk_ty(self, ty)
}
}
fn visit_poly_trait_ref(&mut self,
tr: &'tcx hir::PolyTraitRef,
m: hir::TraitBoundModifier) {
if self.has_late_bound_regions.is_some() { return }
self.binder_depth += 1;
intravisit::walk_poly_trait_ref(self, tr, m);
self.binder_depth -= 1;
}
fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
if self.has_late_bound_regions.is_some() { return }
let hir_id = self.tcx.hir.node_to_hir_id(lt.id);
match self.tcx.named_region(hir_id) {
Some(rl::Region::Static) | Some(rl::Region::EarlyBound(..)) => {}
Some(rl::Region::LateBound(debruijn, _)) |
Some(rl::Region::LateBoundAnon(debruijn, _))
if debruijn.depth < self.binder_depth => {}
_ => self.has_late_bound_regions = Some(lt.span),
}
}
}
fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
generics: &'tcx hir::Generics,
decl: &'tcx hir::FnDecl)
-> Option<Span> {
let mut visitor = LateBoundRegionsDetector {
tcx, binder_depth: 1, has_late_bound_regions: None
};
for lifetime in &generics.lifetimes {
let hir_id = tcx.hir.node_to_hir_id(lifetime.lifetime.id);
if tcx.is_late_bound(hir_id) {
return Some(lifetime.lifetime.span);
}
}
visitor.visit_fn_decl(decl);
visitor.has_late_bound_regions
}
match node {
hir_map::NodeTraitItem(item) => match item.node {
hir::TraitItemKind::Method(ref sig, _) =>
has_late_bound_regions(tcx, &sig.generics, &sig.decl),
_ => None,
},
hir_map::NodeImplItem(item) => match item.node {
hir::ImplItemKind::Method(ref sig, _) =>
has_late_bound_regions(tcx, &sig.generics, &sig.decl),
_ => None,
},
hir_map::NodeForeignItem(item) => match item.node {
hir::ForeignItemFn(ref fn_decl, _, ref generics) =>
has_late_bound_regions(tcx, generics, fn_decl),
_ => None,
},
hir_map::NodeItem(item) => match item.node {
hir::ItemFn(ref fn_decl, .., ref generics, _) =>
has_late_bound_regions(tcx, generics, fn_decl),
_ => None,
},
_ => None
}
}
fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId)
-> &'tcx ty::Generics {
use rustc::hir::map::*;
use rustc::hir::*;
let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
let node = tcx.hir.get(node_id);
let parent_def_id = match node {
NodeImplItem(_) |
NodeTraitItem(_) |
NodeVariant(_) |
NodeStructCtor(_) |
NodeField(_) => {
let parent_id = tcx.hir.get_parent(node_id);
Some(tcx.hir.local_def_id(parent_id))
}
NodeExpr(&hir::Expr { node: hir::ExprClosure(..), .. }) => {
Some(tcx.closure_base_def_id(def_id))
}
NodeTy(&hir::Ty { node: hir::TyImplTrait(..), .. }) => {
let mut parent_id = node_id;
loop {
match tcx.hir.get(parent_id) {
NodeItem(_) | NodeImplItem(_) | NodeTraitItem(_) => break,
_ => {
parent_id = tcx.hir.get_parent_node(parent_id);
}
}
}
Some(tcx.hir.local_def_id(parent_id))
}
_ => None
};
let mut opt_self = None;
let mut allow_defaults = false;
let no_generics = hir::Generics::empty();
let ast_generics = match node {
NodeTraitItem(item) => {
match item.node {
TraitItemKind::Method(ref sig, _) => &sig.generics,
_ => &no_generics
}
}
NodeImplItem(item) => {
match item.node {
ImplItemKind::Method(ref sig, _) => &sig.generics,
_ => &no_generics
}
}
NodeItem(item) => {
match item.node {
ItemFn(.., ref generics, _) |
ItemImpl(_, _, _, ref generics, ..) => generics,
ItemTy(_, ref generics) |
ItemEnum(_, ref generics) |
ItemStruct(_, ref generics) |
ItemUnion(_, ref generics) => {
allow_defaults = true;
generics
}
ItemTrait(_, ref generics, ..) => {
// Add in the self type parameter.
//
// Something of a hack: use the node id for the trait, also as
// the node id for the Self type parameter.
let param_id = item.id;
opt_self = Some(ty::TypeParameterDef {
index: 0,
name: keywords::SelfType.name(),
def_id: tcx.hir.local_def_id(param_id),
has_default: false,
object_lifetime_default: rl::Set1::Empty,
pure_wrt_drop: false,
synthetic: None,
});
allow_defaults = true;
generics
}
_ => &no_generics
}
}
NodeForeignItem(item) => {
match item.node {
ForeignItemStatic(..) => &no_generics,
ForeignItemFn(_, _, ref generics) => generics
}
}
_ => &no_generics
};
let has_self = opt_self.is_some();
let mut parent_has_self = false;
let mut own_start = has_self as u32;
let (parent_regions, parent_types) = parent_def_id.map_or((0, 0), |def_id| {
let generics = tcx.generics_of(def_id);
assert_eq!(has_self, false);
parent_has_self = generics.has_self;
own_start = generics.count() as u32;
(generics.parent_regions + generics.regions.len() as u32,
generics.parent_types + generics.types.len() as u32)
});
let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
let regions = early_lifetimes.enumerate().map(|(i, l)| {
ty::RegionParameterDef {
name: l.lifetime.name.name(),
index: own_start + i as u32,
def_id: tcx.hir.local_def_id(l.lifetime.id),
pure_wrt_drop: l.pure_wrt_drop,
}
}).collect::<Vec<_>>();
let hir_id = tcx.hir.node_to_hir_id(node_id);
let object_lifetime_defaults = tcx.object_lifetime_defaults(hir_id);
// Now create the real type parameters.
let type_start = own_start + regions.len() as u32;
let types = ast_generics.ty_params.iter().enumerate().map(|(i, p)| {
if p.name == keywords::SelfType.name() {
span_bug!(p.span, "`Self` should not be the name of a regular parameter");
}
if !allow_defaults && p.default.is_some() {
if !tcx.sess.features.borrow().default_type_parameter_fallback {
tcx.lint_node(
lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
p.id,
p.span,
&format!("defaults for type parameters are only allowed in `struct`, \
`enum`, `type`, or `trait` definitions."));
}
}
ty::TypeParameterDef {
index: type_start + i as u32,
name: p.name,
def_id: tcx.hir.local_def_id(p.id),
has_default: p.default.is_some(),
object_lifetime_default:
object_lifetime_defaults.as_ref().map_or(rl::Set1::Empty, |o| o[i]),
pure_wrt_drop: p.pure_wrt_drop,
synthetic: p.synthetic,
}
});
let mut types: Vec<_> = opt_self.into_iter().chain(types).collect();