forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
1636 lines (1489 loc) · 66.7 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.
#![crate_name = "rustc_privacy"]
#![unstable(feature = "rustc_private", issue = "27812")]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![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/")]
#![cfg_attr(not(stage0), deny(warnings))]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
extern crate rustc;
extern crate rustc_front;
use self::PrivacyResult::*;
use self::FieldName::*;
use std::cmp;
use std::mem::replace;
use rustc_front::hir::{self, PatKind};
use rustc_front::intravisit::{self, Visitor};
use rustc::dep_graph::DepNode;
use rustc::lint;
use rustc::middle::cstore::CrateStore;
use rustc::middle::def::{self, Def};
use rustc::middle::def_id::DefId;
use rustc::middle::privacy::{AccessLevel, AccessLevels};
use rustc::middle::ty::{self, TyCtxt};
use rustc::util::nodemap::{NodeMap, NodeSet};
use rustc::front::map as ast_map;
use syntax::ast;
use syntax::codemap::Span;
pub mod diagnostics;
type Context<'a, 'tcx> = (&'a ty::MethodMap<'tcx>, &'a def::ExportMap);
/// Result of a checking operation - None => no errors were found. Some => an
/// error and contains the span and message for reporting that error and
/// optionally the same for a note about the error.
type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
////////////////////////////////////////////////////////////////////////////////
/// The parent visitor, used to determine what's the parent of what (node-wise)
////////////////////////////////////////////////////////////////////////////////
struct ParentVisitor<'a, 'tcx:'a> {
tcx: &'a TyCtxt<'tcx>,
parents: NodeMap<ast::NodeId>,
curparent: ast::NodeId,
}
impl<'a, 'tcx, 'v> Visitor<'v> for ParentVisitor<'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 visit_nested_item(&mut self, item: hir::ItemId) {
self.visit_item(self.tcx.map.expect_item(item.id))
}
fn visit_item(&mut self, item: &hir::Item) {
self.parents.insert(item.id, self.curparent);
let prev = self.curparent;
match item.node {
hir::ItemMod(..) => { self.curparent = item.id; }
// Enum variants are parented to the enum definition itself because
// they inherit privacy
hir::ItemEnum(ref def, _) => {
for variant in &def.variants {
// The parent is considered the enclosing enum because the
// enum will dictate the privacy visibility of this variant
// instead.
self.parents.insert(variant.node.data.id(), item.id);
}
}
// Trait methods are always considered "public", but if the trait is
// private then we need some private item in the chain from the
// method to the root. In this case, if the trait is private, then
// parent all the methods to the trait to indicate that they're
// private.
hir::ItemTrait(_, _, _, ref trait_items) if item.vis != hir::Public => {
for trait_item in trait_items {
self.parents.insert(trait_item.id, item.id);
}
}
_ => {}
}
intravisit::walk_item(self, item);
self.curparent = prev;
}
fn visit_foreign_item(&mut self, a: &hir::ForeignItem) {
self.parents.insert(a.id, self.curparent);
intravisit::walk_foreign_item(self, a);
}
fn visit_fn(&mut self, a: intravisit::FnKind<'v>, b: &'v hir::FnDecl,
c: &'v hir::Block, d: Span, id: ast::NodeId) {
// We already took care of some trait methods above, otherwise things
// like impl methods and pub trait methods are parented to the
// containing module, not the containing trait.
if !self.parents.contains_key(&id) {
self.parents.insert(id, self.curparent);
}
intravisit::walk_fn(self, a, b, c, d);
}
fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) {
// visit_fn handles methods, but associated consts have to be handled
// here.
if !self.parents.contains_key(&ii.id) {
self.parents.insert(ii.id, self.curparent);
}
intravisit::walk_impl_item(self, ii);
}
fn visit_variant_data(&mut self, s: &hir::VariantData, _: ast::Name,
_: &'v hir::Generics, item_id: ast::NodeId, _: Span) {
// Struct constructors are parented to their struct definitions because
// they essentially are the struct definitions.
if !s.is_struct() {
self.parents.insert(s.id(), item_id);
}
// While we have the id of the struct definition, go ahead and parent
// all the fields.
for field in s.fields() {
self.parents.insert(field.id, self.curparent);
}
intravisit::walk_struct_def(self, s)
}
}
////////////////////////////////////////////////////////////////////////////////
/// The embargo visitor, used to determine the exports of the ast
////////////////////////////////////////////////////////////////////////////////
struct EmbargoVisitor<'a, 'tcx: 'a> {
tcx: &'a TyCtxt<'tcx>,
export_map: &'a def::ExportMap,
// 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> {
ev: &'b mut EmbargoVisitor<'a, 'tcx>,
}
impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
fn ty_level(&self, ty: &hir::Ty) -> Option<AccessLevel> {
if let hir::TyPath(..) = ty.node {
match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
Def::PrimTy(..) | Def::SelfTy(..) | Def::TyParam(..) => {
Some(AccessLevel::Public)
}
def => {
if let Some(node_id) = self.tcx.map.as_local_node_id(def.def_id()) {
self.get(node_id)
} else {
Some(AccessLevel::Public)
}
}
}
} else {
Some(AccessLevel::Public)
}
}
fn trait_level(&self, trait_ref: &hir::TraitRef) -> Option<AccessLevel> {
let did = self.tcx.trait_ref_to_def_id(trait_ref);
if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
self.get(node_id)
} else {
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) -> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
ReachEverythingInTheInterfaceVisitor { ev: self }
}
}
impl<'a, 'tcx, 'v> Visitor<'v> 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 visit_nested_item(&mut self, item: hir::ItemId) {
self.visit_item(self.tcx.map.expect_item(item.id))
}
fn visit_item(&mut self, item: &hir::Item) {
let inherited_item_level = match item.node {
// Impls inherit level from their types and traits
hir::ItemImpl(_, _, _, None, ref ty, _) => {
self.ty_level(&ty)
}
hir::ItemImpl(_, _, _, Some(ref trait_ref), ref ty, _) => {
cmp::min(self.ty_level(&ty), self.trait_level(trait_ref))
}
hir::ItemDefaultImpl(_, ref trait_ref) => {
self.trait_level(trait_ref)
}
// Foreign mods inherit level from parents
hir::ItemForeignMod(..) => {
self.prev_level
}
// Other `pub` items inherit levels from parents
_ => {
if item.vis == hir::Public { 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::ItemEnum(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::ItemImpl(_, _, _, None, _, ref impl_items) => {
for impl_item in impl_items {
if impl_item.vis == hir::Public {
self.update(impl_item.id, item_level);
}
}
}
hir::ItemImpl(_, _, _, Some(_), _, ref impl_items) => {
for impl_item in impl_items {
self.update(impl_item.id, item_level);
}
}
hir::ItemTrait(_, _, _, ref trait_items) => {
for trait_item in trait_items {
self.update(trait_item.id, item_level);
}
}
hir::ItemStruct(ref def, _) => {
if !def.is_struct() {
self.update(def.id(), item_level);
}
for field in def.fields() {
if field.vis == hir::Public {
self.update(field.id, item_level);
}
}
}
hir::ItemForeignMod(ref foreign_mod) => {
for foreign_item in &foreign_mod.items {
if foreign_item.vis == hir::Public {
self.update(foreign_item.id, item_level);
}
}
}
_ => {}
}
// Mark all items in interfaces of reachable items as reachable
match item.node {
// The interface is empty
hir::ItemExternCrate(..) => {}
// All nested items are checked by visit_item
hir::ItemMod(..) => {}
// Reexports are handled in visit_mod
hir::ItemUse(..) => {}
// Visit everything
hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
hir::ItemTrait(..) | hir::ItemTy(..) | hir::ItemImpl(_, _, _, Some(..), _, _) => {
if item_level.is_some() {
self.reach().visit_item(item);
}
}
// Visit everything, but enum variants have their own levels
hir::ItemEnum(ref def, ref generics) => {
if item_level.is_some() {
self.reach().visit_generics(generics);
}
for variant in &def.variants {
if self.get(variant.node.data.id()).is_some() {
for field in variant.node.data.fields() {
self.reach().visit_struct_field(field);
}
// 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::ItemForeignMod(ref foreign_mod) => {
for foreign_item in &foreign_mod.items {
if self.get(foreign_item.id).is_some() {
self.reach().visit_foreign_item(foreign_item);
}
}
}
// Visit everything except for private fields
hir::ItemStruct(ref struct_def, ref generics) => {
if item_level.is_some() {
self.reach().visit_generics(generics);
for field in struct_def.fields() {
if self.get(field.id).is_some() {
self.reach().visit_struct_field(field);
}
}
}
}
// The interface is empty
hir::ItemDefaultImpl(..) => {}
// Visit everything except for private impl items
hir::ItemImpl(_, _, ref generics, None, _, ref impl_items) => {
if item_level.is_some() {
self.reach().visit_generics(generics);
for impl_item in impl_items {
if self.get(impl_item.id).is_some() {
self.reach().visit_impl_item(impl_item);
}
}
}
}
}
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: &'v 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: &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() {
if let Some(exports) = self.export_map.get(&id) {
for export in exports {
if let Some(node_id) = self.tcx.map.as_local_node_id(export.def_id) {
self.update(node_id, Some(AccessLevel::Exported));
}
}
}
}
intravisit::walk_mod(self, m);
}
fn visit_macro_def(&mut self, md: &'v hir::MacroDef) {
self.update(md.id, Some(AccessLevel::Public));
}
}
impl<'b, 'a, 'tcx: 'a> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
// Make the type hidden under a type alias reachable
fn reach_aliased_type(&mut self, item: &hir::Item, path: &hir::Path) {
if let hir::ItemTy(ref ty, ref generics) = item.node {
// See `fn is_public_type_alias` for details
self.visit_ty(ty);
let provided_params = path.segments.last().unwrap().parameters.types().len();
for ty_param in &generics.ty_params[provided_params..] {
if let Some(ref default_ty) = ty_param.default {
self.visit_ty(default_ty);
}
}
}
}
}
impl<'b, 'a, 'tcx: 'a, 'v> Visitor<'v> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
fn visit_ty(&mut self, ty: &hir::Ty) {
if let hir::TyPath(_, ref path) = ty.node {
let def = self.ev.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
match def {
Def::Struct(def_id) | Def::Enum(def_id) | Def::TyAlias(def_id) |
Def::Trait(def_id) | Def::AssociatedTy(def_id, _) => {
if let Some(node_id) = self.ev.tcx.map.as_local_node_id(def_id) {
let item = self.ev.tcx.map.expect_item(node_id);
if let Def::TyAlias(..) = def {
// Type aliases are substituted. Associated type aliases are not
// substituted yet, but ideally they should be.
if self.ev.get(item.id).is_none() {
self.reach_aliased_type(item, path);
}
} else {
self.ev.update(item.id, Some(AccessLevel::Reachable));
}
}
}
_ => {}
}
}
intravisit::walk_ty(self, ty);
}
fn visit_trait_ref(&mut self, trait_ref: &hir::TraitRef) {
let def_id = self.ev.tcx.trait_ref_to_def_id(trait_ref);
if let Some(node_id) = self.ev.tcx.map.as_local_node_id(def_id) {
let item = self.ev.tcx.map.expect_item(node_id);
self.ev.update(item.id, Some(AccessLevel::Reachable));
}
intravisit::walk_trait_ref(self, trait_ref);
}
// Don't recurse into function bodies
fn visit_block(&mut self, _: &hir::Block) {}
// Don't recurse into expressions in array sizes or const initializers
fn visit_expr(&mut self, _: &hir::Expr) {}
// Don't recurse into patterns in function arguments
fn visit_pat(&mut self, _: &hir::Pat) {}
}
////////////////////////////////////////////////////////////////////////////////
/// The privacy visitor, where privacy checks take place (violations reported)
////////////////////////////////////////////////////////////////////////////////
struct PrivacyVisitor<'a, 'tcx: 'a> {
tcx: &'a TyCtxt<'tcx>,
curitem: ast::NodeId,
in_foreign: bool,
parents: NodeMap<ast::NodeId>,
}
#[derive(Debug)]
enum PrivacyResult {
Allowable,
ExternallyDenied,
DisallowedBy(ast::NodeId),
}
enum FieldName {
UnnamedField(usize), // index
NamedField(ast::Name),
}
impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
// Determines whether the given definition is public from the point of view
// of the current item.
fn def_privacy(&self, did: DefId) -> PrivacyResult {
let node_id = if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
node_id
} else {
if self.tcx.sess.cstore.visibility(did) == hir::Public {
debug!("privacy - {:?} was externally exported", did);
return Allowable;
}
debug!("privacy - is {:?} a public method", did);
return match self.tcx.impl_or_trait_items.borrow().get(&did) {
Some(&ty::ConstTraitItem(ref ac)) => {
debug!("privacy - it's a const: {:?}", *ac);
match ac.container {
ty::TraitContainer(id) => {
debug!("privacy - recursing on trait {:?}", id);
self.def_privacy(id)
}
ty::ImplContainer(id) => {
match self.tcx.impl_trait_ref(id) {
Some(t) => {
debug!("privacy - impl of trait {:?}", id);
self.def_privacy(t.def_id)
}
None => {
debug!("privacy - found inherent \
associated constant {:?}",
ac.vis);
if ac.vis == hir::Public {
Allowable
} else {
ExternallyDenied
}
}
}
}
}
}
Some(&ty::MethodTraitItem(ref meth)) => {
debug!("privacy - well at least it's a method: {:?}",
*meth);
match meth.container {
ty::TraitContainer(id) => {
debug!("privacy - recursing on trait {:?}", id);
self.def_privacy(id)
}
ty::ImplContainer(id) => {
match self.tcx.impl_trait_ref(id) {
Some(t) => {
debug!("privacy - impl of trait {:?}", id);
self.def_privacy(t.def_id)
}
None => {
debug!("privacy - found a method {:?}",
meth.vis);
if meth.vis == hir::Public {
Allowable
} else {
ExternallyDenied
}
}
}
}
}
}
Some(&ty::TypeTraitItem(ref typedef)) => {
match typedef.container {
ty::TraitContainer(id) => {
debug!("privacy - recursing on trait {:?}", id);
self.def_privacy(id)
}
ty::ImplContainer(id) => {
match self.tcx.impl_trait_ref(id) {
Some(t) => {
debug!("privacy - impl of trait {:?}", id);
self.def_privacy(t.def_id)
}
None => {
debug!("privacy - found a typedef {:?}",
typedef.vis);
if typedef.vis == hir::Public {
Allowable
} else {
ExternallyDenied
}
}
}
}
}
}
None => {
debug!("privacy - nope, not even a method");
ExternallyDenied
}
};
};
debug!("privacy - local {} not public all the way down",
self.tcx.map.node_to_string(node_id));
// return quickly for things in the same module
if self.parents.get(&node_id) == self.parents.get(&self.curitem) {
debug!("privacy - same parent, we're done here");
return Allowable;
}
let vis = match self.tcx.map.find(node_id) {
// If this item is a method, then we know for sure that it's an
// actual method and not a static method. The reason for this is
// that these cases are only hit in the ExprMethodCall
// expression, and ExprCall will have its path checked later
// (the path of the trait/impl) if it's a static method.
//
// With this information, then we can completely ignore all
// trait methods. The privacy violation would be if the trait
// couldn't get imported, not if the method couldn't be used
// (all trait methods are public).
//
// However, if this is an impl method, then we dictate this
// decision solely based on the privacy of the method
// invocation.
Some(ast_map::NodeImplItem(ii)) => {
let imp = self.tcx.map.get_parent_did(node_id);
match self.tcx.impl_trait_ref(imp) {
Some(..) => hir::Public,
_ => ii.vis,
}
}
Some(ast_map::NodeTraitItem(_)) => hir::Public,
// This is not a method call, extract the visibility as one
// would normally look at it
Some(ast_map::NodeItem(it)) => it.vis,
Some(ast_map::NodeForeignItem(_)) => {
self.tcx.map.get_foreign_vis(node_id)
}
_ => hir::Public,
};
if vis == hir::Public { return Allowable }
if self.private_accessible(node_id) {
Allowable
} else {
DisallowedBy(node_id)
}
}
/// True if `id` is both local and private-accessible
fn local_private_accessible(&self, did: DefId) -> bool {
if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
self.private_accessible(node_id)
} else {
false
}
}
/// For a local private node in the AST, this function will determine
/// whether the node is accessible by the current module that iteration is
/// inside.
fn private_accessible(&self, id: ast::NodeId) -> bool {
self.tcx.map.private_item_is_visible_from(id, self.curitem)
}
fn report_error(&self, result: CheckResult) -> bool {
match result {
None => true,
Some((span, msg, note)) => {
let mut err = self.tcx.sess.struct_span_err(span, &msg[..]);
if let Some((span, msg)) = note {
err.span_note(span, &msg[..]);
}
err.emit();
false
},
}
}
/// Guarantee that a particular definition is public. Returns a CheckResult
/// which contains any errors found. These can be reported using `report_error`.
/// If the result is `None`, no errors were found.
fn ensure_public(&self,
span: Span,
to_check: DefId,
source_did: Option<DefId>,
msg: &str)
-> CheckResult {
debug!("ensure_public(span={:?}, to_check={:?}, source_did={:?}, msg={:?})",
span, to_check, source_did, msg);
let def_privacy = self.def_privacy(to_check);
debug!("ensure_public: def_privacy={:?}", def_privacy);
let id = match def_privacy {
ExternallyDenied => {
return Some((span, format!("{} is private", msg), None))
}
Allowable => return None,
DisallowedBy(id) => id,
};
// If we're disallowed by a particular id, then we attempt to
// give a nice error message to say why it was disallowed. It
// was either because the item itself is private or because
// its parent is private and its parent isn't in our
// ancestry. (Both the item being checked and its parent must
// be local.)
let def_id = source_did.unwrap_or(to_check);
let node_id = self.tcx.map.as_local_node_id(def_id);
let (err_span, err_msg) = if Some(id) == node_id {
return Some((span, format!("{} is private", msg), None));
} else {
(span, format!("{} is inaccessible", msg))
};
let item = match self.tcx.map.find(id) {
Some(ast_map::NodeItem(item)) => {
match item.node {
// If an impl disallowed this item, then this is resolve's
// way of saying that a struct/enum's static method was
// invoked, and the struct/enum itself is private. Crawl
// back up the chains to find the relevant struct/enum that
// was private.
hir::ItemImpl(_, _, _, _, ref ty, _) => {
match ty.node {
hir::TyPath(..) => {}
_ => return Some((err_span, err_msg, None)),
};
let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
let did = def.def_id();
let node_id = self.tcx.map.as_local_node_id(did).unwrap();
match self.tcx.map.get(node_id) {
ast_map::NodeItem(item) => item,
_ => self.tcx.sess.span_bug(item.span,
"path is not an item")
}
}
_ => item
}
}
Some(..) | None => return Some((err_span, err_msg, None)),
};
let desc = match item.node {
hir::ItemMod(..) => "module",
hir::ItemTrait(..) => "trait",
hir::ItemStruct(..) => "struct",
hir::ItemEnum(..) => "enum",
_ => return Some((err_span, err_msg, None))
};
let msg = format!("{} `{}` is private", desc, item.name);
Some((err_span, err_msg, Some((span, msg))))
}
// Checks that a field is in scope.
fn check_field(&mut self,
span: Span,
def: ty::AdtDef<'tcx>,
v: ty::VariantDef<'tcx>,
name: FieldName) {
let field = match name {
NamedField(f_name) => {
debug!("privacy - check named field {} in struct {:?}", f_name, def);
v.field_named(f_name)
}
UnnamedField(idx) => &v.fields[idx]
};
if field.vis == hir::Public || self.local_private_accessible(def.did) {
return;
}
let struct_desc = match def.adt_kind() {
ty::AdtKind::Struct =>
format!("struct `{}`", self.tcx.item_path_str(def.did)),
// struct variant fields have inherited visibility
ty::AdtKind::Enum => return
};
let msg = match name {
NamedField(name) => format!("field `{}` of {} is private",
name, struct_desc),
UnnamedField(idx) => format!("field #{} of {} is private",
idx, struct_desc),
};
span_err!(self.tcx.sess, span, E0451,
"{}", &msg[..]);
}
// Given the ID of a method, checks to ensure it's in scope.
fn check_static_method(&mut self,
span: Span,
method_id: DefId,
name: ast::Name) {
self.report_error(self.ensure_public(span,
method_id,
None,
&format!("method `{}`",
name)));
}
// Checks that a method is in scope.
fn check_method(&mut self, span: Span, method_def_id: DefId,
name: ast::Name) {
match self.tcx.impl_or_trait_item(method_def_id).container() {
ty::ImplContainer(_) => {
self.check_static_method(span, method_def_id, name)
}
// Trait methods are always all public. The only controlling factor
// is whether the trait itself is accessible or not.
ty::TraitContainer(trait_def_id) => {
let msg = format!("source trait `{}`", self.tcx.item_path_str(trait_def_id));
self.report_error(self.ensure_public(span, trait_def_id, None, &msg));
}
}
}
}
impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'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 visit_nested_item(&mut self, item: hir::ItemId) {
self.visit_item(self.tcx.map.expect_item(item.id))
}
fn visit_item(&mut self, item: &hir::Item) {
let orig_curitem = replace(&mut self.curitem, item.id);
intravisit::walk_item(self, item);
self.curitem = orig_curitem;
}
fn visit_expr(&mut self, expr: &hir::Expr) {
match expr.node {
hir::ExprField(ref base, name) => {
if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&base).sty {
self.check_field(expr.span,
def,
def.struct_variant(),
NamedField(name.node));
}
}
hir::ExprTupField(ref base, idx) => {
if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&base).sty {
self.check_field(expr.span,
def,
def.struct_variant(),
UnnamedField(idx.node));
}
}
hir::ExprMethodCall(name, _, _) => {
let method_call = ty::MethodCall::expr(expr.id);
let method = self.tcx.tables.borrow().method_map[&method_call];
debug!("(privacy checking) checking impl method");
self.check_method(expr.span, method.def_id, name.node);
}
hir::ExprStruct(..) => {
let adt = self.tcx.expr_ty(expr).ty_adt_def().unwrap();
let variant = adt.variant_of_def(self.tcx.resolve_expr(expr));
// RFC 736: ensure all unmentioned fields are visible.
// Rather than computing the set of unmentioned fields
// (i.e. `all_fields - fields`), just check them all.
for field in &variant.fields {
self.check_field(expr.span, adt, variant, NamedField(field.name));
}
}
hir::ExprPath(..) => {
if let Def::Struct(..) = self.tcx.resolve_expr(expr) {
let expr_ty = self.tcx.expr_ty(expr);
let def = match expr_ty.sty {
ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
output: ty::FnConverging(ty), ..
}), ..}) => ty,
_ => expr_ty
}.ty_adt_def().unwrap();
let any_priv = def.struct_variant().fields.iter().any(|f| {
f.vis != hir::Public && !self.local_private_accessible(def.did)
});
if any_priv {
span_err!(self.tcx.sess, expr.span, E0450,
"cannot invoke tuple struct constructor with private \
fields");
}
}
}
_ => {}
}
intravisit::walk_expr(self, expr);
}
fn visit_pat(&mut self, pattern: &hir::Pat) {
// Foreign functions do not have their patterns mapped in the def_map,
// and there's nothing really relevant there anyway, so don't bother
// checking privacy. If you can name the type then you can pass it to an
// external C function anyway.
if self.in_foreign { return }
match pattern.node {
PatKind::Struct(_, ref fields, _) => {
let adt = self.tcx.pat_ty(pattern).ty_adt_def().unwrap();
let def = self.tcx.def_map.borrow().get(&pattern.id).unwrap().full_def();
let variant = adt.variant_of_def(def);
for field in fields {
self.check_field(pattern.span, adt, variant,
NamedField(field.node.name));
}
}
// Patterns which bind no fields are allowable (the path is check
// elsewhere).
PatKind::TupleStruct(_, Some(ref fields)) => {
match self.tcx.pat_ty(pattern).sty {
ty::TyStruct(def, _) => {
for (i, field) in fields.iter().enumerate() {
if let PatKind::Wild = field.node {
continue
}
self.check_field(field.span,
def,
def.struct_variant(),
UnnamedField(i));
}
}
ty::TyEnum(..) => {
// enum fields have no privacy at this time
}
_ => {}
}
}
_ => {}
}
intravisit::walk_pat(self, pattern);
}
fn visit_foreign_item(&mut self, fi: &hir::ForeignItem) {
self.in_foreign = true;
intravisit::walk_foreign_item(self, fi);
self.in_foreign = false;
}
}
////////////////////////////////////////////////////////////////////////////////
/// The privacy sanity check visitor, ensures unnecessary visibility isn't here
////////////////////////////////////////////////////////////////////////////////
struct SanePrivacyVisitor<'a, 'tcx: 'a> {
tcx: &'a TyCtxt<'tcx>,
}
impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
fn visit_item(&mut self, item: &hir::Item) {
self.check_sane_privacy(item);
intravisit::walk_item(self, item);
}
}
impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
/// Validate that items that shouldn't have visibility qualifiers don't have them.
/// Such qualifiers can be set by syntax extensions even if the parser doesn't allow them,
/// so we check things like variant fields too.
fn check_sane_privacy(&self, item: &hir::Item) {
let check_inherited = |sp, vis, note: &str| {
if vis != hir::Inherited {
let mut err = struct_span_err!(self.tcx.sess, sp, E0449,
"unnecessary visibility qualifier");
if !note.is_empty() {
err.span_note(sp, note);
}
err.emit();
}
};
match item.node {
hir::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
check_inherited(item.span, item.vis,
"visibility qualifiers have no effect on trait impls");
for impl_item in impl_items {
check_inherited(impl_item.span, impl_item.vis,
"visibility qualifiers have no effect on trait impl items");
}
}
hir::ItemImpl(_, _, _, None, _, _) => {
check_inherited(item.span, item.vis,
"place qualifiers on individual methods instead");
}
hir::ItemDefaultImpl(..) => {
check_inherited(item.span, item.vis,
"visibility qualifiers have no effect on trait impls");
}
hir::ItemForeignMod(..) => {
check_inherited(item.span, item.vis,
"place qualifiers on individual functions instead");
}
hir::ItemEnum(ref def, _) => {
for variant in &def.variants {
for field in variant.node.data.fields() {
check_inherited(field.span, field.vis,
"visibility qualifiers have no effect on variant fields");
}
}
}
hir::ItemStruct(..) | hir::ItemTrait(..) |
hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
hir::ItemMod(..) | hir::ItemExternCrate(..) |
hir::ItemUse(..) | hir::ItemTy(..) => {}
}
}
}