-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
collect.rs
2651 lines (2408 loc) · 99.9 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
//! "Collection" is the process of determining the type and other external
//! details of each item in Rust. Collection is specifically concerned
//! with *inter-procedural* 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 crate::astconv::{AstConv, Bounds, SizedByDefault};
use crate::check::intrinsic::intrinsic_operation_unsafety;
use crate::constrained_generic_params as cgp;
use crate::middle::lang_items;
use crate::middle::resolve_lifetime as rl;
use rustc::hir::map::blocks::FnLikeNode;
use rustc::hir::map::Map;
use rustc::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
use rustc::mir::mono::Linkage;
use rustc::ty::query::Providers;
use rustc::ty::subst::{InternalSubsts, Subst};
use rustc::ty::util::Discr;
use rustc::ty::util::IntTypeExt;
use rustc::ty::{self, AdtKind, Const, ToPolyTraitRef, Ty, TyCtxt};
use rustc::ty::{ReprOptions, ToPredicate, WithConstness};
use rustc_ast::ast;
use rustc_ast::ast::{Ident, MetaItemKind};
use rustc_attr::{list_contains_name, mark_used, InlineAttr, OptimizeAttr};
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::{struct_span_err, Applicability};
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, DefKind, Res};
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::{GenericParamKind, Node, Unsafety};
use rustc_session::lint;
use rustc_session::parse::feature_err;
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::{Span, DUMMY_SP};
use rustc_target::spec::abi;
mod type_of;
struct OnlySelfBounds(bool);
///////////////////////////////////////////////////////////////////////////
// Main entry point
fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
tcx.hir().visit_item_likes_in_module(
module_def_id,
&mut CollectItemTypesVisitor { tcx }.as_deep_visitor(),
);
}
pub fn provide(providers: &mut Providers<'_>) {
*providers = Providers {
type_of: type_of::type_of,
generics_of,
predicates_of,
predicates_defined_on,
explicit_predicates_of,
super_predicates_of,
type_param_predicates,
trait_def,
adt_def,
fn_sig,
impl_trait_ref,
impl_polarity,
is_foreign_item,
static_mutability,
generator_kind,
codegen_fn_attrs,
collect_mod_item_types,
..*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<'tcx> {
tcx: TyCtxt<'tcx>,
item_def_id: DefId,
}
///////////////////////////////////////////////////////////////////////////
#[derive(Default)]
crate struct PlaceholderHirTyCollector(crate Vec<Span>);
impl<'v> Visitor<'v> for PlaceholderHirTyCollector {
type Map = intravisit::ErasedMap<'v>;
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
fn visit_ty(&mut self, t: &'v hir::Ty<'v>) {
if let hir::TyKind::Infer = t.kind {
self.0.push(t.span);
}
intravisit::walk_ty(self, t)
}
}
struct CollectItemTypesVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
}
/// If there are any placeholder types (`_`), emit an error explaining that this is not allowed
/// and suggest adding type parameters in the appropriate place, taking into consideration any and
/// all already existing generic type parameters to avoid suggesting a name that is already in use.
crate fn placeholder_type_error(
tcx: TyCtxt<'tcx>,
span: Span,
generics: &[hir::GenericParam<'_>],
placeholder_types: Vec<Span>,
suggest: bool,
) {
if placeholder_types.is_empty() {
return;
}
// This is the whitelist of possible parameter names that we might suggest.
let possible_names = ["T", "K", "L", "A", "B", "C"];
let used_names = generics
.iter()
.filter_map(|p| match p.name {
hir::ParamName::Plain(ident) => Some(ident.name),
_ => None,
})
.collect::<Vec<_>>();
let type_name = possible_names
.iter()
.find(|n| !used_names.contains(&Symbol::intern(n)))
.unwrap_or(&"ParamName");
let mut sugg: Vec<_> =
placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
if generics.is_empty() {
sugg.push((span, format!("<{}>", type_name)));
} else if let Some(arg) = generics.iter().find(|arg| match arg.name {
hir::ParamName::Plain(Ident { name: kw::Underscore, .. }) => true,
_ => false,
}) {
// Account for `_` already present in cases like `struct S<_>(_);` and suggest
// `struct S<T>(T);` instead of `struct S<_, T>(T);`.
sugg.push((arg.span, (*type_name).to_string()));
} else {
let last = generics.iter().last().unwrap();
sugg.push((
// Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
last.bounds_span().unwrap_or(last.span).shrink_to_hi(),
format!(", {}", type_name),
));
}
let mut err = bad_placeholder_type(tcx, placeholder_types);
if suggest {
err.multipart_suggestion(
"use type parameters instead",
sugg,
Applicability::HasPlaceholders,
);
}
err.emit();
}
fn reject_placeholder_type_signatures_in_item(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
let (generics, suggest) = match &item.kind {
hir::ItemKind::Union(_, generics)
| hir::ItemKind::Enum(_, generics)
| hir::ItemKind::TraitAlias(generics, _)
| hir::ItemKind::Trait(_, _, generics, ..)
| hir::ItemKind::Impl { generics, .. }
| hir::ItemKind::Struct(_, generics) => (generics, true),
hir::ItemKind::OpaqueTy(hir::OpaqueTy { generics, .. })
| hir::ItemKind::TyAlias(_, generics) => (generics, false),
// `static`, `fn` and `const` are handled elsewhere to suggest appropriate type.
_ => return,
};
let mut visitor = PlaceholderHirTyCollector::default();
visitor.visit_item(item);
placeholder_type_error(tcx, generics.span, &generics.params[..], visitor.0, suggest);
}
impl Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
type Map = Map<'tcx>;
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::OnlyBodies(self.tcx.hir())
}
fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
convert_item(self.tcx, item.hir_id);
reject_placeholder_type_signatures_in_item(self.tcx, item);
intravisit::walk_item(self, item);
}
fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
for param in generics.params {
match param.kind {
hir::GenericParamKind::Lifetime { .. } => {}
hir::GenericParamKind::Type { default: Some(_), .. } => {
let def_id = self.tcx.hir().local_def_id(param.hir_id);
self.tcx.type_of(def_id);
}
hir::GenericParamKind::Type { .. } => {}
hir::GenericParamKind::Const { .. } => {
let def_id = self.tcx.hir().local_def_id(param.hir_id);
self.tcx.type_of(def_id);
}
}
}
intravisit::walk_generics(self, generics);
}
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
if let hir::ExprKind::Closure(..) = expr.kind {
let def_id = self.tcx.hir().local_def_id(expr.hir_id);
self.tcx.generics_of(def_id);
self.tcx.type_of(def_id);
}
intravisit::walk_expr(self, expr);
}
fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
convert_trait_item(self.tcx, trait_item.hir_id);
intravisit::walk_trait_item(self, trait_item);
}
fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
convert_impl_item(self.tcx, impl_item.hir_id);
intravisit::walk_impl_item(self, impl_item);
}
}
///////////////////////////////////////////////////////////////////////////
// Utility types and common code for the above passes.
fn bad_placeholder_type(
tcx: TyCtxt<'tcx>,
mut spans: Vec<Span>,
) -> rustc_errors::DiagnosticBuilder<'tcx> {
spans.sort();
let mut err = struct_span_err!(
tcx.sess,
spans.clone(),
E0121,
"the type placeholder `_` is not allowed within types on item signatures",
);
for span in spans {
err.span_label(span, "not allowed in type signatures");
}
err
}
impl ItemCtxt<'tcx> {
pub fn new(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> ItemCtxt<'tcx> {
ItemCtxt { tcx, item_def_id }
}
pub fn to_ty(&self, ast_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
AstConv::ast_ty_to_ty(self, ast_ty)
}
pub fn hir_id(&self) -> hir::HirId {
self.tcx
.hir()
.as_local_hir_id(self.item_def_id)
.expect("Non-local call to local provider is_const_fn")
}
pub fn node(&self) -> hir::Node<'tcx> {
self.tcx.hir().get(self.hir_id())
}
}
impl AstConv<'tcx> for ItemCtxt<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn item_def_id(&self) -> Option<DefId> {
Some(self.item_def_id)
}
fn default_constness_for_trait_bounds(&self) -> hir::Constness {
if let Some(fn_like) = FnLikeNode::from_node(self.node()) {
fn_like.constness()
} else {
hir::Constness::NotConst
}
}
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, _: Option<&ty::GenericParamDef>, _: Span) -> Option<ty::Region<'tcx>> {
None
}
fn allow_ty_infer(&self) -> bool {
false
}
fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
self.tcx().sess.delay_span_bug(span, "bad placeholder type");
self.tcx().types.err
}
fn ct_infer(
&self,
_: Ty<'tcx>,
_: Option<&ty::GenericParamDef>,
span: Span,
) -> &'tcx Const<'tcx> {
bad_placeholder_type(self.tcx(), vec![span]).emit();
self.tcx().consts.err
}
fn projected_ty_from_poly_trait_ref(
&self,
span: Span,
item_def_id: DefId,
item_segment: &hir::PathSegment<'_>,
poly_trait_ref: ty::PolyTraitRef<'tcx>,
) -> Ty<'tcx> {
if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item(
self,
self.tcx,
span,
item_def_id,
item_segment,
trait_ref.substs,
);
self.tcx().mk_projection(item_def_id, item_substs)
} else {
// There are no late-bound regions; we can just ignore the binder.
let mut err = struct_span_err!(
self.tcx().sess,
span,
E0212,
"cannot extract an associated type from a higher-ranked trait bound \
in this context"
);
match self.node() {
hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
let item =
self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(self.hir_id()));
match &item.kind {
hir::ItemKind::Enum(_, generics)
| hir::ItemKind::Struct(_, generics)
| hir::ItemKind::Union(_, generics) => {
let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
let (lt_sp, sugg) = match &generics.params[..] {
[] => (generics.span, format!("<{}>", lt_name)),
[bound, ..] => {
(bound.span.shrink_to_lo(), format!("{}, ", lt_name))
}
};
let suggestions = vec![
(lt_sp, sugg),
(
span,
format!(
"{}::{}",
// Replace the existing lifetimes with a new named lifetime.
self.tcx
.replace_late_bound_regions(&poly_trait_ref, |_| {
self.tcx.mk_region(ty::ReEarlyBound(
ty::EarlyBoundRegion {
def_id: item_def_id,
index: 0,
name: Symbol::intern(<_name),
},
))
})
.0,
item_segment.ident
),
),
];
err.multipart_suggestion(
"use a fully qualified path with explicit lifetimes",
suggestions,
Applicability::MaybeIncorrect,
);
}
_ => {}
}
}
hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(..), .. })
| hir::Node::Item(hir::Item { kind: hir::ItemKind::Enum(..), .. })
| hir::Node::Item(hir::Item { kind: hir::ItemKind::Union(..), .. }) => {}
hir::Node::Item(_)
| hir::Node::ForeignItem(_)
| hir::Node::TraitItem(_)
| hir::Node::ImplItem(_) => {
err.span_suggestion(
span,
"use a fully qualified path with inferred lifetimes",
format!(
"{}::{}",
// Erase named lt, we want `<A as B<'_>::C`, not `<A as B<'a>::C`.
self.tcx.anonymize_late_bound_regions(&poly_trait_ref).skip_binder(),
item_segment.ident
),
Applicability::MaybeIncorrect,
);
}
_ => {}
}
err.emit();
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) {
// There's no obvious place to track this, so just let it go.
}
fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
// There's no place to record types from signatures?
}
}
/// Synthesize a new lifetime name that doesn't clash with any of the lifetimes already present.
fn get_new_lifetime_name<'tcx>(
tcx: TyCtxt<'tcx>,
poly_trait_ref: ty::PolyTraitRef<'tcx>,
generics: &hir::Generics<'tcx>,
) -> String {
let existing_lifetimes = tcx
.collect_referenced_late_bound_regions(&poly_trait_ref)
.into_iter()
.filter_map(|lt| {
if let ty::BoundRegion::BrNamed(_, name) = lt {
Some(name.as_str().to_string())
} else {
None
}
})
.chain(generics.params.iter().filter_map(|param| {
if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
Some(param.name.ident().as_str().to_string())
} else {
None
}
}))
.collect::<FxHashSet<String>>();
let a_to_z_repeat_n = |n| {
(b'a'..=b'z').map(move |c| {
let mut s = '\''.to_string();
s.extend(std::iter::repeat(char::from(c)).take(n));
s
})
};
// If all single char lifetime names are present, we wrap around and double the chars.
(1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
}
/// Returns the predicates defined on `item_def_id` of the form
/// `X: Foo` where `X` is the type parameter `def_id`.
fn type_param_predicates(
tcx: TyCtxt<'_>,
(item_def_id, def_id): (DefId, DefId),
) -> ty::GenericPredicates<'_> {
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_hir_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.param_def_id_to_index[&def_id];
let ty = tcx.mk_ty_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(|parent| {
let icx = ItemCtxt::new(tcx, parent);
icx.get_type_parameter_bounds(DUMMY_SP, def_id)
})
.unwrap_or_default();
let mut extend = None;
let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
let ast_generics = match tcx.hir().get(item_hir_id) {
Node::TraitItem(item) => &item.generics,
Node::ImplItem(item) => &item.generics,
Node::Item(item) => {
match item.kind {
ItemKind::Fn(.., ref generics, _)
| ItemKind::Impl { ref generics, .. }
| ItemKind::TyAlias(_, ref generics)
| ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
| ItemKind::Enum(_, ref generics)
| ItemKind::Struct(_, ref generics)
| ItemKind::Union(_, ref generics) => generics,
ItemKind::Trait(_, _, ref generics, ..) => {
// Implied `Self: Trait` and supertrait bounds.
if param_id == item_hir_id {
let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
extend =
Some((identity_trait_ref.without_const().to_predicate(), item.span));
}
generics
}
_ => return result,
}
}
Node::ForeignItem(item) => match item.kind {
ForeignItemKind::Fn(_, _, ref generics) => generics,
_ => return result,
},
_ => return result,
};
let icx = ItemCtxt::new(tcx, item_def_id);
let extra_predicates = extend.into_iter().chain(
icx.type_parameter_bounds_in_generics(ast_generics, param_id, ty, OnlySelfBounds(true))
.into_iter()
.filter(|(predicate, _)| match predicate {
ty::Predicate::Trait(ref data, _) => data.skip_binder().self_ty().is_param(index),
_ => false,
}),
);
result.predicates =
tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
result
}
impl ItemCtxt<'tcx> {
/// Finds 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: &'tcx hir::Generics<'tcx>,
param_id: hir::HirId,
ty: Ty<'tcx>,
only_self_bounds: OnlySelfBounds,
) -> Vec<(ty::Predicate<'tcx>, Span)> {
let constness = self.default_constness_for_trait_bounds();
let from_ty_params = ast_generics
.params
.iter()
.filter_map(|param| match param.kind {
GenericParamKind::Type { .. } if param.hir_id == param_id => Some(¶m.bounds),
_ => None,
})
.flat_map(|bounds| bounds.iter())
.flat_map(|b| predicates_from_bound(self, ty, b, constness));
let from_where_clauses = ast_generics
.where_clause
.predicates
.iter()
.filter_map(|wp| match *wp {
hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
_ => None,
})
.flat_map(|bp| {
let bt = if is_param(self.tcx, &bp.bounded_ty, param_id) {
Some(ty)
} else if !only_self_bounds.0 {
Some(self.to_ty(&bp.bounded_ty))
} else {
None
};
bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b)))
})
.flat_map(|(bt, b)| predicates_from_bound(self, bt, b, constness));
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(tcx: TyCtxt<'_>, ast_ty: &hir::Ty<'_>, param_id: hir::HirId) -> bool {
if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) = ast_ty.kind {
match path.res {
Res::SelfTy(Some(def_id), None) | Res::Def(DefKind::TyParam, def_id) => {
def_id == tcx.hir().local_def_id(param_id)
}
_ => false,
}
} else {
false
}
}
fn convert_item(tcx: TyCtxt<'_>, item_id: hir::HirId) {
let it = tcx.hir().expect_item(item_id);
debug!("convert: item {} with id {}", it.ident, it.hir_id);
let def_id = tcx.hir().local_def_id(item_id);
match it.kind {
// These don't define types.
hir::ItemKind::ExternCrate(_)
| hir::ItemKind::Use(..)
| hir::ItemKind::Mod(_)
| hir::ItemKind::GlobalAsm(_) => {}
hir::ItemKind::ForeignMod(ref foreign_mod) => {
for item in foreign_mod.items {
let def_id = tcx.hir().local_def_id(item.hir_id);
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
if let hir::ForeignItemKind::Fn(..) = item.kind {
tcx.fn_sig(def_id);
}
}
}
hir::ItemKind::Enum(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::ItemKind::Impl { .. } => {
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.impl_trait_ref(def_id);
tcx.predicates_of(def_id);
}
hir::ItemKind::Trait(..) => {
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::ItemKind::TraitAlias(..) => {
tcx.generics_of(def_id);
tcx.at(it.span).super_predicates_of(def_id);
tcx.predicates_of(def_id);
}
hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(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.hir_id);
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
}
if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
convert_variant_ctor(tcx, ctor_hir_id);
}
}
// Desugared from `impl Trait`, so visited by the function's return type.
hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => {}
hir::ItemKind::OpaqueTy(..)
| hir::ItemKind::TyAlias(..)
| hir::ItemKind::Static(..)
| hir::ItemKind::Const(..)
| hir::ItemKind::Fn(..) => {
tcx.generics_of(def_id);
tcx.type_of(def_id);
tcx.predicates_of(def_id);
if let hir::ItemKind::Fn(..) = it.kind {
tcx.fn_sig(def_id);
}
}
}
}
fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::HirId) {
let trait_item = tcx.hir().expect_trait_item(trait_item_id);
let def_id = tcx.hir().local_def_id(trait_item.hir_id);
tcx.generics_of(def_id);
match trait_item.kind {
hir::TraitItemKind::Fn(..) => {
tcx.type_of(def_id);
tcx.fn_sig(def_id);
}
hir::TraitItemKind::Const(.., Some(_)) => {
tcx.type_of(def_id);
}
hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(_, Some(_)) => {
tcx.type_of(def_id);
// Account for `const C: _;` and `type T = _;`.
let mut visitor = PlaceholderHirTyCollector::default();
visitor.visit_trait_item(trait_item);
placeholder_type_error(tcx, DUMMY_SP, &[], visitor.0, false);
}
hir::TraitItemKind::Type(_, None) => {}
};
tcx.predicates_of(def_id);
}
fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) {
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);
let impl_item = tcx.hir().expect_impl_item(impl_item_id);
match impl_item.kind {
hir::ImplItemKind::Fn(..) => {
tcx.fn_sig(def_id);
}
hir::ImplItemKind::TyAlias(_) | hir::ImplItemKind::OpaqueTy(_) => {
// Account for `type T = _;`
let mut visitor = PlaceholderHirTyCollector::default();
visitor.visit_impl_item(impl_item);
placeholder_type_error(tcx, DUMMY_SP, &[], visitor.0, false);
}
hir::ImplItemKind::Const(..) => {}
}
}
fn convert_variant_ctor(tcx: TyCtxt<'_>, ctor_id: hir::HirId) {
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(tcx: TyCtxt<'_>, def_id: DefId, variants: &[hir::Variant<'_>]) {
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::<Discr<'_>>;
// fill the discriminant values and field types
for variant in variants {
let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
prev_discr = Some(
if let Some(ref e) = variant.disr_expr {
let expr_did = tcx.hir().local_def_id(e.hir_id);
def.eval_explicit_discr(tcx, expr_did)
} 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.ident, wrapped_discr
))
.emit();
None
}
.unwrap_or(wrapped_discr),
);
for f in variant.data.fields() {
let def_id = tcx.hir().local_def_id(f.hir_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.
if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
convert_variant_ctor(tcx, ctor_hir_id);
}
}
}
fn convert_variant(
tcx: TyCtxt<'_>,
variant_did: Option<DefId>,
ctor_did: Option<DefId>,
ident: Ident,
discr: ty::VariantDiscr,
def: &hir::VariantData<'_>,
adt_kind: ty::AdtKind,
parent_did: DefId,
) -> ty::VariantDef {
let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
let fields = def
.fields()
.iter()
.map(|f| {
let fid = tcx.hir().local_def_id(f.hir_id);
let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
if let Some(prev_span) = dup_span {
struct_span_err!(
tcx.sess,
f.span,
E0124,
"field `{}` is already declared",
f.ident
)
.span_label(f.span, "field already declared")
.span_label(prev_span, format!("`{}` first declared here", f.ident))
.emit();
} else {
seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
}
ty::FieldDef {
did: fid,
ident: f.ident,
vis: ty::Visibility::from_hir(&f.vis, hir_id, tcx),
}
})
.collect();
let recovered = match def {
hir::VariantData::Struct(_, r) => *r,
_ => false,
};
ty::VariantDef::new(
tcx,
ident,
variant_did,
ctor_did,
discr,
fields,
CtorKind::from_hir(def),
adt_kind,
parent_did,
recovered,
)
}
fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
use rustc_hir::*;
let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
let item = match tcx.hir().get(hir_id) {
Node::Item(item) => item,
_ => bug!(),
};
let repr = ReprOptions::new(tcx, def_id);
let (kind, variants) = match item.kind {
ItemKind::Enum(ref def, _) => {
let mut distance_from_explicit = 0;
let variants = def
.variants
.iter()
.map(|v| {
let variant_did = Some(tcx.hir().local_def_id(v.id));
let ctor_did =
v.data.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
let discr = if let Some(ref e) = v.disr_expr {
distance_from_explicit = 0;
ty::VariantDiscr::Explicit(tcx.hir().local_def_id(e.hir_id))
} else {
ty::VariantDiscr::Relative(distance_from_explicit)
};
distance_from_explicit += 1;
convert_variant(
tcx,
variant_did,
ctor_did,
v.ident,
discr,
&v.data,
AdtKind::Enum,
def_id,
)
})
.collect();
(AdtKind::Enum, variants)
}
ItemKind::Struct(ref def, _) => {
let variant_did = None;
let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
let variants = std::iter::once(convert_variant(
tcx,
variant_did,
ctor_did,
item.ident,
ty::VariantDiscr::Relative(0),
def,
AdtKind::Struct,
def_id,
))
.collect();
(AdtKind::Struct, variants)
}
ItemKind::Union(ref def, _) => {
let variant_did = None;
let ctor_did = def.ctor_hir_id().map(|hir_id| tcx.hir().local_def_id(hir_id));
let variants = std::iter::once(convert_variant(
tcx,
variant_did,
ctor_did,
item.ident,
ty::VariantDiscr::Relative(0),
def,
AdtKind::Union,
def_id,
))
.collect();
(AdtKind::Union, variants)
}
_ => bug!(),
};
tcx.alloc_adt_def(def_id, kind, variants, repr)
}
/// Ensures that the super-predicates of the trait with a `DefId`
/// of `trait_def_id` are converted and stored. This also ensures that
/// the transitive super-predicates are converted.
fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
debug!("super_predicates(trait_def_id={:?})", trait_def_id);
let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
let item = match tcx.hir().get(trait_hir_id) {
Node::Item(item) => item,
_ => bug!("trait_node_id {} is not an item", trait_hir_id),
};
let (generics, bounds) = match item.kind {
hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
hir::ItemKind::TraitAlias(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.types.self_param;
let superbounds1 =
AstConv::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`.
// In the case of trait aliases, however, we include all bounds in the where-clause,
// so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
// as one of its "superpredicates".
let is_trait_alias = tcx.is_trait_alias(trait_def_id);
let superbounds2 = icx.type_parameter_bounds_in_generics(
generics,
item.hir_id,
self_param_ty,
OnlySelfBounds(!is_trait_alias),
);
// Combine the two lists to form the complete set of superbounds:
let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));