-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
Copy pathlib.rs
1773 lines (1602 loc) · 72.6 KB
/
lib.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.
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
#![feature(rustc_diagnostic_macros)]
#![recursion_limit="256"]
#[macro_use] extern crate rustc;
#[macro_use] extern crate syntax;
extern crate rustc_typeck;
extern crate syntax_pos;
extern crate rustc_data_structures;
use rustc::hir::{self, GenericParamKind, PatKind};
use rustc::hir::def::Def;
use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::itemlikevisit::DeepVisitor;
use rustc::lint;
use rustc::middle::privacy::{AccessLevel, AccessLevels};
use rustc::ty::{self, TyCtxt, Ty, TypeFoldable, GenericParamDefKind};
use rustc::ty::fold::TypeVisitor;
use rustc::ty::query::Providers;
use rustc::ty::subst::UnpackedKind;
use rustc::util::nodemap::NodeSet;
use syntax::ast::{self, CRATE_NODE_ID, Ident};
use syntax::symbol::keywords;
use syntax_pos::Span;
use std::cmp;
use std::mem::replace;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::Lrc;
mod diagnostics;
////////////////////////////////////////////////////////////////////////////////
/// Visitor used to determine if pub(restricted) is used anywhere in the crate.
///
/// This is done so that `private_in_public` warnings can be turned into hard errors
/// in crates that have been updated to use pub(restricted).
////////////////////////////////////////////////////////////////////////////////
struct PubRestrictedVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
has_pub_restricted: bool,
}
impl<'a, 'tcx> Visitor<'tcx> for PubRestrictedVisitor<'a, 'tcx> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
NestedVisitorMap::All(&self.tcx.hir)
}
fn visit_vis(&mut self, vis: &'tcx hir::Visibility) {
self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted();
}
}
////////////////////////////////////////////////////////////////////////////////
/// The embargo visitor, used to determine the exports of the ast
////////////////////////////////////////////////////////////////////////////////
struct EmbargoVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
// Accessibility levels for reachable nodes
access_levels: AccessLevels,
// Previous accessibility level, None means unreachable
prev_level: Option<AccessLevel>,
// Have something changed in the level map?
changed: bool,
}
struct ReachEverythingInTheInterfaceVisitor<'b, 'a: 'b, 'tcx: 'a> {
item_def_id: DefId,
ev: &'b mut EmbargoVisitor<'a, 'tcx>,
}
impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
fn item_ty_level(&self, item_def_id: DefId) -> Option<AccessLevel> {
let ty_def_id = match self.tcx.type_of(item_def_id).sty {
ty::TyAdt(adt, _) => adt.did,
ty::TyForeign(did) => did,
ty::TyDynamic(ref obj, ..) if obj.principal().is_some() =>
obj.principal().unwrap().def_id(),
ty::TyProjection(ref proj) => proj.trait_ref(self.tcx).def_id,
_ => return Some(AccessLevel::Public)
};
if let Some(node_id) = self.tcx.hir.as_local_node_id(ty_def_id) {
self.get(node_id)
} else {
Some(AccessLevel::Public)
}
}
fn impl_trait_level(&self, impl_def_id: DefId) -> Option<AccessLevel> {
if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_def_id) {
if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
return self.get(node_id);
}
}
Some(AccessLevel::Public)
}
fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
self.access_levels.map.get(&id).cloned()
}
// Updates node level and returns the updated level
fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
let old_level = self.get(id);
// Accessibility levels can only grow
if level > old_level {
self.access_levels.map.insert(id, level.unwrap());
self.changed = true;
level
} else {
old_level
}
}
fn reach<'b>(&'b mut self, item_id: ast::NodeId)
-> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
ReachEverythingInTheInterfaceVisitor {
item_def_id: self.tcx.hir.local_def_id(item_id),
ev: self,
}
}
}
impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> {
/// We want to visit items in the context of their containing
/// module and so forth, so supply a crate for doing a deep walk.
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
NestedVisitorMap::All(&self.tcx.hir)
}
fn visit_item(&mut self, item: &'tcx hir::Item) {
let inherited_item_level = match item.node {
// Impls inherit level from their types and traits
hir::ItemKind::Impl(..) => {
let def_id = self.tcx.hir.local_def_id(item.id);
cmp::min(self.item_ty_level(def_id), self.impl_trait_level(def_id))
}
// Foreign mods inherit level from parents
hir::ItemKind::ForeignMod(..) => {
self.prev_level
}
// Other `pub` items inherit levels from parents
hir::ItemKind::Const(..) | hir::ItemKind::Enum(..) | hir::ItemKind::ExternCrate(..) |
hir::ItemKind::GlobalAsm(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) |
hir::ItemKind::Static(..) | hir::ItemKind::Struct(..) |
hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) |
hir::ItemKind::Existential(..) |
hir::ItemKind::Ty(..) | hir::ItemKind::Union(..) | hir::ItemKind::Use(..) => {
if item.vis.node.is_pub() { self.prev_level } else { None }
}
};
// Update level of the item itself
let item_level = self.update(item.id, inherited_item_level);
// Update levels of nested things
match item.node {
hir::ItemKind::Enum(ref def, _) => {
for variant in &def.variants {
let variant_level = self.update(variant.node.data.id(), item_level);
for field in variant.node.data.fields() {
self.update(field.id, variant_level);
}
}
}
hir::ItemKind::Impl(.., None, _, ref impl_item_refs) => {
for impl_item_ref in impl_item_refs {
if impl_item_ref.vis.node.is_pub() {
self.update(impl_item_ref.id.node_id, item_level);
}
}
}
hir::ItemKind::Impl(.., Some(_), _, ref impl_item_refs) => {
for impl_item_ref in impl_item_refs {
self.update(impl_item_ref.id.node_id, item_level);
}
}
hir::ItemKind::Trait(.., ref trait_item_refs) => {
for trait_item_ref in trait_item_refs {
self.update(trait_item_ref.id.node_id, item_level);
}
}
hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
if !def.is_struct() {
self.update(def.id(), item_level);
}
for field in def.fields() {
if field.vis.node.is_pub() {
self.update(field.id, item_level);
}
}
}
hir::ItemKind::ForeignMod(ref foreign_mod) => {
for foreign_item in &foreign_mod.items {
if foreign_item.vis.node.is_pub() {
self.update(foreign_item.id, item_level);
}
}
}
hir::ItemKind::Existential(..) |
hir::ItemKind::Use(..) |
hir::ItemKind::Static(..) |
hir::ItemKind::Const(..) |
hir::ItemKind::GlobalAsm(..) |
hir::ItemKind::Ty(..) |
hir::ItemKind::Mod(..) |
hir::ItemKind::TraitAlias(..) |
hir::ItemKind::Fn(..) |
hir::ItemKind::ExternCrate(..) => {}
}
// Mark all items in interfaces of reachable items as reachable
match item.node {
// The interface is empty
hir::ItemKind::ExternCrate(..) => {}
// All nested items are checked by visit_item
hir::ItemKind::Mod(..) => {}
// Re-exports are handled in visit_mod
hir::ItemKind::Use(..) => {}
// The interface is empty
hir::ItemKind::GlobalAsm(..) => {}
hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {
if item_level.is_some() {
// Reach the (potentially private) type and the API being exposed
self.reach(item.id).ty().predicates();
}
}
// Visit everything
hir::ItemKind::Const(..) | hir::ItemKind::Static(..) |
hir::ItemKind::Existential(..) |
hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) => {
if item_level.is_some() {
self.reach(item.id).generics().predicates().ty();
}
}
hir::ItemKind::Trait(.., ref trait_item_refs) => {
if item_level.is_some() {
self.reach(item.id).generics().predicates();
for trait_item_ref in trait_item_refs {
let mut reach = self.reach(trait_item_ref.id.node_id);
reach.generics().predicates();
if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
!trait_item_ref.defaultness.has_value() {
// No type to visit.
} else {
reach.ty();
}
}
}
}
hir::ItemKind::TraitAlias(..) => {
if item_level.is_some() {
self.reach(item.id).generics().predicates();
}
}
// Visit everything except for private impl items
hir::ItemKind::Impl(.., ref trait_ref, _, ref impl_item_refs) => {
if item_level.is_some() {
self.reach(item.id).generics().predicates().impl_trait_ref();
for impl_item_ref in impl_item_refs {
let id = impl_item_ref.id.node_id;
if trait_ref.is_some() || self.get(id).is_some() {
self.reach(id).generics().predicates().ty();
}
}
}
}
// Visit everything, but enum variants have their own levels
hir::ItemKind::Enum(ref def, _) => {
if item_level.is_some() {
self.reach(item.id).generics().predicates();
}
for variant in &def.variants {
if self.get(variant.node.data.id()).is_some() {
for field in variant.node.data.fields() {
self.reach(field.id).ty();
}
// Corner case: if the variant is reachable, but its
// enum is not, make the enum reachable as well.
self.update(item.id, Some(AccessLevel::Reachable));
}
}
}
// Visit everything, but foreign items have their own levels
hir::ItemKind::ForeignMod(ref foreign_mod) => {
for foreign_item in &foreign_mod.items {
if self.get(foreign_item.id).is_some() {
self.reach(foreign_item.id).generics().predicates().ty();
}
}
}
// Visit everything except for private fields
hir::ItemKind::Struct(ref struct_def, _) |
hir::ItemKind::Union(ref struct_def, _) => {
if item_level.is_some() {
self.reach(item.id).generics().predicates();
for field in struct_def.fields() {
if self.get(field.id).is_some() {
self.reach(field.id).ty();
}
}
}
}
}
let orig_level = self.prev_level;
self.prev_level = item_level;
intravisit::walk_item(self, item);
self.prev_level = orig_level;
}
fn visit_block(&mut self, b: &'tcx hir::Block) {
let orig_level = replace(&mut self.prev_level, None);
// Blocks can have public items, for example impls, but they always
// start as completely private regardless of publicity of a function,
// constant, type, field, etc. in which this block resides
intravisit::walk_block(self, b);
self.prev_level = orig_level;
}
fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
// This code is here instead of in visit_item so that the
// crate module gets processed as well.
if self.prev_level.is_some() {
let def_id = self.tcx.hir.local_def_id(id);
if let Some(exports) = self.tcx.module_exports(def_id) {
for export in exports.iter() {
if let Some(node_id) = self.tcx.hir.as_local_node_id(export.def.def_id()) {
if export.vis == ty::Visibility::Public {
self.update(node_id, Some(AccessLevel::Exported));
}
}
}
}
}
intravisit::walk_mod(self, m, id);
}
fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
if md.legacy {
self.update(md.id, Some(AccessLevel::Public));
return
}
let module_did = ty::DefIdTree::parent(self.tcx, self.tcx.hir.local_def_id(md.id)).unwrap();
let mut module_id = self.tcx.hir.as_local_node_id(module_did).unwrap();
let level = if md.vis.node.is_pub() { self.get(module_id) } else { None };
let level = self.update(md.id, level);
if level.is_none() {
return
}
loop {
let module = if module_id == ast::CRATE_NODE_ID {
&self.tcx.hir.krate().module
} else if let hir::ItemKind::Mod(ref module) = self.tcx.hir.expect_item(module_id).node
{
module
} else {
unreachable!()
};
for id in &module.item_ids {
self.update(id.id, level);
}
let def_id = self.tcx.hir.local_def_id(module_id);
if let Some(exports) = self.tcx.module_exports(def_id) {
for export in exports.iter() {
if let Some(node_id) = self.tcx.hir.as_local_node_id(export.def.def_id()) {
self.update(node_id, level);
}
}
}
if module_id == ast::CRATE_NODE_ID {
break
}
module_id = self.tcx.hir.get_parent_node(module_id);
}
}
}
impl<'b, 'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
fn generics(&mut self) -> &mut Self {
for param in &self.ev.tcx.generics_of(self.item_def_id).params {
match param.kind {
GenericParamDefKind::Type { has_default, .. } => {
if has_default {
self.ev.tcx.type_of(param.def_id).visit_with(self);
}
}
GenericParamDefKind::Lifetime => {}
}
}
self
}
fn predicates(&mut self) -> &mut Self {
let predicates = self.ev.tcx.predicates_of(self.item_def_id);
for predicate in &predicates.predicates {
predicate.visit_with(self);
match predicate {
&ty::Predicate::Trait(poly_predicate) => {
self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
},
&ty::Predicate::Projection(poly_predicate) => {
let tcx = self.ev.tcx;
self.check_trait_ref(
poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
);
},
_ => (),
};
}
self
}
fn ty(&mut self) -> &mut Self {
let ty = self.ev.tcx.type_of(self.item_def_id);
ty.visit_with(self);
if let ty::TyFnDef(def_id, _) = ty.sty {
if def_id == self.item_def_id {
self.ev.tcx.fn_sig(def_id).visit_with(self);
}
}
self
}
fn impl_trait_ref(&mut self) -> &mut Self {
if let Some(impl_trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
self.check_trait_ref(impl_trait_ref);
impl_trait_ref.super_visit_with(self);
}
self
}
fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(trait_ref.def_id) {
let item = self.ev.tcx.hir.expect_item(node_id);
self.ev.update(item.id, Some(AccessLevel::Reachable));
}
}
}
impl<'b, 'a, 'tcx> TypeVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
let ty_def_id = match ty.sty {
ty::TyAdt(adt, _) => Some(adt.did),
ty::TyForeign(did) => Some(did),
ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
ty::TyProjection(ref proj) => Some(proj.item_def_id),
ty::TyFnDef(def_id, ..) |
ty::TyClosure(def_id, ..) |
ty::TyGenerator(def_id, ..) |
ty::TyAnon(def_id, _) => Some(def_id),
_ => None
};
if let Some(def_id) = ty_def_id {
if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(def_id) {
self.ev.update(node_id, Some(AccessLevel::Reachable));
}
}
ty.super_visit_with(self)
}
}
//////////////////////////////////////////////////////////////////////////////////////
/// Name privacy visitor, checks privacy and reports violations.
/// Most of name privacy checks are performed during the main resolution phase,
/// or later in type checking when field accesses and associated items are resolved.
/// This pass performs remaining checks for fields in struct expressions and patterns.
//////////////////////////////////////////////////////////////////////////////////////
struct NamePrivacyVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
tables: &'a ty::TypeckTables<'tcx>,
current_item: ast::NodeId,
empty_tables: &'a ty::TypeckTables<'tcx>,
}
impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
// Checks that a field in a struct constructor (expression or pattern) is accessible.
fn check_field(&mut self,
use_ctxt: Span, // Syntax context of the field name at the use site
span: Span, // Span of the field pattern, e.g. `x: 0`
def: &'tcx ty::AdtDef, // Definition of the struct or enum
field: &'tcx ty::FieldDef) { // Definition of the field
let ident = Ident::new(keywords::Invalid.name(), use_ctxt);
let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
field.ident, def.variant_descr(), self.tcx.item_path_str(def.did))
.span_label(span, format!("field `{}` is private", field.ident))
.emit();
}
}
}
// Set the correct TypeckTables for the given `item_id` (or an empty table if
// there is no TypeckTables for the item).
fn update_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
item_id: ast::NodeId,
tables: &mut &'a ty::TypeckTables<'tcx>,
empty_tables: &'a ty::TypeckTables<'tcx>)
-> &'a ty::TypeckTables<'tcx> {
let def_id = tcx.hir.local_def_id(item_id);
if tcx.has_typeck_tables(def_id) {
replace(tables, tcx.typeck_tables_of(def_id))
} else {
replace(tables, empty_tables)
}
}
impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
/// We want to visit items in the context of their containing
/// module and so forth, so supply a crate for doing a deep walk.
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
NestedVisitorMap::All(&self.tcx.hir)
}
fn visit_nested_body(&mut self, body: hir::BodyId) {
let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
let body = self.tcx.hir.body(body);
self.visit_body(body);
self.tables = orig_tables;
}
fn visit_item(&mut self, item: &'tcx hir::Item) {
let orig_current_item = replace(&mut self.current_item, item.id);
let orig_tables = update_tables(self.tcx, item.id, &mut self.tables, self.empty_tables);
intravisit::walk_item(self, item);
self.current_item = orig_current_item;
self.tables = orig_tables;
}
fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
intravisit::walk_trait_item(self, ti);
self.tables = orig_tables;
}
fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
intravisit::walk_impl_item(self, ii);
self.tables = orig_tables;
}
fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
match expr.node {
hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
let def = self.tables.qpath_def(qpath, expr.hir_id);
let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
let variant = adt.variant_of_def(def);
if let Some(ref base) = *base {
// If the expression uses FRU we need to make sure all the unmentioned fields
// are checked for privacy (RFC 736). Rather than computing the set of
// unmentioned fields, just check them all.
for (vf_index, variant_field) in variant.fields.iter().enumerate() {
let field = fields.iter().find(|f| {
self.tcx.field_index(f.id, self.tables) == vf_index
});
let (use_ctxt, span) = match field {
Some(field) => (field.ident.span, field.span),
None => (base.span, base.span),
};
self.check_field(use_ctxt, span, adt, variant_field);
}
} else {
for field in fields {
let use_ctxt = field.ident.span;
let index = self.tcx.field_index(field.id, self.tables);
self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
}
}
}
_ => {}
}
intravisit::walk_expr(self, expr);
}
fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
match pat.node {
PatKind::Struct(ref qpath, ref fields, _) => {
let def = self.tables.qpath_def(qpath, pat.hir_id);
let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
let variant = adt.variant_of_def(def);
for field in fields {
let use_ctxt = field.node.ident.span;
let index = self.tcx.field_index(field.node.id, self.tables);
self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
}
}
_ => {}
}
intravisit::walk_pat(self, pat);
}
}
////////////////////////////////////////////////////////////////////////////////////////////
/// Type privacy visitor, checks types for privacy and reports violations.
/// Both explicitly written types and inferred types of expressions and patters are checked.
/// Checks are performed on "semantic" types regardless of names and their hygiene.
////////////////////////////////////////////////////////////////////////////////////////////
struct TypePrivacyVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
tables: &'a ty::TypeckTables<'tcx>,
current_item: DefId,
in_body: bool,
span: Span,
empty_tables: &'a ty::TypeckTables<'tcx>,
visited_anon_tys: FxHashSet<DefId>
}
impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
fn def_id_visibility(&self, did: DefId) -> ty::Visibility {
match self.tcx.hir.as_local_node_id(did) {
Some(node_id) => {
let vis = match self.tcx.hir.get(node_id) {
hir::map::NodeItem(item) => &item.vis,
hir::map::NodeForeignItem(foreign_item) => &foreign_item.vis,
hir::map::NodeImplItem(impl_item) => &impl_item.vis,
hir::map::NodeTraitItem(..) |
hir::map::NodeVariant(..) => {
return self.def_id_visibility(self.tcx.hir.get_parent_did(node_id));
}
hir::map::NodeStructCtor(vdata) => {
let struct_node_id = self.tcx.hir.get_parent(node_id);
let struct_vis = match self.tcx.hir.get(struct_node_id) {
hir::map::NodeItem(item) => &item.vis,
node => bug!("unexpected node kind: {:?}", node),
};
let mut ctor_vis
= ty::Visibility::from_hir(struct_vis, struct_node_id, self.tcx);
for field in vdata.fields() {
let field_vis = ty::Visibility::from_hir(&field.vis, node_id, self.tcx);
if ctor_vis.is_at_least(field_vis, self.tcx) {
ctor_vis = field_vis;
}
}
// If the structure is marked as non_exhaustive then lower the
// visibility to within the crate.
let struct_def_id = self.tcx.hir.get_parent_did(node_id);
let adt_def = self.tcx.adt_def(struct_def_id);
if adt_def.is_non_exhaustive() && ctor_vis == ty::Visibility::Public {
ctor_vis = ty::Visibility::Restricted(
DefId::local(CRATE_DEF_INDEX));
}
return ctor_vis;
}
node => bug!("unexpected node kind: {:?}", node)
};
ty::Visibility::from_hir(vis, node_id, self.tcx)
}
None => self.tcx.visibility(did),
}
}
fn item_is_accessible(&self, did: DefId) -> bool {
self.def_id_visibility(did).is_accessible_from(self.current_item, self.tcx)
}
// Take node ID of an expression or pattern and check its type for privacy.
fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
self.span = span;
if self.tables.node_id_to_type(id).visit_with(self) {
return true;
}
if self.tables.node_substs(id).visit_with(self) {
return true;
}
if let Some(adjustments) = self.tables.adjustments().get(id) {
for adjustment in adjustments {
if adjustment.target.visit_with(self) {
return true;
}
}
}
false
}
fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
if !self.item_is_accessible(trait_ref.def_id) {
let msg = format!("trait `{}` is private", trait_ref);
self.tcx.sess.span_err(self.span, &msg);
return true;
}
trait_ref.super_visit_with(self)
}
}
impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
/// We want to visit items in the context of their containing
/// module and so forth, so supply a crate for doing a deep walk.
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
NestedVisitorMap::All(&self.tcx.hir)
}
fn visit_nested_body(&mut self, body: hir::BodyId) {
let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
let orig_in_body = replace(&mut self.in_body, true);
let body = self.tcx.hir.body(body);
self.visit_body(body);
self.tables = orig_tables;
self.in_body = orig_in_body;
}
fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty) {
self.span = hir_ty.span;
if self.in_body {
// Types in bodies.
if self.tables.node_id_to_type(hir_ty.hir_id).visit_with(self) {
return;
}
} else {
// Types in signatures.
// FIXME: This is very ineffective. Ideally each HIR type should be converted
// into a semantic type only once and the result should be cached somehow.
if rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty).visit_with(self) {
return;
}
}
intravisit::walk_ty(self, hir_ty);
}
fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef) {
self.span = trait_ref.path.span;
if !self.in_body {
// Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
// The traits' privacy in bodies is already checked as a part of trait object types.
let (principal, projections) =
rustc_typeck::hir_trait_to_predicates(self.tcx, trait_ref);
if self.check_trait_ref(*principal.skip_binder()) {
return;
}
for poly_predicate in projections {
let tcx = self.tcx;
if self.check_trait_ref(poly_predicate.skip_binder().projection_ty.trait_ref(tcx)) {
return;
}
}
}
intravisit::walk_trait_ref(self, trait_ref);
}
// Check types of expressions
fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
if self.check_expr_pat_type(expr.hir_id, expr.span) {
// Do not check nested expressions if the error already happened.
return;
}
match expr.node {
hir::ExprKind::Assign(.., ref rhs) | hir::ExprKind::Match(ref rhs, ..) => {
// Do not report duplicate errors for `x = y` and `match x { ... }`.
if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
return;
}
}
hir::ExprKind::MethodCall(_, span, _) => {
// Method calls have to be checked specially.
self.span = span;
if let Some(def) = self.tables.type_dependent_defs().get(expr.hir_id) {
let def_id = def.def_id();
if self.tcx.type_of(def_id).visit_with(self) {
return;
}
} else {
self.tcx.sess.delay_span_bug(expr.span,
"no type-dependent def for method call");
}
}
_ => {}
}
intravisit::walk_expr(self, expr);
}
// Prohibit access to associated items with insufficient nominal visibility.
//
// Additionally, until better reachability analysis for macros 2.0 is available,
// we prohibit access to private statics from other crates, this allows to give
// more code internal visibility at link time. (Access to private functions
// is already prohibited by type privacy for function types.)
fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: ast::NodeId, span: Span) {
let def = match *qpath {
hir::QPath::Resolved(_, ref path) => match path.def {
Def::Method(..) | Def::AssociatedConst(..) |
Def::AssociatedTy(..) | Def::Static(..) => Some(path.def),
_ => None,
}
hir::QPath::TypeRelative(..) => {
let hir_id = self.tcx.hir.node_to_hir_id(id);
self.tables.type_dependent_defs().get(hir_id).cloned()
}
};
if let Some(def) = def {
let def_id = def.def_id();
let is_local_static = if let Def::Static(..) = def { def_id.is_local() } else { false };
if !self.item_is_accessible(def_id) && !is_local_static {
let name = match *qpath {
hir::QPath::Resolved(_, ref path) => path.to_string(),
hir::QPath::TypeRelative(_, ref segment) => segment.ident.to_string(),
};
let msg = format!("{} `{}` is private", def.kind_name(), name);
self.tcx.sess.span_err(span, &msg);
return;
}
}
intravisit::walk_qpath(self, qpath, id, span);
}
// Check types of patterns
fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
// Do not check nested patterns if the error already happened.
return;
}
intravisit::walk_pat(self, pattern);
}
fn visit_local(&mut self, local: &'tcx hir::Local) {
if let Some(ref init) = local.init {
if self.check_expr_pat_type(init.hir_id, init.span) {
// Do not report duplicate errors for `let x = y`.
return;
}
}
intravisit::walk_local(self, local);
}
// Check types in item interfaces
fn visit_item(&mut self, item: &'tcx hir::Item) {
let orig_current_item = self.current_item;
let orig_tables = update_tables(self.tcx,
item.id,
&mut self.tables,
self.empty_tables);
let orig_in_body = replace(&mut self.in_body, false);
self.current_item = self.tcx.hir.local_def_id(item.id);
intravisit::walk_item(self, item);
self.tables = orig_tables;
self.in_body = orig_in_body;
self.current_item = orig_current_item;
}
fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
intravisit::walk_trait_item(self, ti);
self.tables = orig_tables;
}
fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
intravisit::walk_impl_item(self, ii);
self.tables = orig_tables;
}
}
impl<'a, 'tcx> TypeVisitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
match ty.sty {
ty::TyAdt(&ty::AdtDef { did: def_id, .. }, ..) |
ty::TyFnDef(def_id, ..) |
ty::TyForeign(def_id) => {
if !self.item_is_accessible(def_id) {
let msg = format!("type `{}` is private", ty);
self.tcx.sess.span_err(self.span, &msg);
return true;
}
if let ty::TyFnDef(..) = ty.sty {
if self.tcx.fn_sig(def_id).visit_with(self) {
return true;
}
}
// Inherent static methods don't have self type in substs,
// we have to check it additionally.
if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
if let ty::ImplContainer(impl_def_id) = assoc_item.container {
if self.tcx.type_of(impl_def_id).visit_with(self) {
return true;
}
}
}
}
ty::TyDynamic(ref predicates, ..) => {
let is_private = predicates.skip_binder().iter().any(|predicate| {
let def_id = match *predicate {
ty::ExistentialPredicate::Trait(trait_ref) => trait_ref.def_id,
ty::ExistentialPredicate::Projection(proj) =>
proj.trait_ref(self.tcx).def_id,
ty::ExistentialPredicate::AutoTrait(def_id) => def_id,
};
!self.item_is_accessible(def_id)
});
if is_private {
let msg = format!("type `{}` is private", ty);
self.tcx.sess.span_err(self.span, &msg);
return true;
}
}
ty::TyProjection(ref proj) => {
let tcx = self.tcx;
if self.check_trait_ref(proj.trait_ref(tcx)) {
return true;
}
}
ty::TyAnon(def_id, ..) => {
for predicate in &self.tcx.predicates_of(def_id).predicates {
let trait_ref = match *predicate {
ty::Predicate::Trait(ref poly_trait_predicate) => {
Some(poly_trait_predicate.skip_binder().trait_ref)
}
ty::Predicate::Projection(ref poly_projection_predicate) => {
if poly_projection_predicate.skip_binder().ty.visit_with(self) {
return true;
}
Some(poly_projection_predicate.skip_binder()
.projection_ty.trait_ref(self.tcx))
}
ty::Predicate::TypeOutlives(..) => None,
_ => bug!("unexpected predicate: {:?}", predicate),
};
if let Some(trait_ref) = trait_ref {
if !self.item_is_accessible(trait_ref.def_id) {
let msg = format!("trait `{}` is private", trait_ref);
self.tcx.sess.span_err(self.span, &msg);
return true;
}
for subst in trait_ref.substs.iter() {
// Skip repeated `TyAnon`s to avoid infinite recursion.
if let UnpackedKind::Type(ty) = subst.unpack() {
if let ty::TyAnon(def_id, ..) = ty.sty {
if !self.visited_anon_tys.insert(def_id) {
continue;
}
}
}
if subst.visit_with(self) {
return true;
}
}
}
}
}
_ => {}
}
ty.super_visit_with(self)
}
}
///////////////////////////////////////////////////////////////////////////////
/// Obsolete visitors for checking for private items in public interfaces.
/// These visitors are supposed to be kept in frozen state and produce an
/// "old error node set". For backward compatibility the new visitor reports
/// warnings instead of hard errors when the erroneous node is not in this old set.
///////////////////////////////////////////////////////////////////////////////
struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
access_levels: &'a AccessLevels,
in_variant: bool,
// set of errors produced by this obsolete visitor