1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_privacy"]
14 #![unstable(feature = "rustc_private")]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url
= "http://www.rust-lang.org/favicon.ico",
20 html_root_url
= "http://doc.rust-lang.org/nightly/")]
22 #![feature(rustc_diagnostic_macros)]
23 #![feature(rustc_private)]
24 #![feature(staged_api)]
26 #[macro_use] extern crate log;
27 #[macro_use] extern crate syntax;
31 use self::PrivacyResult
::*;
32 use self::FieldName
::*;
34 use std
::mem
::replace
;
36 use rustc
::metadata
::csearch
;
37 use rustc
::middle
::def
;
38 use rustc
::middle
::privacy
::ImportUse
::*;
39 use rustc
::middle
::privacy
::LastPrivate
::*;
40 use rustc
::middle
::privacy
::PrivateDep
::*;
41 use rustc
::middle
::privacy
::{ExternalExports, ExportedItems, PublicItems}
;
42 use rustc
::middle
::ty
::{MethodTypeParam, MethodStatic}
;
43 use rustc
::middle
::ty
::{MethodCall, MethodMap, MethodOrigin, MethodParam}
;
44 use rustc
::middle
::ty
::{MethodStaticClosure, MethodObject}
;
45 use rustc
::middle
::ty
::MethodTraitObject
;
46 use rustc
::middle
::ty
::{self, Ty}
;
47 use rustc
::util
::nodemap
::{NodeMap, NodeSet}
;
49 use syntax
::{ast, ast_map}
;
50 use syntax
::ast_util
::{is_local, local_def}
;
51 use syntax
::codemap
::Span
;
52 use syntax
::parse
::token
;
53 use syntax
::visit
::{self, Visitor}
;
55 type Context
<'a
, 'tcx
> = (&'a MethodMap
<'tcx
>, &'a def
::ExportMap
);
57 /// Result of a checking operation - None => no errors were found. Some => an
58 /// error and contains the span and message for reporting that error and
59 /// optionally the same for a note about the error.
60 type CheckResult
= Option
<(Span
, String
, Option
<(Span
, String
)>)>;
62 ////////////////////////////////////////////////////////////////////////////////
63 /// The parent visitor, used to determine what's the parent of what (node-wise)
64 ////////////////////////////////////////////////////////////////////////////////
66 struct ParentVisitor
{
67 parents
: NodeMap
<ast
::NodeId
>,
68 curparent
: ast
::NodeId
,
71 impl<'v
> Visitor
<'v
> for ParentVisitor
{
72 fn visit_item(&mut self, item
: &ast
::Item
) {
73 self.parents
.insert(item
.id
, self.curparent
);
75 let prev
= self.curparent
;
77 ast
::ItemMod(..) => { self.curparent = item.id; }
78 // Enum variants are parented to the enum definition itself because
79 // they inherit privacy
80 ast
::ItemEnum(ref def
, _
) => {
81 for variant
in &def
.variants
{
82 // The parent is considered the enclosing enum because the
83 // enum will dictate the privacy visibility of this variant
85 self.parents
.insert(variant
.node
.id
, item
.id
);
89 // Trait methods are always considered "public", but if the trait is
90 // private then we need some private item in the chain from the
91 // method to the root. In this case, if the trait is private, then
92 // parent all the methods to the trait to indicate that they're
94 ast
::ItemTrait(_
, _
, _
, ref trait_items
) if item
.vis
!= ast
::Public
=> {
95 for trait_item
in trait_items
{
96 self.parents
.insert(trait_item
.id
, item
.id
);
102 visit
::walk_item(self, item
);
103 self.curparent
= prev
;
106 fn visit_foreign_item(&mut self, a
: &ast
::ForeignItem
) {
107 self.parents
.insert(a
.id
, self.curparent
);
108 visit
::walk_foreign_item(self, a
);
111 fn visit_fn(&mut self, a
: visit
::FnKind
<'v
>, b
: &'v ast
::FnDecl
,
112 c
: &'v ast
::Block
, d
: Span
, id
: ast
::NodeId
) {
113 // We already took care of some trait methods above, otherwise things
114 // like impl methods and pub trait methods are parented to the
115 // containing module, not the containing trait.
116 if !self.parents
.contains_key(&id
) {
117 self.parents
.insert(id
, self.curparent
);
119 visit
::walk_fn(self, a
, b
, c
, d
);
122 fn visit_struct_def(&mut self, s
: &ast
::StructDef
, _
: ast
::Ident
,
123 _
: &'v ast
::Generics
, n
: ast
::NodeId
) {
124 // Struct constructors are parented to their struct definitions because
125 // they essentially are the struct definitions.
127 Some(id
) => { self.parents.insert(id, n); }
131 // While we have the id of the struct definition, go ahead and parent
133 for field
in &s
.fields
{
134 self.parents
.insert(field
.node
.id
, self.curparent
);
136 visit
::walk_struct_def(self, s
)
140 ////////////////////////////////////////////////////////////////////////////////
141 /// The embargo visitor, used to determine the exports of the ast
142 ////////////////////////////////////////////////////////////////////////////////
144 struct EmbargoVisitor
<'a
, 'tcx
: 'a
> {
145 tcx
: &'a ty
::ctxt
<'tcx
>,
146 export_map
: &'a def
::ExportMap
,
148 // This flag is an indicator of whether the previous item in the
149 // hierarchical chain was exported or not. This is the indicator of whether
150 // children should be exported as well. Note that this can flip from false
151 // to true if a reexported module is entered (or an action similar).
154 // This is a list of all exported items in the AST. An exported item is any
155 // function/method/item which is usable by external crates. This essentially
156 // means that the result is "public all the way down", but the "path down"
157 // may jump across private boundaries through reexport statements.
158 exported_items
: ExportedItems
,
160 // This sets contains all the destination nodes which are publicly
161 // re-exported. This is *not* a set of all reexported nodes, only a set of
162 // all nodes which are reexported *and* reachable from external crates. This
163 // means that the destination of the reexport is exported, and hence the
164 // destination must also be exported.
167 // These two fields are closely related to one another in that they are only
168 // used for generation of the 'PublicItems' set, not for privacy checking at
170 public_items
: PublicItems
,
174 impl<'a
, 'tcx
> EmbargoVisitor
<'a
, 'tcx
> {
175 // There are checks inside of privacy which depend on knowing whether a
176 // trait should be exported or not. The two current consumers of this are:
178 // 1. Should default methods of a trait be exported?
179 // 2. Should the methods of an implementation of a trait be exported?
181 // The answer to both of these questions partly rely on whether the trait
182 // itself is exported or not. If the trait is somehow exported, then the
183 // answers to both questions must be yes. Right now this question involves
184 // more analysis than is currently done in rustc, so we conservatively
185 // answer "yes" so that all traits need to be exported.
186 fn exported_trait(&self, _id
: ast
::NodeId
) -> bool
{
191 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for EmbargoVisitor
<'a
, 'tcx
> {
192 fn visit_item(&mut self, item
: &ast
::Item
) {
193 let orig_all_pub
= self.prev_public
;
194 self.prev_public
= orig_all_pub
&& item
.vis
== ast
::Public
;
195 if self.prev_public
{
196 self.public_items
.insert(item
.id
);
199 let orig_all_exported
= self.prev_exported
;
201 // impls/extern blocks do not break the "public chain" because they
202 // cannot have visibility qualifiers on them anyway
203 ast
::ItemImpl(..) | ast
::ItemDefaultImpl(..) | ast
::ItemForeignMod(..) => {}
205 // Traits are a little special in that even if they themselves are
206 // not public they may still be exported.
207 ast
::ItemTrait(..) => {
208 self.prev_exported
= self.exported_trait(item
.id
);
211 // Private by default, hence we only retain the "public chain" if
212 // `pub` is explicitly listed.
215 (orig_all_exported
&& item
.vis
== ast
::Public
) ||
216 self.reexports
.contains(&item
.id
);
220 let public_first
= self.prev_exported
&&
221 self.exported_items
.insert(item
.id
);
224 // Enum variants inherit from their parent, so if the enum is
225 // public all variants are public unless they're explicitly priv
226 ast
::ItemEnum(ref def
, _
) if public_first
=> {
227 for variant
in &def
.variants
{
228 self.exported_items
.insert(variant
.node
.id
);
229 self.public_items
.insert(variant
.node
.id
);
233 // Implementations are a little tricky to determine what's exported
234 // out of them. Here's a few cases which are currently defined:
236 // * Impls for private types do not need to export their methods
237 // (either public or private methods)
239 // * Impls for public types only have public methods exported
241 // * Public trait impls for public types must have all methods
244 // * Private trait impls for public types can be ignored
246 // * Public trait impls for private types have their methods
247 // exported. I'm not entirely certain that this is the correct
248 // thing to do, but I have seen use cases of where this will cause
249 // undefined symbols at linkage time if this case is not handled.
251 // * Private trait impls for private types can be completely ignored
252 ast
::ItemImpl(_
, _
, _
, _
, ref ty
, ref impl_items
) => {
253 let public_ty
= match ty
.node
{
255 match self.tcx
.def_map
.borrow().get(&ty
.id
).unwrap().full_def() {
256 def
::DefPrimTy(..) => true,
258 let did
= def
.def_id();
260 self.exported_items
.contains(&did
.node
)
266 let tr
= ty
::impl_trait_ref(self.tcx
, local_def(item
.id
));
267 let public_trait
= tr
.clone().map_or(false, |tr
| {
268 !is_local(tr
.def_id
) ||
269 self.exported_items
.contains(&tr
.def_id
.node
)
272 if public_ty
|| public_trait
{
273 for impl_item
in impl_items
{
274 match impl_item
.node
{
275 ast
::MethodImplItem(ref sig
, _
) => {
276 let meth_public
= match sig
.explicit_self
.node
{
277 ast
::SelfStatic
=> public_ty
,
279 } && impl_item
.vis
== ast
::Public
;
280 if meth_public
|| tr
.is_some() {
281 self.exported_items
.insert(impl_item
.id
);
284 ast
::TypeImplItem(_
) |
285 ast
::MacImplItem(_
) => {}
291 // Default methods on traits are all public so long as the trait
293 ast
::ItemTrait(_
, _
, _
, ref trait_items
) if public_first
=> {
294 for trait_item
in trait_items
{
295 debug
!("trait item {}", trait_item
.id
);
296 self.exported_items
.insert(trait_item
.id
);
300 // Struct constructors are public if the struct is all public.
301 ast
::ItemStruct(ref def
, _
) if public_first
=> {
303 Some(id
) => { self.exported_items.insert(id); }
306 // fields can be public or private, so lets check
307 for field
in &def
.fields
{
308 let vis
= match field
.node
.kind
{
309 ast
::NamedField(_
, vis
) | ast
::UnnamedField(vis
) => vis
311 if vis
== ast
::Public
{
312 self.public_items
.insert(field
.node
.id
);
317 ast
::ItemTy(ref ty
, _
) if public_first
=> {
318 if let ast
::TyPath(..) = ty
.node
{
319 match self.tcx
.def_map
.borrow().get(&ty
.id
).unwrap().full_def() {
320 def
::DefPrimTy(..) | def
::DefTyParam(..) => {}
,
322 let did
= def
.def_id();
324 self.exported_items
.insert(did
.node
);
334 visit
::walk_item(self, item
);
336 self.prev_exported
= orig_all_exported
;
337 self.prev_public
= orig_all_pub
;
340 fn visit_foreign_item(&mut self, a
: &ast
::ForeignItem
) {
341 if (self.prev_exported
&& a
.vis
== ast
::Public
) || self.reexports
.contains(&a
.id
) {
342 self.exported_items
.insert(a
.id
);
346 fn visit_mod(&mut self, m
: &ast
::Mod
, _sp
: Span
, id
: ast
::NodeId
) {
347 // This code is here instead of in visit_item so that the
348 // crate module gets processed as well.
349 if self.prev_exported
{
350 assert
!(self.export_map
.contains_key(&id
), "wut {}", id
);
351 for export
in self.export_map
.get(&id
).unwrap() {
352 if is_local(export
.def_id
) {
353 self.reexports
.insert(export
.def_id
.node
);
357 visit
::walk_mod(self, m
)
361 ////////////////////////////////////////////////////////////////////////////////
362 /// The privacy visitor, where privacy checks take place (violations reported)
363 ////////////////////////////////////////////////////////////////////////////////
365 struct PrivacyVisitor
<'a
, 'tcx
: 'a
> {
366 tcx
: &'a ty
::ctxt
<'tcx
>,
367 curitem
: ast
::NodeId
,
369 parents
: NodeMap
<ast
::NodeId
>,
370 external_exports
: ExternalExports
,
376 DisallowedBy(ast
::NodeId
),
380 UnnamedField(usize), // index
381 // (Name, not Ident, because struct fields are not macro-hygienic)
382 NamedField(ast
::Name
),
385 impl<'a
, 'tcx
> PrivacyVisitor
<'a
, 'tcx
> {
386 // used when debugging
387 fn nodestr(&self, id
: ast
::NodeId
) -> String
{
388 self.tcx
.map
.node_to_string(id
).to_string()
391 // Determines whether the given definition is public from the point of view
392 // of the current item.
393 fn def_privacy(&self, did
: ast
::DefId
) -> PrivacyResult
{
395 if self.external_exports
.contains(&did
) {
396 debug
!("privacy - {:?} was externally exported", did
);
399 debug
!("privacy - is {:?} a public method", did
);
401 return match self.tcx
.impl_or_trait_items
.borrow().get(&did
) {
402 Some(&ty
::MethodTraitItem(ref meth
)) => {
403 debug
!("privacy - well at least it's a method: {:?}",
405 match meth
.container
{
406 ty
::TraitContainer(id
) => {
407 debug
!("privacy - recursing on trait {:?}", id
);
410 ty
::ImplContainer(id
) => {
411 match ty
::impl_trait_ref(self.tcx
, id
) {
413 debug
!("privacy - impl of trait {:?}", id
);
414 self.def_privacy(t
.def_id
)
417 debug
!("privacy - found a method {:?}",
419 if meth
.vis
== ast
::Public
{
429 Some(&ty
::TypeTraitItem(ref typedef
)) => {
430 match typedef
.container
{
431 ty
::TraitContainer(id
) => {
432 debug
!("privacy - recursing on trait {:?}", id
);
435 ty
::ImplContainer(id
) => {
436 match ty
::impl_trait_ref(self.tcx
, id
) {
438 debug
!("privacy - impl of trait {:?}", id
);
439 self.def_privacy(t
.def_id
)
442 debug
!("privacy - found a typedef {:?}",
444 if typedef
.vis
== ast
::Public
{
455 debug
!("privacy - nope, not even a method");
461 debug
!("privacy - local {} not public all the way down",
462 self.tcx
.map
.node_to_string(did
.node
));
463 // return quickly for things in the same module
464 if self.parents
.get(&did
.node
) == self.parents
.get(&self.curitem
) {
465 debug
!("privacy - same parent, we're done here");
469 // We now know that there is at least one private member between the
470 // destination and the root.
471 let mut closest_private_id
= did
.node
;
473 debug
!("privacy - examining {}", self.nodestr(closest_private_id
));
474 let vis
= match self.tcx
.map
.find(closest_private_id
) {
475 // If this item is a method, then we know for sure that it's an
476 // actual method and not a static method. The reason for this is
477 // that these cases are only hit in the ExprMethodCall
478 // expression, and ExprCall will have its path checked later
479 // (the path of the trait/impl) if it's a static method.
481 // With this information, then we can completely ignore all
482 // trait methods. The privacy violation would be if the trait
483 // couldn't get imported, not if the method couldn't be used
484 // (all trait methods are public).
486 // However, if this is an impl method, then we dictate this
487 // decision solely based on the privacy of the method
489 // FIXME(#10573) is this the right behavior? Why not consider
490 // where the method was defined?
491 Some(ast_map
::NodeImplItem(ii
)) => {
493 ast
::MethodImplItem(..) => {
494 let imp
= self.tcx
.map
495 .get_parent_did(closest_private_id
);
496 match ty
::impl_trait_ref(self.tcx
, imp
) {
497 Some(..) => return Allowable
,
498 _
if ii
.vis
== ast
::Public
=> {
504 ast
::TypeImplItem(_
) |
505 ast
::MacImplItem(_
) => return Allowable
,
508 Some(ast_map
::NodeTraitItem(_
)) => {
512 // This is not a method call, extract the visibility as one
513 // would normally look at it
514 Some(ast_map
::NodeItem(it
)) => it
.vis
,
515 Some(ast_map
::NodeForeignItem(_
)) => {
516 self.tcx
.map
.get_foreign_vis(closest_private_id
)
518 Some(ast_map
::NodeVariant(..)) => {
519 ast
::Public
// need to move up a level (to the enum)
523 if vis
!= ast
::Public { break }
524 // if we've reached the root, then everything was allowable and this
526 if closest_private_id
== ast
::CRATE_NODE_ID { return Allowable }
527 closest_private_id
= *self.parents
.get(&closest_private_id
).unwrap();
529 // If we reached the top, then we were public all the way down and
530 // we can allow this access.
531 if closest_private_id
== ast
::DUMMY_NODE_ID { return Allowable }
533 debug
!("privacy - closest priv {}", self.nodestr(closest_private_id
));
534 if self.private_accessible(closest_private_id
) {
537 DisallowedBy(closest_private_id
)
541 /// For a local private node in the AST, this function will determine
542 /// whether the node is accessible by the current module that iteration is
544 fn private_accessible(&self, id
: ast
::NodeId
) -> bool
{
545 let parent
= *self.parents
.get(&id
).unwrap();
546 debug
!("privacy - accessible parent {}", self.nodestr(parent
));
548 // After finding `did`'s closest private member, we roll ourselves back
549 // to see if this private member's parent is anywhere in our ancestry.
550 // By the privacy rules, we can access all of our ancestor's private
551 // members, so that's why we test the parent, and not the did itself.
552 let mut cur
= self.curitem
;
554 debug
!("privacy - questioning {}, {}", self.nodestr(cur
), cur
);
556 // If the relevant parent is in our history, then we're allowed
557 // to look inside any of our ancestor's immediate private items,
558 // so this access is valid.
559 x
if x
== parent
=> return true,
561 // If we've reached the root, then we couldn't access this item
562 // in the first place
563 ast
::DUMMY_NODE_ID
=> return false,
569 cur
= *self.parents
.get(&cur
).unwrap();
573 fn report_error(&self, result
: CheckResult
) -> bool
{
576 Some((span
, msg
, note
)) => {
577 self.tcx
.sess
.span_err(span
, &msg
[..]);
579 Some((span
, msg
)) => {
580 self.tcx
.sess
.span_note(span
, &msg
[..])
589 /// Guarantee that a particular definition is public. Returns a CheckResult
590 /// which contains any errors found. These can be reported using `report_error`.
591 /// If the result is `None`, no errors were found.
592 fn ensure_public(&self, span
: Span
, to_check
: ast
::DefId
,
593 source_did
: Option
<ast
::DefId
>, msg
: &str) -> CheckResult
{
594 let id
= match self.def_privacy(to_check
) {
595 ExternallyDenied
=> {
596 return Some((span
, format
!("{} is private", msg
), None
))
598 Allowable
=> return None
,
599 DisallowedBy(id
) => id
,
602 // If we're disallowed by a particular id, then we attempt to give a
603 // nice error message to say why it was disallowed. It was either
604 // because the item itself is private or because its parent is private
605 // and its parent isn't in our ancestry.
606 let (err_span
, err_msg
) = if id
== source_did
.unwrap_or(to_check
).node
{
607 return Some((span
, format
!("{} is private", msg
), None
));
609 (span
, format
!("{} is inaccessible", msg
))
611 let item
= match self.tcx
.map
.find(id
) {
612 Some(ast_map
::NodeItem(item
)) => {
614 // If an impl disallowed this item, then this is resolve's
615 // way of saying that a struct/enum's static method was
616 // invoked, and the struct/enum itself is private. Crawl
617 // back up the chains to find the relevant struct/enum that
619 ast
::ItemImpl(_
, _
, _
, _
, ref ty
, _
) => {
621 ast
::TyPath(..) => {}
622 _
=> return Some((err_span
, err_msg
, None
)),
624 let def
= self.tcx
.def_map
.borrow().get(&ty
.id
).unwrap().full_def();
625 let did
= def
.def_id();
626 assert
!(is_local(did
));
627 match self.tcx
.map
.get(did
.node
) {
628 ast_map
::NodeItem(item
) => item
,
629 _
=> self.tcx
.sess
.span_bug(item
.span
,
630 "path is not an item")
636 Some(..) | None
=> return Some((err_span
, err_msg
, None
)),
638 let desc
= match item
.node
{
639 ast
::ItemMod(..) => "module",
640 ast
::ItemTrait(..) => "trait",
641 ast
::ItemStruct(..) => "struct",
642 ast
::ItemEnum(..) => "enum",
643 _
=> return Some((err_span
, err_msg
, None
))
645 let msg
= format
!("{} `{}` is private", desc
,
646 token
::get_ident(item
.ident
));
647 Some((err_span
, err_msg
, Some((span
, msg
))))
650 // Checks that a field is in scope.
651 fn check_field(&mut self,
655 let fields
= ty
::lookup_struct_fields(self.tcx
, id
);
656 let field
= match name
{
657 NamedField(f_name
) => {
658 debug
!("privacy - check named field {} in struct {:?}", f_name
, id
);
659 fields
.iter().find(|f
| f
.name
== f_name
).unwrap()
661 UnnamedField(idx
) => &fields
[idx
]
663 if field
.vis
== ast
::Public
||
664 (is_local(field
.id
) && self.private_accessible(field
.id
.node
)) {
668 let struct_type
= ty
::lookup_item_type(self.tcx
, id
).ty
;
669 let struct_desc
= match struct_type
.sty
{
670 ty
::ty_struct(_
, _
) =>
671 format
!("struct `{}`", ty
::item_path_str(self.tcx
, id
)),
672 // struct variant fields have inherited visibility
673 ty
::ty_enum(..) => return,
674 _
=> self.tcx
.sess
.span_bug(span
, "can't find struct for field")
676 let msg
= match name
{
677 NamedField(name
) => format
!("field `{}` of {} is private",
678 token
::get_name(name
), struct_desc
),
679 UnnamedField(idx
) => format
!("field #{} of {} is private",
680 idx
+ 1, struct_desc
),
682 self.tcx
.sess
.span_err(span
, &msg
[..]);
685 // Given the ID of a method, checks to ensure it's in scope.
686 fn check_static_method(&mut self,
688 method_id
: ast
::DefId
,
690 // If the method is a default method, we need to use the def_id of
691 // the default implementation.
692 let method_id
= match ty
::impl_or_trait_item(self.tcx
, method_id
) {
693 ty
::MethodTraitItem(method_type
) => {
694 method_type
.provided_source
.unwrap_or(method_id
)
696 ty
::TypeTraitItem(_
) => method_id
,
699 let string
= token
::get_name(name
);
700 self.report_error(self.ensure_public(span
,
703 &format
!("method `{}`",
707 // Checks that a path is in scope.
708 fn check_path(&mut self, span
: Span
, path_id
: ast
::NodeId
, last
: ast
::Name
) {
709 debug
!("privacy - path {}", self.nodestr(path_id
));
710 let path_res
= *self.tcx
.def_map
.borrow().get(&path_id
).unwrap();
711 let ck
= |tyname
: &str| {
712 let ck_public
= |def
: ast
::DefId
| {
713 debug
!("privacy - ck_public {:?}", def
);
714 let name
= token
::get_name(last
);
715 let origdid
= path_res
.def_id();
716 self.ensure_public(span
,
719 &format
!("{} `{}`", tyname
, name
))
722 match path_res
.last_private
{
723 LastMod(AllPublic
) => {}
,
724 LastMod(DependsOn(def
)) => {
725 self.report_error(ck_public(def
));
727 LastImport
{ value_priv
,
728 value_used
: check_value
,
730 type_used
: check_type
} => {
731 // This dance with found_error is because we don't want to
732 // report a privacy error twice for the same directive.
733 let found_error
= match (type_priv
, check_type
) {
734 (Some(DependsOn(def
)), Used
) => {
735 !self.report_error(ck_public(def
))
740 match (value_priv
, check_value
) {
741 (Some(DependsOn(def
)), Used
) => {
742 self.report_error(ck_public(def
));
747 // If an import is not used in either namespace, we still
748 // want to check that it could be legal. Therefore we check
749 // in both namespaces and only report an error if both would
750 // be illegal. We only report one error, even if it is
751 // illegal to import from both namespaces.
752 match (value_priv
, check_value
, type_priv
, check_type
) {
753 (Some(p
), Unused
, None
, _
) |
754 (None
, _
, Some(p
), Unused
) => {
757 DependsOn(def
) => ck_public(def
),
760 self.report_error(p
);
763 (Some(v
), Unused
, Some(t
), Unused
) => {
766 DependsOn(def
) => ck_public(def
),
770 DependsOn(def
) => ck_public(def
),
772 if let (Some(_
), Some(t
)) = (v
, t
) {
773 self.report_error(Some(t
));
781 // FIXME(#12334) Imports can refer to definitions in both the type and
782 // value namespaces. The privacy information is aware of this, but the
783 // def map is not. Therefore the names we work out below will not always
784 // be accurate and we can get slightly wonky error messages (but type
785 // checking is always correct).
786 match path_res
.full_def() {
787 def
::DefFn(..) => ck("function"),
788 def
::DefStatic(..) => ck("static"),
789 def
::DefConst(..) => ck("const"),
790 def
::DefVariant(..) => ck("variant"),
791 def
::DefTy(_
, false) => ck("type"),
792 def
::DefTy(_
, true) => ck("enum"),
793 def
::DefTrait(..) => ck("trait"),
794 def
::DefStruct(..) => ck("struct"),
795 def
::DefMethod(..) => ck("method"),
796 def
::DefMod(..) => ck("module"),
801 // Checks that a method is in scope.
802 fn check_method(&mut self, span
: Span
, origin
: &MethodOrigin
,
805 MethodStatic(method_id
) => {
806 self.check_static_method(span
, method_id
, name
)
808 MethodStaticClosure(_
) => {}
809 // Trait methods are always all public. The only controlling factor
810 // is whether the trait itself is accessible or not.
811 MethodTypeParam(MethodParam { ref trait_ref, .. }
) |
812 MethodTraitObject(MethodObject { ref trait_ref, .. }
) => {
813 self.report_error(self.ensure_public(span
, trait_ref
.def_id
,
814 None
, "source trait"));
820 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for PrivacyVisitor
<'a
, 'tcx
> {
821 fn visit_item(&mut self, item
: &ast
::Item
) {
822 if let ast
::ItemUse(ref vpath
) = item
.node
{
823 if let ast
::ViewPathList(ref prefix
, ref list
) = vpath
.node
{
826 ast
::PathListIdent { id, name }
=> {
827 debug
!("privacy - ident item {}", id
);
828 self.check_path(pid
.span
, id
, name
.name
);
830 ast
::PathListMod { id }
=> {
831 debug
!("privacy - mod item {}", id
);
832 let name
= prefix
.segments
.last().unwrap().identifier
.name
;
833 self.check_path(pid
.span
, id
, name
);
839 let orig_curitem
= replace(&mut self.curitem
, item
.id
);
840 visit
::walk_item(self, item
);
841 self.curitem
= orig_curitem
;
844 fn visit_expr(&mut self, expr
: &ast
::Expr
) {
846 ast
::ExprField(ref base
, ident
) => {
847 if let ty
::ty_struct(id
, _
) = ty
::expr_ty_adjusted(self.tcx
, &**base
).sty
{
848 self.check_field(expr
.span
, id
, NamedField(ident
.node
.name
));
851 ast
::ExprTupField(ref base
, idx
) => {
852 if let ty
::ty_struct(id
, _
) = ty
::expr_ty_adjusted(self.tcx
, &**base
).sty
{
853 self.check_field(expr
.span
, id
, UnnamedField(idx
.node
));
856 ast
::ExprMethodCall(ident
, _
, _
) => {
857 let method_call
= MethodCall
::expr(expr
.id
);
858 match self.tcx
.method_map
.borrow().get(&method_call
) {
860 self.tcx
.sess
.span_bug(expr
.span
,
861 "method call not in \
865 debug
!("(privacy checking) checking impl method");
866 self.check_method(expr
.span
, &method
.origin
, ident
.node
.name
);
870 ast
::ExprStruct(_
, ref fields
, _
) => {
871 match ty
::expr_ty(self.tcx
, expr
).sty
{
872 ty
::ty_struct(ctor_id
, _
) => {
873 // RFC 736: ensure all unmentioned fields are visible.
874 // Rather than computing the set of unmentioned fields
875 // (i.e. `all_fields - fields`), just check them all.
876 let all_fields
= ty
::lookup_struct_fields(self.tcx
, ctor_id
);
877 for field
in all_fields
{
878 self.check_field(expr
.span
, ctor_id
,
879 NamedField(field
.name
));
882 ty
::ty_enum(_
, _
) => {
883 match self.tcx
.def_map
.borrow().get(&expr
.id
).unwrap().full_def() {
884 def
::DefVariant(_
, variant_id
, _
) => {
885 for field
in fields
{
886 self.check_field(expr
.span
, variant_id
,
887 NamedField(field
.ident
.node
.name
));
890 _
=> self.tcx
.sess
.span_bug(expr
.span
,
897 _
=> self.tcx
.sess
.span_bug(expr
.span
, "struct expr \
902 ast
::ExprPath(..) => {
903 let guard
= |did
: ast
::DefId
| {
904 let fields
= ty
::lookup_struct_fields(self.tcx
, did
);
905 let any_priv
= fields
.iter().any(|f
| {
906 f
.vis
!= ast
::Public
&& (
908 !self.private_accessible(f
.id
.node
))
911 self.tcx
.sess
.span_err(expr
.span
,
912 "cannot invoke tuple struct constructor \
913 with private fields");
916 match self.tcx
.def_map
.borrow().get(&expr
.id
).map(|d
| d
.full_def()) {
917 Some(def
::DefStruct(did
)) => {
918 guard(if is_local(did
) {
919 local_def(self.tcx
.map
.get_parent(did
.node
))
921 // "tuple structs" with zero fields (such as
922 // `pub struct Foo;`) don't have a ctor_id, hence
923 // the unwrap_or to the same struct id.
925 csearch
::get_tuple_struct_definition_if_ctor(
926 &self.tcx
.sess
.cstore
, did
);
927 maybe_did
.unwrap_or(did
)
936 visit
::walk_expr(self, expr
);
939 fn visit_pat(&mut self, pattern
: &ast
::Pat
) {
940 // Foreign functions do not have their patterns mapped in the def_map,
941 // and there's nothing really relevant there anyway, so don't bother
942 // checking privacy. If you can name the type then you can pass it to an
943 // external C function anyway.
944 if self.in_foreign { return }
947 ast
::PatStruct(_
, ref fields
, _
) => {
948 match ty
::pat_ty(self.tcx
, pattern
).sty
{
949 ty
::ty_struct(id
, _
) => {
950 for field
in fields
{
951 self.check_field(pattern
.span
, id
,
952 NamedField(field
.node
.ident
.name
));
955 ty
::ty_enum(_
, _
) => {
956 match self.tcx
.def_map
.borrow().get(&pattern
.id
).map(|d
| d
.full_def()) {
957 Some(def
::DefVariant(_
, variant_id
, _
)) => {
958 for field
in fields
{
959 self.check_field(pattern
.span
, variant_id
,
960 NamedField(field
.node
.ident
.name
));
963 _
=> self.tcx
.sess
.span_bug(pattern
.span
,
970 _
=> self.tcx
.sess
.span_bug(pattern
.span
,
971 "struct pattern didn't have \
976 // Patterns which bind no fields are allowable (the path is check
978 ast
::PatEnum(_
, Some(ref fields
)) => {
979 match ty
::pat_ty(self.tcx
, pattern
).sty
{
980 ty
::ty_struct(id
, _
) => {
981 for (i
, field
) in fields
.iter().enumerate() {
982 if let ast
::PatWild(..) = field
.node
{
985 self.check_field(field
.span
, id
, UnnamedField(i
));
989 // enum fields have no privacy at this time
998 visit
::walk_pat(self, pattern
);
1001 fn visit_foreign_item(&mut self, fi
: &ast
::ForeignItem
) {
1002 self.in_foreign
= true;
1003 visit
::walk_foreign_item(self, fi
);
1004 self.in_foreign
= false;
1007 fn visit_path(&mut self, path
: &ast
::Path
, id
: ast
::NodeId
) {
1008 self.check_path(path
.span
, id
, path
.segments
.last().unwrap().identifier
.name
);
1009 visit
::walk_path(self, path
);
1013 ////////////////////////////////////////////////////////////////////////////////
1014 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1015 ////////////////////////////////////////////////////////////////////////////////
1017 struct SanePrivacyVisitor
<'a
, 'tcx
: 'a
> {
1018 tcx
: &'a ty
::ctxt
<'tcx
>,
1022 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for SanePrivacyVisitor
<'a
, 'tcx
> {
1023 fn visit_item(&mut self, item
: &ast
::Item
) {
1025 self.check_all_inherited(item
);
1027 self.check_sane_privacy(item
);
1030 let in_fn
= self.in_fn
;
1031 let orig_in_fn
= replace(&mut self.in_fn
, match item
.node
{
1032 ast
::ItemMod(..) => false, // modules turn privacy back on
1033 _
=> in_fn
, // otherwise we inherit
1035 visit
::walk_item(self, item
);
1036 self.in_fn
= orig_in_fn
;
1039 fn visit_fn(&mut self, fk
: visit
::FnKind
<'v
>, fd
: &'v ast
::FnDecl
,
1040 b
: &'v ast
::Block
, s
: Span
, _
: ast
::NodeId
) {
1041 // This catches both functions and methods
1042 let orig_in_fn
= replace(&mut self.in_fn
, true);
1043 visit
::walk_fn(self, fk
, fd
, b
, s
);
1044 self.in_fn
= orig_in_fn
;
1048 impl<'a
, 'tcx
> SanePrivacyVisitor
<'a
, 'tcx
> {
1049 /// Validates all of the visibility qualifiers placed on the item given. This
1050 /// ensures that there are no extraneous qualifiers that don't actually do
1051 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1052 /// later on down the road...
1053 fn check_sane_privacy(&self, item
: &ast
::Item
) {
1055 let check_inherited
= |sp
: Span
, vis
: ast
::Visibility
, note
: &str| {
1056 if vis
!= ast
::Inherited
{
1057 tcx
.sess
.span_err(sp
, "unnecessary visibility qualifier");
1058 if !note
.is_empty() {
1059 tcx
.sess
.span_note(sp
, note
);
1064 // implementations of traits don't need visibility qualifiers because
1065 // that's controlled by having the trait in scope.
1066 ast
::ItemImpl(_
, _
, _
, Some(..), _
, ref impl_items
) => {
1067 check_inherited(item
.span
, item
.vis
,
1068 "visibility qualifiers have no effect on trait \
1070 for impl_item
in impl_items
{
1071 check_inherited(impl_item
.span
, impl_item
.vis
, "");
1075 ast
::ItemImpl(..) => {
1076 check_inherited(item
.span
, item
.vis
,
1077 "place qualifiers on individual methods instead");
1079 ast
::ItemForeignMod(..) => {
1080 check_inherited(item
.span
, item
.vis
,
1081 "place qualifiers on individual functions \
1085 ast
::ItemEnum(ref def
, _
) => {
1086 for v
in &def
.variants
{
1089 if item
.vis
== ast
::Public
{
1090 tcx
.sess
.span_err(v
.span
, "unnecessary `pub` \
1094 ast
::Inherited
=> {}
1099 ast
::ItemTrait(..) | ast
::ItemDefaultImpl(..) |
1100 ast
::ItemConst(..) | ast
::ItemStatic(..) | ast
::ItemStruct(..) |
1101 ast
::ItemFn(..) | ast
::ItemMod(..) | ast
::ItemTy(..) |
1102 ast
::ItemExternCrate(_
) | ast
::ItemUse(_
) | ast
::ItemMac(..) => {}
1106 /// When inside of something like a function or a method, visibility has no
1107 /// control over anything so this forbids any mention of any visibility
1108 fn check_all_inherited(&self, item
: &ast
::Item
) {
1110 fn check_inherited(tcx
: &ty
::ctxt
, sp
: Span
, vis
: ast
::Visibility
) {
1111 if vis
!= ast
::Inherited
{
1112 tcx
.sess
.span_err(sp
, "visibility has no effect inside functions");
1115 let check_struct
= |def
: &ast
::StructDef
| {
1116 for f
in &def
.fields
{
1118 ast
::NamedField(_
, p
) => check_inherited(tcx
, f
.span
, p
),
1119 ast
::UnnamedField(..) => {}
1123 check_inherited(tcx
, item
.span
, item
.vis
);
1125 ast
::ItemImpl(_
, _
, _
, _
, _
, ref impl_items
) => {
1126 for impl_item
in impl_items
{
1127 match impl_item
.node
{
1128 ast
::MethodImplItem(..) => {
1129 check_inherited(tcx
, impl_item
.span
, impl_item
.vis
);
1131 ast
::TypeImplItem(_
) |
1132 ast
::MacImplItem(_
) => {}
1136 ast
::ItemForeignMod(ref fm
) => {
1137 for i
in &fm
.items
{
1138 check_inherited(tcx
, i
.span
, i
.vis
);
1141 ast
::ItemEnum(ref def
, _
) => {
1142 for v
in &def
.variants
{
1143 check_inherited(tcx
, v
.span
, v
.node
.vis
);
1147 ast
::ItemStruct(ref def
, _
) => check_struct(&**def
),
1149 ast
::ItemExternCrate(_
) | ast
::ItemUse(_
) |
1150 ast
::ItemTrait(..) | ast
::ItemDefaultImpl(..) |
1151 ast
::ItemStatic(..) | ast
::ItemConst(..) |
1152 ast
::ItemFn(..) | ast
::ItemMod(..) | ast
::ItemTy(..) |
1153 ast
::ItemMac(..) => {}
1158 struct VisiblePrivateTypesVisitor
<'a
, 'tcx
: 'a
> {
1159 tcx
: &'a ty
::ctxt
<'tcx
>,
1160 exported_items
: &'a ExportedItems
,
1161 public_items
: &'a PublicItems
,
1165 struct CheckTypeForPrivatenessVisitor
<'a
, 'b
: 'a
, 'tcx
: 'b
> {
1166 inner
: &'a VisiblePrivateTypesVisitor
<'b
, 'tcx
>,
1167 /// whether the type refers to private types.
1168 contains_private
: bool
,
1169 /// whether we've recurred at all (i.e. if we're pointing at the
1170 /// first type on which visit_ty was called).
1171 at_outer_type
: bool
,
1172 // whether that first type is a public path.
1173 outer_type_is_public_path
: bool
,
1176 impl<'a
, 'tcx
> VisiblePrivateTypesVisitor
<'a
, 'tcx
> {
1177 fn path_is_private_type(&self, path_id
: ast
::NodeId
) -> bool
{
1178 let did
= match self.tcx
.def_map
.borrow().get(&path_id
).map(|d
| d
.full_def()) {
1179 // `int` etc. (None doesn't seem to occur.)
1180 None
| Some(def
::DefPrimTy(..)) => return false,
1181 Some(def
) => def
.def_id(),
1183 // A path can only be private if:
1184 // it's in this crate...
1189 // .. and it corresponds to a private type in the AST (this returns
1190 // None for type parameters)
1191 match self.tcx
.map
.find(did
.node
) {
1192 Some(ast_map
::NodeItem(ref item
)) => item
.vis
!= ast
::Public
,
1193 Some(_
) | None
=> false,
1197 fn trait_is_public(&self, trait_id
: ast
::NodeId
) -> bool
{
1198 // FIXME: this would preferably be using `exported_items`, but all
1199 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1200 self.public_items
.contains(&trait_id
)
1203 fn check_ty_param_bound(&self,
1204 ty_param_bound
: &ast
::TyParamBound
) {
1205 if let ast
::TraitTyParamBound(ref trait_ref
, _
) = *ty_param_bound
{
1206 if !self.tcx
.sess
.features
.borrow().visible_private_types
&&
1207 self.path_is_private_type(trait_ref
.trait_ref
.ref_id
) {
1208 let span
= trait_ref
.trait_ref
.path
.span
;
1209 self.tcx
.sess
.span_err(span
, "private trait in exported type \
1215 fn item_is_public(&self, id
: &ast
::NodeId
, vis
: ast
::Visibility
) -> bool
{
1216 self.exported_items
.contains(id
) || vis
== ast
::Public
1220 impl<'a
, 'b
, 'tcx
, 'v
> Visitor
<'v
> for CheckTypeForPrivatenessVisitor
<'a
, 'b
, 'tcx
> {
1221 fn visit_ty(&mut self, ty
: &ast
::Ty
) {
1222 if let ast
::TyPath(..) = ty
.node
{
1223 if self.inner
.path_is_private_type(ty
.id
) {
1224 self.contains_private
= true;
1225 // found what we're looking for so let's stop
1228 } else if self.at_outer_type
{
1229 self.outer_type_is_public_path
= true;
1232 self.at_outer_type
= false;
1233 visit
::walk_ty(self, ty
)
1236 // don't want to recurse into [, .. expr]
1237 fn visit_expr(&mut self, _
: &ast
::Expr
) {}
1240 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for VisiblePrivateTypesVisitor
<'a
, 'tcx
> {
1241 fn visit_item(&mut self, item
: &ast
::Item
) {
1243 // contents of a private mod can be reexported, so we need
1244 // to check internals.
1245 ast
::ItemMod(_
) => {}
1247 // An `extern {}` doesn't introduce a new privacy
1248 // namespace (the contents have their own privacies).
1249 ast
::ItemForeignMod(_
) => {}
1251 ast
::ItemTrait(_
, _
, ref bounds
, _
) => {
1252 if !self.trait_is_public(item
.id
) {
1256 for bound
in &**bounds
{
1257 self.check_ty_param_bound(bound
)
1261 // impls need some special handling to try to offer useful
1262 // error messages without (too many) false positives
1263 // (i.e. we could just return here to not check them at
1264 // all, or some worse estimation of whether an impl is
1265 // publicly visible).
1266 ast
::ItemImpl(_
, _
, ref g
, ref trait_ref
, ref self_
, ref impl_items
) => {
1267 // `impl [... for] Private` is never visible.
1268 let self_contains_private
;
1269 // impl [... for] Public<...>, but not `impl [... for]
1270 // ~[Public]` or `(Public,)` etc.
1271 let self_is_public_path
;
1273 // check the properties of the Self type:
1275 let mut visitor
= CheckTypeForPrivatenessVisitor
{
1277 contains_private
: false,
1278 at_outer_type
: true,
1279 outer_type_is_public_path
: false,
1281 visitor
.visit_ty(&**self_
);
1282 self_contains_private
= visitor
.contains_private
;
1283 self_is_public_path
= visitor
.outer_type_is_public_path
;
1286 // miscellaneous info about the impl
1288 // `true` iff this is `impl Private for ...`.
1289 let not_private_trait
=
1290 trait_ref
.as_ref().map_or(true, // no trait counts as public trait
1292 let did
= ty
::trait_ref_to_def_id(self.tcx
, tr
);
1294 !is_local(did
) || self.trait_is_public(did
.node
)
1297 // `true` iff this is a trait impl or at least one method is public.
1299 // `impl Public { $( fn ...() {} )* }` is not visible.
1301 // This is required over just using the methods' privacy
1302 // directly because we might have `impl<T: Foo<Private>> ...`,
1303 // and we shouldn't warn about the generics if all the methods
1304 // are private (because `T` won't be visible externally).
1305 let trait_or_some_public_method
=
1306 trait_ref
.is_some() ||
1309 match impl_item
.node
{
1310 ast
::MethodImplItem(..) => {
1311 self.exported_items
.contains(&impl_item
.id
)
1313 ast
::TypeImplItem(_
) |
1314 ast
::MacImplItem(_
) => false,
1318 if !self_contains_private
&&
1319 not_private_trait
&&
1320 trait_or_some_public_method
{
1322 visit
::walk_generics(self, g
);
1326 for impl_item
in impl_items
{
1327 // This is where we choose whether to walk down
1328 // further into the impl to check its items. We
1329 // should only walk into public items so that we
1330 // don't erroneously report errors for private
1331 // types in private items.
1332 match impl_item
.node
{
1333 ast
::MethodImplItem(..)
1334 if self.item_is_public(&impl_item
.id
, impl_item
.vis
) =>
1336 visit
::walk_impl_item(self, impl_item
)
1338 ast
::TypeImplItem(..) => {
1339 visit
::walk_impl_item(self, impl_item
)
1346 // Any private types in a trait impl fall into three
1348 // 1. mentioned in the trait definition
1349 // 2. mentioned in the type params/generics
1350 // 3. mentioned in the associated types of the impl
1352 // Those in 1. can only occur if the trait is in
1353 // this crate and will've been warned about on the
1354 // trait definition (there's no need to warn twice
1355 // so we don't check the methods).
1357 // Those in 2. are warned via walk_generics and this
1359 visit
::walk_path(self, &tr
.path
);
1361 // Those in 3. are warned with this call.
1362 for impl_item
in impl_items
{
1363 match impl_item
.node
{
1364 ast
::TypeImplItem(ref ty
) => {
1367 ast
::MethodImplItem(..) |
1368 ast
::MacImplItem(_
) => {}
,
1373 } else if trait_ref
.is_none() && self_is_public_path
{
1374 // impl Public<Private> { ... }. Any public static
1375 // methods will be visible as `Public::foo`.
1376 let mut found_pub_static
= false;
1377 for impl_item
in impl_items
{
1378 match impl_item
.node
{
1379 ast
::MethodImplItem(ref sig
, _
) => {
1380 if sig
.explicit_self
.node
== ast
::SelfStatic
&&
1381 self.item_is_public(&impl_item
.id
, impl_item
.vis
) {
1382 found_pub_static
= true;
1383 visit
::walk_impl_item(self, impl_item
);
1386 ast
::TypeImplItem(_
) |
1387 ast
::MacImplItem(_
) => {}
1390 if found_pub_static
{
1391 visit
::walk_generics(self, g
)
1397 // `type ... = ...;` can contain private types, because
1398 // we're introducing a new name.
1399 ast
::ItemTy(..) => return,
1401 // not at all public, so we don't care
1402 _
if !self.item_is_public(&item
.id
, item
.vis
) => {
1409 // We've carefully constructed it so that if we're here, then
1410 // any `visit_ty`'s will be called on things that are in
1411 // public signatures, i.e. things that we're interested in for
1413 debug
!("VisiblePrivateTypesVisitor entering item {:?}", item
);
1414 visit
::walk_item(self, item
);
1417 fn visit_generics(&mut self, generics
: &ast
::Generics
) {
1418 for ty_param
in &*generics
.ty_params
{
1419 for bound
in &*ty_param
.bounds
{
1420 self.check_ty_param_bound(bound
)
1423 for predicate
in &generics
.where_clause
.predicates
{
1425 &ast
::WherePredicate
::BoundPredicate(ref bound_pred
) => {
1426 for bound
in &*bound_pred
.bounds
{
1427 self.check_ty_param_bound(bound
)
1430 &ast
::WherePredicate
::RegionPredicate(_
) => {}
1431 &ast
::WherePredicate
::EqPredicate(ref eq_pred
) => {
1432 self.visit_ty(&*eq_pred
.ty
);
1438 fn visit_foreign_item(&mut self, item
: &ast
::ForeignItem
) {
1439 if self.exported_items
.contains(&item
.id
) {
1440 visit
::walk_foreign_item(self, item
)
1444 fn visit_ty(&mut self, t
: &ast
::Ty
) {
1445 debug
!("VisiblePrivateTypesVisitor checking ty {:?}", t
);
1446 if let ast
::TyPath(_
, ref p
) = t
.node
{
1447 if !self.tcx
.sess
.features
.borrow().visible_private_types
&&
1448 self.path_is_private_type(t
.id
) {
1449 self.tcx
.sess
.span_err(p
.span
, "private type in exported type signature");
1452 visit
::walk_ty(self, t
)
1455 fn visit_variant(&mut self, v
: &ast
::Variant
, g
: &ast
::Generics
) {
1456 if self.exported_items
.contains(&v
.node
.id
) {
1457 self.in_variant
= true;
1458 visit
::walk_variant(self, v
, g
);
1459 self.in_variant
= false;
1463 fn visit_struct_field(&mut self, s
: &ast
::StructField
) {
1465 ast
::NamedField(_
, vis
) if vis
== ast
::Public
|| self.in_variant
=> {
1466 visit
::walk_struct_field(self, s
);
1473 // we don't need to introspect into these at all: an
1474 // expression/block context can't possibly contain exported things.
1475 // (Making them no-ops stops us from traversing the whole AST without
1476 // having to be super careful about our `walk_...` calls above.)
1477 fn visit_block(&mut self, _
: &ast
::Block
) {}
1478 fn visit_expr(&mut self, _
: &ast
::Expr
) {}
1481 pub fn check_crate(tcx
: &ty
::ctxt
,
1482 export_map
: &def
::ExportMap
,
1483 external_exports
: ExternalExports
)
1484 -> (ExportedItems
, PublicItems
) {
1485 let krate
= tcx
.map
.krate();
1487 // Figure out who everyone's parent is
1488 let mut visitor
= ParentVisitor
{
1490 curparent
: ast
::DUMMY_NODE_ID
,
1492 visit
::walk_crate(&mut visitor
, krate
);
1494 // Use the parent map to check the privacy of everything
1495 let mut visitor
= PrivacyVisitor
{
1496 curitem
: ast
::DUMMY_NODE_ID
,
1499 parents
: visitor
.parents
,
1500 external_exports
: external_exports
,
1502 visit
::walk_crate(&mut visitor
, krate
);
1504 // Sanity check to make sure that all privacy usage and controls are
1506 let mut visitor
= SanePrivacyVisitor
{
1510 visit
::walk_crate(&mut visitor
, krate
);
1512 tcx
.sess
.abort_if_errors();
1514 // Build up a set of all exported items in the AST. This is a set of all
1515 // items which are reachable from external crates based on visibility.
1516 let mut visitor
= EmbargoVisitor
{
1518 exported_items
: NodeSet(),
1519 public_items
: NodeSet(),
1520 reexports
: NodeSet(),
1521 export_map
: export_map
,
1522 prev_exported
: true,
1526 let before
= visitor
.exported_items
.len();
1527 visit
::walk_crate(&mut visitor
, krate
);
1528 if before
== visitor
.exported_items
.len() {
1533 let EmbargoVisitor { exported_items, public_items, .. }
= visitor
;
1536 let mut visitor
= VisiblePrivateTypesVisitor
{
1538 exported_items
: &exported_items
,
1539 public_items
: &public_items
,
1542 visit
::walk_crate(&mut visitor
, krate
);
1544 return (exported_items
, public_items
);