-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
collect.rs
1989 lines (1755 loc) · 77.3 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.
/*
# Collect phase
The collect phase of type check has the job of visiting all items,
determining their type, and writing that type into the `tcx.types`
table. Despite its name, this table does not really operate as a
*cache*, at least not for the types of items defined within the
current crate: we assume that after the collect phase, the types of
all local items will be present in the table.
Unlike most of the types that are present in Rust, the types computed
for each item are in fact type schemes. This means that they are
generic types that may have type parameters. TypeSchemes are
represented by a pair of `Generics` and `Ty`. Type
parameters themselves are represented as `ty_param()` instances.
The phasing of type conversion is somewhat complicated. There is no
clear set of phases we can enforce (e.g., converting traits first,
then types, or something like that) because the user can introduce
arbitrary interdependencies. So instead we generally convert things
lazilly and on demand, and include logic that checks for cycles.
Demand is driven by calls to `AstConv::get_item_type_scheme` or
`AstConv::lookup_trait_def`.
Currently, we "convert" types and traits in two phases (note that
conversion only affects the types of items / enum variants / methods;
it does not e.g. compute the types of individual expressions):
0. Intrinsics
1. Trait/Type definitions
Conversion itself is done by simply walking each of the items in turn
and invoking an appropriate function (e.g., `trait_def_of_item` or
`convert_item`). However, it is possible that while converting an
item, we may need to compute the *type scheme* or *trait definition*
for other items.
There are some shortcomings in this design:
- Before walking the set of supertraits for a given trait, you must
call `ensure_super_predicates` on that trait def-id. Otherwise,
`item_super_predicates` will result in ICEs.
- Because the item generics include defaults, cycles through type
parameter defaults are illegal even if those defaults are never
employed. This is not necessarily a bug.
*/
use astconv::{AstConv, Bounds};
use lint;
use constrained_type_params as ctp;
use middle::lang_items::SizedTraitLangItem;
use middle::const_val::ConstVal;
use rustc_const_eval::EvalHint::UncheckedExprHint;
use rustc_const_eval::{ConstContext, report_const_eval_err};
use rustc::ty::subst::Substs;
use rustc::ty::{ToPredicate, ImplContainer, AssociatedItemContainer, TraitContainer};
use rustc::ty::{self, AdtKind, ToPolyTraitRef, Ty, TyCtxt};
use rustc::ty::util::IntTypeExt;
use rustc::dep_graph::DepNode;
use util::common::{ErrorReported, MemoizationMap};
use util::nodemap::{NodeMap, FxHashMap};
use CrateCtxt;
use rustc_const_math::ConstInt;
use std::cell::RefCell;
use syntax::{abi, ast, attr};
use syntax::symbol::{Symbol, keywords};
use syntax_pos::Span;
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(ccx: &CrateCtxt) {
let mut visitor = CollectItemTypesVisitor { ccx: ccx };
ccx.tcx.visit_all_item_likes_in_krate(DepNode::CollectItem, &mut visitor.as_deep_visitor());
}
///////////////////////////////////////////////////////////////////////////
/// 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 `GetTypeParameterBounds` object
/// that it uses to satisfy `get_type_parameter_bounds` requests.
/// This object might draw the information from the AST
/// (`hir::Generics`) or it might draw from a `ty::GenericPredicates`
/// or both (a tuple).
struct ItemCtxt<'a,'tcx:'a> {
ccx: &'a CrateCtxt<'a,'tcx>,
param_bounds: &'a (GetTypeParameterBounds<'tcx>+'a),
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum AstConvRequest {
GetGenerics(DefId),
GetItemTypeScheme(DefId),
GetTraitDef(DefId),
EnsureSuperPredicates(DefId),
GetTypeParameterBounds(ast::NodeId),
}
///////////////////////////////////////////////////////////////////////////
struct CollectItemTypesVisitor<'a, 'tcx: 'a> {
ccx: &'a CrateCtxt<'a, 'tcx>
}
impl<'a, 'tcx> CollectItemTypesVisitor<'a, 'tcx> {
/// Collect item types is structured into two tasks. The outer
/// task, `CollectItem`, walks the entire content of an item-like
/// thing, including its body. It also spawns an inner task,
/// `CollectItemSig`, which walks only the signature. This inner
/// task is the one that writes the item-type into the various
/// maps. This setup ensures that the item body is never
/// accessible to the task that computes its signature, so that
/// changes to the body don't affect the signature.
///
/// Consider an example function `foo` that also has a closure in its body:
///
/// ```
/// fn foo(<sig>) {
/// ...
/// let bar = || ...; // we'll label this closure as "bar" below
/// }
/// ```
///
/// This results in a dep-graph like so. I've labeled the edges to
/// document where they arise.
///
/// ```
/// [HirBody(foo)] -2--> [CollectItem(foo)] -4-> [ItemSignature(bar)]
/// ^ ^
/// 1 3
/// [Hir(foo)] -----------+-6-> [CollectItemSig(foo)] -5-> [ItemSignature(foo)]
/// ```
///
/// 1. This is added by the `visit_all_item_likes_in_krate`.
/// 2. This is added when we fetch the item body.
/// 3. This is added because `CollectItem` launches `CollectItemSig`.
/// - it is arguably false; if we refactor the `with_task` system;
/// we could get probably rid of it, but it is also harmless enough.
/// 4. This is added by the code in `visit_expr` when we write to `item_types`.
/// 5. This is added by the code in `convert_item` when we write to `item_types`;
/// note that this write occurs inside the `CollectItemSig` task.
/// 6. Added by explicit `read` below
fn with_collect_item_sig<OP>(&self, id: ast::NodeId, op: OP)
where OP: FnOnce()
{
let def_id = self.ccx.tcx.hir.local_def_id(id);
self.ccx.tcx.dep_graph.with_task(DepNode::CollectItemSig(def_id), || {
self.ccx.tcx.hir.read(id);
op();
});
}
}
impl<'a, 'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'a, 'tcx> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
NestedVisitorMap::OnlyBodies(&self.ccx.tcx.hir)
}
fn visit_item(&mut self, item: &'tcx hir::Item) {
self.with_collect_item_sig(item.id, || convert_item(self.ccx, item));
intravisit::walk_item(self, item);
}
fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
if let hir::ExprClosure(..) = expr.node {
let def_id = self.ccx.tcx.hir.local_def_id(expr.id);
generics_of_def_id(self.ccx, def_id);
type_of_def_id(self.ccx, 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.ccx.tcx.hir.local_def_id(ty.id);
generics_of_def_id(self.ccx, def_id);
}
intravisit::walk_ty(self, ty);
}
fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
self.with_collect_item_sig(trait_item.id, || {
convert_trait_item(self.ccx, trait_item)
});
intravisit::walk_trait_item(self, trait_item);
}
fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
self.with_collect_item_sig(impl_item.id, || {
convert_impl_item(self.ccx, impl_item)
});
intravisit::walk_impl_item(self, impl_item);
}
}
///////////////////////////////////////////////////////////////////////////
// Utility types and common code for the above passes.
impl<'a,'tcx> CrateCtxt<'a,'tcx> {
fn icx(&'a self, param_bounds: &'a GetTypeParameterBounds<'tcx>) -> ItemCtxt<'a,'tcx> {
ItemCtxt {
ccx: self,
param_bounds: param_bounds,
}
}
fn cycle_check<F,R>(&self,
span: Span,
request: AstConvRequest,
code: F)
-> Result<R,ErrorReported>
where F: FnOnce() -> Result<R,ErrorReported>
{
{
let mut stack = self.stack.borrow_mut();
if let Some((i, _)) = stack.iter().enumerate().rev().find(|&(_, r)| *r == request) {
let cycle = &stack[i..];
self.report_cycle(span, cycle);
return Err(ErrorReported);
}
stack.push(request);
}
let result = code();
self.stack.borrow_mut().pop();
result
}
fn report_cycle(&self,
span: Span,
cycle: &[AstConvRequest])
{
assert!(!cycle.is_empty());
let tcx = self.tcx;
let mut err = struct_span_err!(tcx.sess, span, E0391,
"unsupported cyclic reference between types/traits detected");
err.span_label(span, &format!("cyclic reference"));
match cycle[0] {
AstConvRequest::GetGenerics(def_id) |
AstConvRequest::GetItemTypeScheme(def_id) |
AstConvRequest::GetTraitDef(def_id) => {
err.note(
&format!("the cycle begins when processing `{}`...",
tcx.item_path_str(def_id)));
}
AstConvRequest::EnsureSuperPredicates(def_id) => {
err.note(
&format!("the cycle begins when computing the supertraits of `{}`...",
tcx.item_path_str(def_id)));
}
AstConvRequest::GetTypeParameterBounds(id) => {
let def = tcx.type_parameter_def(id);
err.note(
&format!("the cycle begins when computing the bounds \
for type parameter `{}`...",
def.name));
}
}
for request in &cycle[1..] {
match *request {
AstConvRequest::GetGenerics(def_id) |
AstConvRequest::GetItemTypeScheme(def_id) |
AstConvRequest::GetTraitDef(def_id) => {
err.note(
&format!("...which then requires processing `{}`...",
tcx.item_path_str(def_id)));
}
AstConvRequest::EnsureSuperPredicates(def_id) => {
err.note(
&format!("...which then requires computing the supertraits of `{}`...",
tcx.item_path_str(def_id)));
}
AstConvRequest::GetTypeParameterBounds(id) => {
let def = tcx.type_parameter_def(id);
err.note(
&format!("...which then requires computing the bounds \
for type parameter `{}`...",
def.name));
}
}
}
match cycle[0] {
AstConvRequest::GetGenerics(def_id) |
AstConvRequest::GetItemTypeScheme(def_id) |
AstConvRequest::GetTraitDef(def_id) => {
err.note(
&format!("...which then again requires processing `{}`, completing the cycle.",
tcx.item_path_str(def_id)));
}
AstConvRequest::EnsureSuperPredicates(def_id) => {
err.note(
&format!("...which then again requires computing the supertraits of `{}`, \
completing the cycle.",
tcx.item_path_str(def_id)));
}
AstConvRequest::GetTypeParameterBounds(id) => {
let def = tcx.type_parameter_def(id);
err.note(
&format!("...which then again requires computing the bounds \
for type parameter `{}`, completing the cycle.",
def.name));
}
}
err.emit();
}
/// Loads the trait def for a given trait, returning ErrorReported if a cycle arises.
fn get_trait_def(&self, def_id: DefId)
-> &'tcx ty::TraitDef
{
let tcx = self.tcx;
if let Some(trait_id) = tcx.hir.as_local_node_id(def_id) {
let item = match tcx.hir.get(trait_id) {
hir_map::NodeItem(item) => item,
_ => bug!("get_trait_def({:?}): not an item", trait_id)
};
generics_of_def_id(self, def_id);
trait_def_of_item(self, &item)
} else {
tcx.lookup_trait_def(def_id)
}
}
/// Ensure that the (transitive) super predicates for
/// `trait_def_id` are available. This will report a cycle error
/// if a trait `X` (transitively) extends itself in some form.
fn ensure_super_predicates(&self, span: Span, trait_def_id: DefId)
-> Result<(), ErrorReported>
{
self.cycle_check(span, AstConvRequest::EnsureSuperPredicates(trait_def_id), || {
let def_ids = ensure_super_predicates_step(self, trait_def_id);
for def_id in def_ids {
self.ensure_super_predicates(span, def_id)?;
}
Ok(())
})
}
}
impl<'a,'tcx> ItemCtxt<'a,'tcx> {
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.ccx.tcx }
fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>> {
&self.ccx.ast_ty_to_ty_cache
}
fn get_generics(&self, span: Span, id: DefId)
-> Result<&'tcx ty::Generics<'tcx>, ErrorReported>
{
self.ccx.cycle_check(span, AstConvRequest::GetGenerics(id), || {
Ok(generics_of_def_id(self.ccx, id))
})
}
fn get_item_type(&self, span: Span, id: DefId) -> Result<Ty<'tcx>, ErrorReported> {
self.ccx.cycle_check(span, AstConvRequest::GetItemTypeScheme(id), || {
Ok(type_of_def_id(self.ccx, id))
})
}
fn get_trait_def(&self, span: Span, id: DefId)
-> Result<&'tcx ty::TraitDef, ErrorReported>
{
self.ccx.cycle_check(span, AstConvRequest::GetTraitDef(id), || {
Ok(self.ccx.get_trait_def(id))
})
}
fn ensure_super_predicates(&self,
span: Span,
trait_def_id: DefId)
-> Result<(), ErrorReported>
{
debug!("ensure_super_predicates(trait_def_id={:?})",
trait_def_id);
self.ccx.ensure_super_predicates(span, trait_def_id)
}
fn get_type_parameter_bounds(&self,
span: Span,
node_id: ast::NodeId)
-> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>
{
self.ccx.cycle_check(span, AstConvRequest::GetTypeParameterBounds(node_id), || {
let v = self.param_bounds.get_type_parameter_bounds(self, span, node_id)
.into_iter()
.filter_map(|p| p.to_opt_poly_trait_ref())
.collect();
Ok(v)
})
}
fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
None
}
fn re_infer(&self, _span: Span, _def: Option<&ty::RegionParameterDef>)
-> Option<&'tcx ty::Region> {
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, &format!("not allowed in type signatures"))
.emit();
self.tcx().types.err
}
fn projected_ty_from_poly_trait_ref(&self,
span: Span,
poly_trait_ref: ty::PolyTraitRef<'tcx>,
item_name: ast::Name)
-> Ty<'tcx>
{
if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) {
self.projected_ty(span, trait_ref, item_name)
} 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 projected_ty(&self,
_span: Span,
trait_ref: ty::TraitRef<'tcx>,
item_name: ast::Name)
-> Ty<'tcx>
{
self.tcx().mk_projection(trait_ref, item_name)
}
fn set_tainted_by_errors(&self) {
// no obvious place to track this, just let it go
}
}
/// Interface used to find the bounds on a type parameter from within
/// an `ItemCtxt`. This allows us to use multiple kinds of sources.
trait GetTypeParameterBounds<'tcx> {
fn get_type_parameter_bounds(&self,
astconv: &AstConv<'tcx, 'tcx>,
span: Span,
node_id: ast::NodeId)
-> Vec<ty::Predicate<'tcx>>;
}
/// Find bounds from both elements of the tuple.
impl<'a,'b,'tcx,A,B> GetTypeParameterBounds<'tcx> for (&'a A,&'b B)
where A : GetTypeParameterBounds<'tcx>, B : GetTypeParameterBounds<'tcx>
{
fn get_type_parameter_bounds(&self,
astconv: &AstConv<'tcx, 'tcx>,
span: Span,
node_id: ast::NodeId)
-> Vec<ty::Predicate<'tcx>>
{
let mut v = self.0.get_type_parameter_bounds(astconv, span, node_id);
v.extend(self.1.get_type_parameter_bounds(astconv, span, node_id));
v
}
}
/// Empty set of bounds.
impl<'tcx> GetTypeParameterBounds<'tcx> for () {
fn get_type_parameter_bounds(&self,
_astconv: &AstConv<'tcx, 'tcx>,
_span: Span,
_node_id: ast::NodeId)
-> Vec<ty::Predicate<'tcx>>
{
Vec::new()
}
}
/// Find bounds from the parsed and converted predicates. This is
/// used when converting methods, because by that time the predicates
/// from the trait/impl have been fully converted.
impl<'tcx> GetTypeParameterBounds<'tcx> for ty::GenericPredicates<'tcx> {
fn get_type_parameter_bounds(&self,
astconv: &AstConv<'tcx, 'tcx>,
span: Span,
node_id: ast::NodeId)
-> Vec<ty::Predicate<'tcx>>
{
let def = astconv.tcx().type_parameter_def(node_id);
let mut results = self.parent.map_or(vec![], |def_id| {
let parent = astconv.tcx().item_predicates(def_id);
parent.get_type_parameter_bounds(astconv, span, node_id)
});
results.extend(self.predicates.iter().filter(|predicate| {
match **predicate {
ty::Predicate::Trait(ref data) => {
data.skip_binder().self_ty().is_param(def.index)
}
ty::Predicate::TypeOutlives(ref data) => {
data.skip_binder().0.is_param(def.index)
}
ty::Predicate::Equate(..) |
ty::Predicate::RegionOutlives(..) |
ty::Predicate::WellFormed(..) |
ty::Predicate::ObjectSafe(..) |
ty::Predicate::ClosureKind(..) |
ty::Predicate::Projection(..) => {
false
}
}
}).cloned());
results
}
}
/// 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.
impl<'tcx> GetTypeParameterBounds<'tcx> for hir::Generics {
fn get_type_parameter_bounds(&self,
astconv: &AstConv<'tcx, 'tcx>,
_: Span,
node_id: ast::NodeId)
-> Vec<ty::Predicate<'tcx>>
{
// 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 def = astconv.tcx().type_parameter_def(node_id);
let ty = astconv.tcx().mk_param_from_def(&def);
let from_ty_params =
self.ty_params
.iter()
.filter(|p| p.id == node_id)
.flat_map(|p| p.bounds.iter())
.flat_map(|b| predicates_from_bound(astconv, ty, b));
let from_where_clauses =
self.where_clause
.predicates
.iter()
.filter_map(|wp| match *wp {
hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
_ => None
})
.filter(|bp| is_param(astconv.tcx(), &bp.bounded_ty, node_id))
.flat_map(|bp| bp.bounds.iter())
.flat_map(|b| predicates_from_bound(astconv, 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 convert_field<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
struct_generics: &'tcx ty::Generics<'tcx>,
struct_predicates: &ty::GenericPredicates<'tcx>,
field: &hir::StructField,
ty_f: &'tcx ty::FieldDef)
{
let tt = ccx.icx(struct_predicates).to_ty(&field.ty);
ccx.tcx.item_types.borrow_mut().insert(ty_f.did, tt);
let def_id = ccx.tcx.hir.local_def_id(field.id);
ccx.tcx.item_types.borrow_mut().insert(def_id, tt);
ccx.tcx.generics.borrow_mut().insert(def_id, struct_generics);
ccx.tcx.predicates.borrow_mut().insert(def_id, struct_predicates.clone());
}
fn convert_method<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
id: ast::NodeId,
sig: &hir::MethodSig,
rcvr_ty_predicates: &ty::GenericPredicates<'tcx>,) {
let def_id = ccx.tcx.hir.local_def_id(id);
let ty_generics = generics_of_def_id(ccx, def_id);
let ty_generic_predicates =
ty_generic_predicates(ccx, &sig.generics, ty_generics.parent, vec![], false);
let fty = AstConv::ty_of_fn(&ccx.icx(&(rcvr_ty_predicates, &sig.generics)),
sig.unsafety, sig.abi, &sig.decl);
let substs = mk_item_substs(&ccx.icx(&(rcvr_ty_predicates, &sig.generics)),
ccx.tcx.hir.span(id), def_id);
let fty = ccx.tcx.mk_fn_def(def_id, substs, fty);
ccx.tcx.item_types.borrow_mut().insert(def_id, fty);
ccx.tcx.predicates.borrow_mut().insert(def_id, ty_generic_predicates);
}
fn convert_associated_const<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
container: AssociatedItemContainer,
id: ast::NodeId,
ty: ty::Ty<'tcx>)
{
let predicates = ty::GenericPredicates {
parent: Some(container.id()),
predicates: vec![]
};
let def_id = ccx.tcx.hir.local_def_id(id);
ccx.tcx.predicates.borrow_mut().insert(def_id, predicates);
ccx.tcx.item_types.borrow_mut().insert(def_id, ty);
}
fn convert_associated_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
container: AssociatedItemContainer,
id: ast::NodeId,
ty: Option<Ty<'tcx>>)
{
let predicates = ty::GenericPredicates {
parent: Some(container.id()),
predicates: vec![]
};
let def_id = ccx.tcx.hir.local_def_id(id);
ccx.tcx.predicates.borrow_mut().insert(def_id, predicates);
if let Some(ty) = ty {
ccx.tcx.item_types.borrow_mut().insert(def_id, ty);
}
}
fn ensure_no_ty_param_bounds(ccx: &CrateCtxt,
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!(ccx.tcx.sess, span, E0122,
"trait bounds are not (yet) enforced \
in {} definitions",
thing);
}
}
fn convert_item(ccx: &CrateCtxt, it: &hir::Item) {
let tcx = ccx.tcx;
debug!("convert: item {} with id {}", it.name, it.id);
let def_id = ccx.tcx.hir.local_def_id(it.id);
match it.node {
// These don't define types.
hir::ItemExternCrate(_) | hir::ItemUse(..) | hir::ItemMod(_) => {
}
hir::ItemForeignMod(ref foreign_mod) => {
for item in &foreign_mod.items {
convert_foreign_item(ccx, item);
}
}
hir::ItemEnum(ref enum_definition, _) => {
let ty = type_of_def_id(ccx, def_id);
let generics = generics_of_def_id(ccx, def_id);
let predicates = predicates_of_item(ccx, it);
convert_enum_variant_types(ccx,
tcx.lookup_adt_def(ccx.tcx.hir.local_def_id(it.id)),
ty,
generics,
predicates,
&enum_definition.variants);
},
hir::ItemDefaultImpl(_, ref ast_trait_ref) => {
let trait_ref =
AstConv::instantiate_mono_trait_ref(&ccx.icx(&()),
ast_trait_ref,
tcx.mk_self_type());
tcx.record_trait_has_default_impl(trait_ref.def_id);
tcx.impl_trait_refs.borrow_mut().insert(ccx.tcx.hir.local_def_id(it.id),
Some(trait_ref));
}
hir::ItemImpl(..,
ref generics,
ref opt_trait_ref,
ref selfty,
_) => {
// Create generics from the generics specified in the impl head.
debug!("convert: ast_generics={:?}", generics);
generics_of_def_id(ccx, def_id);
let mut ty_predicates =
ty_generic_predicates(ccx, generics, None, vec![], false);
debug!("convert: impl_bounds={:?}", ty_predicates);
let selfty = ccx.icx(&ty_predicates).to_ty(&selfty);
tcx.item_types.borrow_mut().insert(def_id, selfty);
let trait_ref = opt_trait_ref.as_ref().map(|ast_trait_ref| {
AstConv::instantiate_mono_trait_ref(&ccx.icx(&ty_predicates),
ast_trait_ref,
selfty)
});
tcx.impl_trait_refs.borrow_mut().insert(def_id, trait_ref);
// Subtle: before we store the predicates into the tcx, we
// sort them so that predicates like `T: Foo<Item=U>` come
// before uses of `U`. This avoids false ambiguity errors
// in trait checking. See `setup_constraining_predicates`
// for details.
ctp::setup_constraining_predicates(&mut ty_predicates.predicates,
trait_ref,
&mut ctp::parameters_for_impl(selfty, trait_ref));
tcx.predicates.borrow_mut().insert(def_id, ty_predicates.clone());
},
hir::ItemTrait(..) => {
generics_of_def_id(ccx, def_id);
trait_def_of_item(ccx, it);
let _: Result<(), ErrorReported> = // any error is already reported, can ignore
ccx.ensure_super_predicates(it.span, def_id);
convert_trait_predicates(ccx, it);
},
hir::ItemStruct(ref struct_def, _) |
hir::ItemUnion(ref struct_def, _) => {
let ty = type_of_def_id(ccx, def_id);
let generics = generics_of_def_id(ccx, def_id);
let predicates = predicates_of_item(ccx, it);
let variant = tcx.lookup_adt_def(def_id).struct_variant();
for (f, ty_f) in struct_def.fields().iter().zip(variant.fields.iter()) {
convert_field(ccx, generics, &predicates, f, ty_f)
}
if !struct_def.is_struct() {
convert_variant_ctor(ccx, struct_def.id(), variant, ty, predicates);
}
},
hir::ItemTy(_, ref generics) => {
ensure_no_ty_param_bounds(ccx, it.span, generics, "type");
type_of_def_id(ccx, def_id);
generics_of_def_id(ccx, def_id);
predicates_of_item(ccx, it);
},
_ => {
type_of_def_id(ccx, def_id);
generics_of_def_id(ccx, def_id);
predicates_of_item(ccx, it);
},
}
}
fn convert_trait_item(ccx: &CrateCtxt, trait_item: &hir::TraitItem) {
let tcx = ccx.tcx;
// we can lookup details about the trait because items are visited
// before trait-items
let trait_def_id = tcx.hir.get_parent_did(trait_item.id);
let trait_predicates = tcx.item_predicates(trait_def_id);
match trait_item.node {
hir::TraitItemKind::Const(ref ty, _) => {
let const_def_id = ccx.tcx.hir.local_def_id(trait_item.id);
generics_of_def_id(ccx, const_def_id);
let ty = ccx.icx(&trait_predicates).to_ty(&ty);
tcx.item_types.borrow_mut().insert(const_def_id, ty);
convert_associated_const(ccx, TraitContainer(trait_def_id),
trait_item.id, ty);
}
hir::TraitItemKind::Type(_, ref opt_ty) => {
let type_def_id = ccx.tcx.hir.local_def_id(trait_item.id);
generics_of_def_id(ccx, type_def_id);
let typ = opt_ty.as_ref().map({
|ty| ccx.icx(&trait_predicates).to_ty(&ty)
});
convert_associated_type(ccx, TraitContainer(trait_def_id), trait_item.id, typ);
}
hir::TraitItemKind::Method(ref sig, _) => {
convert_method(ccx, trait_item.id, sig, &trait_predicates);
}
}
}
fn convert_impl_item(ccx: &CrateCtxt, impl_item: &hir::ImplItem) {
let tcx = ccx.tcx;
// we can lookup details about the impl because items are visited
// before impl-items
let impl_def_id = tcx.hir.get_parent_did(impl_item.id);
let impl_predicates = tcx.item_predicates(impl_def_id);
let impl_trait_ref = tcx.impl_trait_ref(impl_def_id);
match impl_item.node {
hir::ImplItemKind::Const(ref ty, _) => {
let const_def_id = ccx.tcx.hir.local_def_id(impl_item.id);
generics_of_def_id(ccx, const_def_id);
let ty = ccx.icx(&impl_predicates).to_ty(&ty);
tcx.item_types.borrow_mut().insert(const_def_id, ty);
convert_associated_const(ccx, ImplContainer(impl_def_id),
impl_item.id, ty);
}
hir::ImplItemKind::Type(ref ty) => {
let type_def_id = ccx.tcx.hir.local_def_id(impl_item.id);
generics_of_def_id(ccx, type_def_id);
if impl_trait_ref.is_none() {
span_err!(tcx.sess, impl_item.span, E0202,
"associated types are not allowed in inherent impls");
}
let typ = ccx.icx(&impl_predicates).to_ty(ty);
convert_associated_type(ccx, ImplContainer(impl_def_id), impl_item.id, Some(typ));
}
hir::ImplItemKind::Method(ref sig, _) => {
convert_method(ccx, impl_item.id, sig, &impl_predicates);
}
}
}
fn convert_variant_ctor<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
ctor_id: ast::NodeId,
variant: &'tcx ty::VariantDef,
ty: Ty<'tcx>,
predicates: ty::GenericPredicates<'tcx>) {
let tcx = ccx.tcx;
let def_id = tcx.hir.local_def_id(ctor_id);
generics_of_def_id(ccx, def_id);
let ctor_ty = match variant.ctor_kind {
CtorKind::Fictive | CtorKind::Const => ty,
CtorKind::Fn => {
let inputs = variant.fields.iter().map(|field| tcx.item_type(field.did));
let substs = mk_item_substs(&ccx.icx(&predicates), ccx.tcx.hir.span(ctor_id), def_id);
tcx.mk_fn_def(def_id, substs, tcx.mk_bare_fn(ty::BareFnTy {
unsafety: hir::Unsafety::Normal,
abi: abi::Abi::Rust,
sig: ty::Binder(ccx.tcx.mk_fn_sig(inputs, ty, false))
}))
}
};
tcx.item_types.borrow_mut().insert(def_id, ctor_ty);
tcx.predicates.borrow_mut().insert(tcx.hir.local_def_id(ctor_id), predicates);
}
fn convert_enum_variant_types<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
def: &'tcx ty::AdtDef,
ty: Ty<'tcx>,
generics: &'tcx ty::Generics<'tcx>,
predicates: ty::GenericPredicates<'tcx>,
variants: &[hir::Variant]) {
// fill the field types
for (variant, ty_variant) in variants.iter().zip(def.variants.iter()) {
for (f, ty_f) in variant.node.data.fields().iter().zip(ty_variant.fields.iter()) {
convert_field(ccx, generics, &predicates, f, ty_f)
}
// Convert the ctor, if any. This also registers the variant as
// an item.
convert_variant_ctor(
ccx,
variant.node.data.id(),
ty_variant,
ty,
predicates.clone()
);
}
}
fn convert_struct_variant<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
did: DefId,
name: ast::Name,
disr_val: ty::Disr,
def: &hir::VariantData)
-> ty::VariantDef {
let mut seen_fields: FxHashMap<ast::Name, Span> = FxHashMap();
let node_id = ccx.tcx.hir.as_local_node_id(did).unwrap();
let fields = def.fields().iter().map(|f| {
let fid = ccx.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!(ccx.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, ccx.tcx)
}
}).collect();
ty::VariantDef {
did: did,
name: name,
disr_val: disr_val,
fields: fields,
ctor_kind: CtorKind::from_hir(def),
}
}
fn convert_struct_def<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
it: &hir::Item,
def: &hir::VariantData)
-> &'tcx ty::AdtDef