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_impl_item(&mut self, ii
: &'v ast
::ImplItem
) {
123 // visit_fn handles methods, but associated consts have to be handled
125 if !self.parents
.contains_key(&ii
.id
) {
126 self.parents
.insert(ii
.id
, self.curparent
);
128 visit
::walk_impl_item(self, ii
);
131 fn visit_struct_def(&mut self, s
: &ast
::StructDef
, _
: ast
::Ident
,
132 _
: &'v ast
::Generics
, n
: ast
::NodeId
) {
133 // Struct constructors are parented to their struct definitions because
134 // they essentially are the struct definitions.
136 Some(id
) => { self.parents.insert(id, n); }
140 // While we have the id of the struct definition, go ahead and parent
142 for field
in &s
.fields
{
143 self.parents
.insert(field
.node
.id
, self.curparent
);
145 visit
::walk_struct_def(self, s
)
149 ////////////////////////////////////////////////////////////////////////////////
150 /// The embargo visitor, used to determine the exports of the ast
151 ////////////////////////////////////////////////////////////////////////////////
153 struct EmbargoVisitor
<'a
, 'tcx
: 'a
> {
154 tcx
: &'a ty
::ctxt
<'tcx
>,
155 export_map
: &'a def
::ExportMap
,
157 // This flag is an indicator of whether the previous item in the
158 // hierarchical chain was exported or not. This is the indicator of whether
159 // children should be exported as well. Note that this can flip from false
160 // to true if a reexported module is entered (or an action similar).
163 // This is a list of all exported items in the AST. An exported item is any
164 // function/method/item which is usable by external crates. This essentially
165 // means that the result is "public all the way down", but the "path down"
166 // may jump across private boundaries through reexport statements.
167 exported_items
: ExportedItems
,
169 // This sets contains all the destination nodes which are publicly
170 // re-exported. This is *not* a set of all reexported nodes, only a set of
171 // all nodes which are reexported *and* reachable from external crates. This
172 // means that the destination of the reexport is exported, and hence the
173 // destination must also be exported.
176 // These two fields are closely related to one another in that they are only
177 // used for generation of the 'PublicItems' set, not for privacy checking at
179 public_items
: PublicItems
,
183 impl<'a
, 'tcx
> EmbargoVisitor
<'a
, 'tcx
> {
184 // There are checks inside of privacy which depend on knowing whether a
185 // trait should be exported or not. The two current consumers of this are:
187 // 1. Should default methods of a trait be exported?
188 // 2. Should the methods of an implementation of a trait be exported?
190 // The answer to both of these questions partly rely on whether the trait
191 // itself is exported or not. If the trait is somehow exported, then the
192 // answers to both questions must be yes. Right now this question involves
193 // more analysis than is currently done in rustc, so we conservatively
194 // answer "yes" so that all traits need to be exported.
195 fn exported_trait(&self, _id
: ast
::NodeId
) -> bool
{
200 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for EmbargoVisitor
<'a
, 'tcx
> {
201 fn visit_item(&mut self, item
: &ast
::Item
) {
202 let orig_all_pub
= self.prev_public
;
203 self.prev_public
= orig_all_pub
&& item
.vis
== ast
::Public
;
204 if self.prev_public
{
205 self.public_items
.insert(item
.id
);
208 let orig_all_exported
= self.prev_exported
;
210 // impls/extern blocks do not break the "public chain" because they
211 // cannot have visibility qualifiers on them anyway
212 ast
::ItemImpl(..) | ast
::ItemDefaultImpl(..) | ast
::ItemForeignMod(..) => {}
214 // Traits are a little special in that even if they themselves are
215 // not public they may still be exported.
216 ast
::ItemTrait(..) => {
217 self.prev_exported
= self.exported_trait(item
.id
);
220 // Private by default, hence we only retain the "public chain" if
221 // `pub` is explicitly listed.
224 (orig_all_exported
&& item
.vis
== ast
::Public
) ||
225 self.reexports
.contains(&item
.id
);
229 let public_first
= self.prev_exported
&&
230 self.exported_items
.insert(item
.id
);
233 // Enum variants inherit from their parent, so if the enum is
234 // public all variants are public unless they're explicitly priv
235 ast
::ItemEnum(ref def
, _
) if public_first
=> {
236 for variant
in &def
.variants
{
237 self.exported_items
.insert(variant
.node
.id
);
238 self.public_items
.insert(variant
.node
.id
);
242 // Implementations are a little tricky to determine what's exported
243 // out of them. Here's a few cases which are currently defined:
245 // * Impls for private types do not need to export their methods
246 // (either public or private methods)
248 // * Impls for public types only have public methods exported
250 // * Public trait impls for public types must have all methods
253 // * Private trait impls for public types can be ignored
255 // * Public trait impls for private types have their methods
256 // exported. I'm not entirely certain that this is the correct
257 // thing to do, but I have seen use cases of where this will cause
258 // undefined symbols at linkage time if this case is not handled.
260 // * Private trait impls for private types can be completely ignored
261 ast
::ItemImpl(_
, _
, _
, _
, ref ty
, ref impl_items
) => {
262 let public_ty
= match ty
.node
{
264 match self.tcx
.def_map
.borrow().get(&ty
.id
).unwrap().full_def() {
265 def
::DefPrimTy(..) => true,
267 let did
= def
.def_id();
269 self.exported_items
.contains(&did
.node
)
275 let tr
= ty
::impl_trait_ref(self.tcx
, local_def(item
.id
));
276 let public_trait
= tr
.clone().map_or(false, |tr
| {
277 !is_local(tr
.def_id
) ||
278 self.exported_items
.contains(&tr
.def_id
.node
)
281 if public_ty
|| public_trait
{
282 for impl_item
in impl_items
{
283 match impl_item
.node
{
284 ast
::ConstImplItem(..) => {
285 if (public_ty
&& impl_item
.vis
== ast
::Public
)
287 self.exported_items
.insert(impl_item
.id
);
290 ast
::MethodImplItem(ref sig
, _
) => {
291 let meth_public
= match sig
.explicit_self
.node
{
292 ast
::SelfStatic
=> public_ty
,
294 } && impl_item
.vis
== ast
::Public
;
295 if meth_public
|| tr
.is_some() {
296 self.exported_items
.insert(impl_item
.id
);
299 ast
::TypeImplItem(_
) |
300 ast
::MacImplItem(_
) => {}
306 // Default methods on traits are all public so long as the trait
308 ast
::ItemTrait(_
, _
, _
, ref trait_items
) if public_first
=> {
309 for trait_item
in trait_items
{
310 debug
!("trait item {}", trait_item
.id
);
311 self.exported_items
.insert(trait_item
.id
);
315 // Struct constructors are public if the struct is all public.
316 ast
::ItemStruct(ref def
, _
) if public_first
=> {
318 Some(id
) => { self.exported_items.insert(id); }
321 // fields can be public or private, so lets check
322 for field
in &def
.fields
{
323 let vis
= match field
.node
.kind
{
324 ast
::NamedField(_
, vis
) | ast
::UnnamedField(vis
) => vis
326 if vis
== ast
::Public
{
327 self.public_items
.insert(field
.node
.id
);
332 ast
::ItemTy(ref ty
, _
) if public_first
=> {
333 if let ast
::TyPath(..) = ty
.node
{
334 match self.tcx
.def_map
.borrow().get(&ty
.id
).unwrap().full_def() {
335 def
::DefPrimTy(..) | def
::DefTyParam(..) => {}
,
337 let did
= def
.def_id();
339 self.exported_items
.insert(did
.node
);
349 visit
::walk_item(self, item
);
351 self.prev_exported
= orig_all_exported
;
352 self.prev_public
= orig_all_pub
;
355 fn visit_foreign_item(&mut self, a
: &ast
::ForeignItem
) {
356 if (self.prev_exported
&& a
.vis
== ast
::Public
) || self.reexports
.contains(&a
.id
) {
357 self.exported_items
.insert(a
.id
);
361 fn visit_mod(&mut self, m
: &ast
::Mod
, _sp
: Span
, id
: ast
::NodeId
) {
362 // This code is here instead of in visit_item so that the
363 // crate module gets processed as well.
364 if self.prev_exported
{
365 assert
!(self.export_map
.contains_key(&id
), "wut {}", id
);
366 for export
in self.export_map
.get(&id
).unwrap() {
367 if is_local(export
.def_id
) {
368 self.reexports
.insert(export
.def_id
.node
);
372 visit
::walk_mod(self, m
)
376 ////////////////////////////////////////////////////////////////////////////////
377 /// The privacy visitor, where privacy checks take place (violations reported)
378 ////////////////////////////////////////////////////////////////////////////////
380 struct PrivacyVisitor
<'a
, 'tcx
: 'a
> {
381 tcx
: &'a ty
::ctxt
<'tcx
>,
382 curitem
: ast
::NodeId
,
384 parents
: NodeMap
<ast
::NodeId
>,
385 external_exports
: ExternalExports
,
391 DisallowedBy(ast
::NodeId
),
395 UnnamedField(usize), // index
396 // (Name, not Ident, because struct fields are not macro-hygienic)
397 NamedField(ast
::Name
),
400 impl<'a
, 'tcx
> PrivacyVisitor
<'a
, 'tcx
> {
401 // used when debugging
402 fn nodestr(&self, id
: ast
::NodeId
) -> String
{
403 self.tcx
.map
.node_to_string(id
).to_string()
406 // Determines whether the given definition is public from the point of view
407 // of the current item.
408 fn def_privacy(&self, did
: ast
::DefId
) -> PrivacyResult
{
410 if self.external_exports
.contains(&did
) {
411 debug
!("privacy - {:?} was externally exported", did
);
414 debug
!("privacy - is {:?} a public method", did
);
416 return match self.tcx
.impl_or_trait_items
.borrow().get(&did
) {
417 Some(&ty
::ConstTraitItem(ref ac
)) => {
418 debug
!("privacy - it's a const: {:?}", *ac
);
420 ty
::TraitContainer(id
) => {
421 debug
!("privacy - recursing on trait {:?}", id
);
424 ty
::ImplContainer(id
) => {
425 match ty
::impl_trait_ref(self.tcx
, id
) {
427 debug
!("privacy - impl of trait {:?}", id
);
428 self.def_privacy(t
.def_id
)
431 debug
!("privacy - found inherent \
432 associated constant {:?}",
434 if ac
.vis
== ast
::Public
{
444 Some(&ty
::MethodTraitItem(ref meth
)) => {
445 debug
!("privacy - well at least it's a method: {:?}",
447 match meth
.container
{
448 ty
::TraitContainer(id
) => {
449 debug
!("privacy - recursing on trait {:?}", id
);
452 ty
::ImplContainer(id
) => {
453 match ty
::impl_trait_ref(self.tcx
, id
) {
455 debug
!("privacy - impl of trait {:?}", id
);
456 self.def_privacy(t
.def_id
)
459 debug
!("privacy - found a method {:?}",
461 if meth
.vis
== ast
::Public
{
471 Some(&ty
::TypeTraitItem(ref typedef
)) => {
472 match typedef
.container
{
473 ty
::TraitContainer(id
) => {
474 debug
!("privacy - recursing on trait {:?}", id
);
477 ty
::ImplContainer(id
) => {
478 match ty
::impl_trait_ref(self.tcx
, id
) {
480 debug
!("privacy - impl of trait {:?}", id
);
481 self.def_privacy(t
.def_id
)
484 debug
!("privacy - found a typedef {:?}",
486 if typedef
.vis
== ast
::Public
{
497 debug
!("privacy - nope, not even a method");
503 debug
!("privacy - local {} not public all the way down",
504 self.tcx
.map
.node_to_string(did
.node
));
505 // return quickly for things in the same module
506 if self.parents
.get(&did
.node
) == self.parents
.get(&self.curitem
) {
507 debug
!("privacy - same parent, we're done here");
511 // We now know that there is at least one private member between the
512 // destination and the root.
513 let mut closest_private_id
= did
.node
;
515 debug
!("privacy - examining {}", self.nodestr(closest_private_id
));
516 let vis
= match self.tcx
.map
.find(closest_private_id
) {
517 // If this item is a method, then we know for sure that it's an
518 // actual method and not a static method. The reason for this is
519 // that these cases are only hit in the ExprMethodCall
520 // expression, and ExprCall will have its path checked later
521 // (the path of the trait/impl) if it's a static method.
523 // With this information, then we can completely ignore all
524 // trait methods. The privacy violation would be if the trait
525 // couldn't get imported, not if the method couldn't be used
526 // (all trait methods are public).
528 // However, if this is an impl method, then we dictate this
529 // decision solely based on the privacy of the method
531 // FIXME(#10573) is this the right behavior? Why not consider
532 // where the method was defined?
533 Some(ast_map
::NodeImplItem(ii
)) => {
535 ast
::ConstImplItem(..) |
536 ast
::MethodImplItem(..) => {
537 let imp
= self.tcx
.map
538 .get_parent_did(closest_private_id
);
539 match ty
::impl_trait_ref(self.tcx
, imp
) {
540 Some(..) => return Allowable
,
541 _
if ii
.vis
== ast
::Public
=> {
547 ast
::TypeImplItem(_
) |
548 ast
::MacImplItem(_
) => return Allowable
,
551 Some(ast_map
::NodeTraitItem(_
)) => {
555 // This is not a method call, extract the visibility as one
556 // would normally look at it
557 Some(ast_map
::NodeItem(it
)) => it
.vis
,
558 Some(ast_map
::NodeForeignItem(_
)) => {
559 self.tcx
.map
.get_foreign_vis(closest_private_id
)
561 Some(ast_map
::NodeVariant(..)) => {
562 ast
::Public
// need to move up a level (to the enum)
566 if vis
!= ast
::Public { break }
567 // if we've reached the root, then everything was allowable and this
569 if closest_private_id
== ast
::CRATE_NODE_ID { return Allowable }
570 closest_private_id
= *self.parents
.get(&closest_private_id
).unwrap();
572 // If we reached the top, then we were public all the way down and
573 // we can allow this access.
574 if closest_private_id
== ast
::DUMMY_NODE_ID { return Allowable }
576 debug
!("privacy - closest priv {}", self.nodestr(closest_private_id
));
577 if self.private_accessible(closest_private_id
) {
580 DisallowedBy(closest_private_id
)
584 /// For a local private node in the AST, this function will determine
585 /// whether the node is accessible by the current module that iteration is
587 fn private_accessible(&self, id
: ast
::NodeId
) -> bool
{
588 let parent
= *self.parents
.get(&id
).unwrap();
589 debug
!("privacy - accessible parent {}", self.nodestr(parent
));
591 // After finding `did`'s closest private member, we roll ourselves back
592 // to see if this private member's parent is anywhere in our ancestry.
593 // By the privacy rules, we can access all of our ancestor's private
594 // members, so that's why we test the parent, and not the did itself.
595 let mut cur
= self.curitem
;
597 debug
!("privacy - questioning {}, {}", self.nodestr(cur
), cur
);
599 // If the relevant parent is in our history, then we're allowed
600 // to look inside any of our ancestor's immediate private items,
601 // so this access is valid.
602 x
if x
== parent
=> return true,
604 // If we've reached the root, then we couldn't access this item
605 // in the first place
606 ast
::DUMMY_NODE_ID
=> return false,
612 cur
= *self.parents
.get(&cur
).unwrap();
616 fn report_error(&self, result
: CheckResult
) -> bool
{
619 Some((span
, msg
, note
)) => {
620 self.tcx
.sess
.span_err(span
, &msg
[..]);
622 Some((span
, msg
)) => {
623 self.tcx
.sess
.span_note(span
, &msg
[..])
632 /// Guarantee that a particular definition is public. Returns a CheckResult
633 /// which contains any errors found. These can be reported using `report_error`.
634 /// If the result is `None`, no errors were found.
635 fn ensure_public(&self, span
: Span
, to_check
: ast
::DefId
,
636 source_did
: Option
<ast
::DefId
>, msg
: &str) -> CheckResult
{
637 let id
= match self.def_privacy(to_check
) {
638 ExternallyDenied
=> {
639 return Some((span
, format
!("{} is private", msg
), None
))
641 Allowable
=> return None
,
642 DisallowedBy(id
) => id
,
645 // If we're disallowed by a particular id, then we attempt to give a
646 // nice error message to say why it was disallowed. It was either
647 // because the item itself is private or because its parent is private
648 // and its parent isn't in our ancestry.
649 let (err_span
, err_msg
) = if id
== source_did
.unwrap_or(to_check
).node
{
650 return Some((span
, format
!("{} is private", msg
), None
));
652 (span
, format
!("{} is inaccessible", msg
))
654 let item
= match self.tcx
.map
.find(id
) {
655 Some(ast_map
::NodeItem(item
)) => {
657 // If an impl disallowed this item, then this is resolve's
658 // way of saying that a struct/enum's static method was
659 // invoked, and the struct/enum itself is private. Crawl
660 // back up the chains to find the relevant struct/enum that
662 ast
::ItemImpl(_
, _
, _
, _
, ref ty
, _
) => {
664 ast
::TyPath(..) => {}
665 _
=> return Some((err_span
, err_msg
, None
)),
667 let def
= self.tcx
.def_map
.borrow().get(&ty
.id
).unwrap().full_def();
668 let did
= def
.def_id();
669 assert
!(is_local(did
));
670 match self.tcx
.map
.get(did
.node
) {
671 ast_map
::NodeItem(item
) => item
,
672 _
=> self.tcx
.sess
.span_bug(item
.span
,
673 "path is not an item")
679 Some(..) | None
=> return Some((err_span
, err_msg
, None
)),
681 let desc
= match item
.node
{
682 ast
::ItemMod(..) => "module",
683 ast
::ItemTrait(..) => "trait",
684 ast
::ItemStruct(..) => "struct",
685 ast
::ItemEnum(..) => "enum",
686 _
=> return Some((err_span
, err_msg
, None
))
688 let msg
= format
!("{} `{}` is private", desc
,
689 token
::get_ident(item
.ident
));
690 Some((err_span
, err_msg
, Some((span
, msg
))))
693 // Checks that a field is in scope.
694 fn check_field(&mut self,
698 let fields
= ty
::lookup_struct_fields(self.tcx
, id
);
699 let field
= match name
{
700 NamedField(f_name
) => {
701 debug
!("privacy - check named field {} in struct {:?}", f_name
, id
);
702 fields
.iter().find(|f
| f
.name
== f_name
).unwrap()
704 UnnamedField(idx
) => &fields
[idx
]
706 if field
.vis
== ast
::Public
||
707 (is_local(field
.id
) && self.private_accessible(field
.id
.node
)) {
711 let struct_type
= ty
::lookup_item_type(self.tcx
, id
).ty
;
712 let struct_desc
= match struct_type
.sty
{
713 ty
::ty_struct(_
, _
) =>
714 format
!("struct `{}`", ty
::item_path_str(self.tcx
, id
)),
715 // struct variant fields have inherited visibility
716 ty
::ty_enum(..) => return,
717 _
=> self.tcx
.sess
.span_bug(span
, "can't find struct for field")
719 let msg
= match name
{
720 NamedField(name
) => format
!("field `{}` of {} is private",
721 token
::get_name(name
), struct_desc
),
722 UnnamedField(idx
) => format
!("field #{} of {} is private",
723 idx
+ 1, struct_desc
),
725 self.tcx
.sess
.span_err(span
, &msg
[..]);
728 // Given the ID of a method, checks to ensure it's in scope.
729 fn check_static_method(&mut self,
731 method_id
: ast
::DefId
,
733 // If the method is a default method, we need to use the def_id of
734 // the default implementation.
735 let method_id
= match ty
::impl_or_trait_item(self.tcx
, method_id
) {
736 ty
::MethodTraitItem(method_type
) => {
737 method_type
.provided_source
.unwrap_or(method_id
)
742 "got non-method item in check_static_method")
746 let string
= token
::get_name(name
);
747 self.report_error(self.ensure_public(span
,
750 &format
!("method `{}`",
754 // Checks that a path is in scope.
755 fn check_path(&mut self, span
: Span
, path_id
: ast
::NodeId
, last
: ast
::Name
) {
756 debug
!("privacy - path {}", self.nodestr(path_id
));
757 let path_res
= *self.tcx
.def_map
.borrow().get(&path_id
).unwrap();
758 let ck
= |tyname
: &str| {
759 let ck_public
= |def
: ast
::DefId
| {
760 debug
!("privacy - ck_public {:?}", def
);
761 let name
= token
::get_name(last
);
762 let origdid
= path_res
.def_id();
763 self.ensure_public(span
,
766 &format
!("{} `{}`", tyname
, name
))
769 match path_res
.last_private
{
770 LastMod(AllPublic
) => {}
,
771 LastMod(DependsOn(def
)) => {
772 self.report_error(ck_public(def
));
774 LastImport
{ value_priv
,
775 value_used
: check_value
,
777 type_used
: check_type
} => {
778 // This dance with found_error is because we don't want to
779 // report a privacy error twice for the same directive.
780 let found_error
= match (type_priv
, check_type
) {
781 (Some(DependsOn(def
)), Used
) => {
782 !self.report_error(ck_public(def
))
787 match (value_priv
, check_value
) {
788 (Some(DependsOn(def
)), Used
) => {
789 self.report_error(ck_public(def
));
794 // If an import is not used in either namespace, we still
795 // want to check that it could be legal. Therefore we check
796 // in both namespaces and only report an error if both would
797 // be illegal. We only report one error, even if it is
798 // illegal to import from both namespaces.
799 match (value_priv
, check_value
, type_priv
, check_type
) {
800 (Some(p
), Unused
, None
, _
) |
801 (None
, _
, Some(p
), Unused
) => {
804 DependsOn(def
) => ck_public(def
),
807 self.report_error(p
);
810 (Some(v
), Unused
, Some(t
), Unused
) => {
813 DependsOn(def
) => ck_public(def
),
817 DependsOn(def
) => ck_public(def
),
819 if let (Some(_
), Some(t
)) = (v
, t
) {
820 self.report_error(Some(t
));
828 // FIXME(#12334) Imports can refer to definitions in both the type and
829 // value namespaces. The privacy information is aware of this, but the
830 // def map is not. Therefore the names we work out below will not always
831 // be accurate and we can get slightly wonky error messages (but type
832 // checking is always correct).
833 match path_res
.full_def() {
834 def
::DefFn(..) => ck("function"),
835 def
::DefStatic(..) => ck("static"),
836 def
::DefConst(..) => ck("const"),
837 def
::DefAssociatedConst(..) => ck("associated const"),
838 def
::DefVariant(..) => ck("variant"),
839 def
::DefTy(_
, false) => ck("type"),
840 def
::DefTy(_
, true) => ck("enum"),
841 def
::DefTrait(..) => ck("trait"),
842 def
::DefStruct(..) => ck("struct"),
843 def
::DefMethod(..) => ck("method"),
844 def
::DefMod(..) => ck("module"),
849 // Checks that a method is in scope.
850 fn check_method(&mut self, span
: Span
, origin
: &MethodOrigin
,
853 MethodStatic(method_id
) => {
854 self.check_static_method(span
, method_id
, name
)
856 MethodStaticClosure(_
) => {}
857 // Trait methods are always all public. The only controlling factor
858 // is whether the trait itself is accessible or not.
859 MethodTypeParam(MethodParam { ref trait_ref, .. }
) |
860 MethodTraitObject(MethodObject { ref trait_ref, .. }
) => {
861 self.report_error(self.ensure_public(span
, trait_ref
.def_id
,
862 None
, "source trait"));
868 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for PrivacyVisitor
<'a
, 'tcx
> {
869 fn visit_item(&mut self, item
: &ast
::Item
) {
870 if let ast
::ItemUse(ref vpath
) = item
.node
{
871 if let ast
::ViewPathList(ref prefix
, ref list
) = vpath
.node
{
874 ast
::PathListIdent { id, name }
=> {
875 debug
!("privacy - ident item {}", id
);
876 self.check_path(pid
.span
, id
, name
.name
);
878 ast
::PathListMod { id }
=> {
879 debug
!("privacy - mod item {}", id
);
880 let name
= prefix
.segments
.last().unwrap().identifier
.name
;
881 self.check_path(pid
.span
, id
, name
);
887 let orig_curitem
= replace(&mut self.curitem
, item
.id
);
888 visit
::walk_item(self, item
);
889 self.curitem
= orig_curitem
;
892 fn visit_expr(&mut self, expr
: &ast
::Expr
) {
894 ast
::ExprField(ref base
, ident
) => {
895 if let ty
::ty_struct(id
, _
) = ty
::expr_ty_adjusted(self.tcx
, &**base
).sty
{
896 self.check_field(expr
.span
, id
, NamedField(ident
.node
.name
));
899 ast
::ExprTupField(ref base
, idx
) => {
900 if let ty
::ty_struct(id
, _
) = ty
::expr_ty_adjusted(self.tcx
, &**base
).sty
{
901 self.check_field(expr
.span
, id
, UnnamedField(idx
.node
));
904 ast
::ExprMethodCall(ident
, _
, _
) => {
905 let method_call
= MethodCall
::expr(expr
.id
);
906 match self.tcx
.method_map
.borrow().get(&method_call
) {
908 self.tcx
.sess
.span_bug(expr
.span
,
909 "method call not in \
913 debug
!("(privacy checking) checking impl method");
914 self.check_method(expr
.span
, &method
.origin
, ident
.node
.name
);
918 ast
::ExprStruct(_
, ref fields
, _
) => {
919 match ty
::expr_ty(self.tcx
, expr
).sty
{
920 ty
::ty_struct(ctor_id
, _
) => {
921 // RFC 736: ensure all unmentioned fields are visible.
922 // Rather than computing the set of unmentioned fields
923 // (i.e. `all_fields - fields`), just check them all.
924 let all_fields
= ty
::lookup_struct_fields(self.tcx
, ctor_id
);
925 for field
in all_fields
{
926 self.check_field(expr
.span
, ctor_id
,
927 NamedField(field
.name
));
930 ty
::ty_enum(_
, _
) => {
931 match self.tcx
.def_map
.borrow().get(&expr
.id
).unwrap().full_def() {
932 def
::DefVariant(_
, variant_id
, _
) => {
933 for field
in fields
{
934 self.check_field(expr
.span
, variant_id
,
935 NamedField(field
.ident
.node
.name
));
938 _
=> self.tcx
.sess
.span_bug(expr
.span
,
945 _
=> self.tcx
.sess
.span_bug(expr
.span
, "struct expr \
950 ast
::ExprPath(..) => {
951 let guard
= |did
: ast
::DefId
| {
952 let fields
= ty
::lookup_struct_fields(self.tcx
, did
);
953 let any_priv
= fields
.iter().any(|f
| {
954 f
.vis
!= ast
::Public
&& (
956 !self.private_accessible(f
.id
.node
))
959 self.tcx
.sess
.span_err(expr
.span
,
960 "cannot invoke tuple struct constructor \
961 with private fields");
964 match self.tcx
.def_map
.borrow().get(&expr
.id
).map(|d
| d
.full_def()) {
965 Some(def
::DefStruct(did
)) => {
966 guard(if is_local(did
) {
967 local_def(self.tcx
.map
.get_parent(did
.node
))
969 // "tuple structs" with zero fields (such as
970 // `pub struct Foo;`) don't have a ctor_id, hence
971 // the unwrap_or to the same struct id.
973 csearch
::get_tuple_struct_definition_if_ctor(
974 &self.tcx
.sess
.cstore
, did
);
975 maybe_did
.unwrap_or(did
)
984 visit
::walk_expr(self, expr
);
987 fn visit_pat(&mut self, pattern
: &ast
::Pat
) {
988 // Foreign functions do not have their patterns mapped in the def_map,
989 // and there's nothing really relevant there anyway, so don't bother
990 // checking privacy. If you can name the type then you can pass it to an
991 // external C function anyway.
992 if self.in_foreign { return }
995 ast
::PatStruct(_
, ref fields
, _
) => {
996 match ty
::pat_ty(self.tcx
, pattern
).sty
{
997 ty
::ty_struct(id
, _
) => {
998 for field
in fields
{
999 self.check_field(pattern
.span
, id
,
1000 NamedField(field
.node
.ident
.name
));
1003 ty
::ty_enum(_
, _
) => {
1004 match self.tcx
.def_map
.borrow().get(&pattern
.id
).map(|d
| d
.full_def()) {
1005 Some(def
::DefVariant(_
, variant_id
, _
)) => {
1006 for field
in fields
{
1007 self.check_field(pattern
.span
, variant_id
,
1008 NamedField(field
.node
.ident
.name
));
1011 _
=> self.tcx
.sess
.span_bug(pattern
.span
,
1018 _
=> self.tcx
.sess
.span_bug(pattern
.span
,
1019 "struct pattern didn't have \
1024 // Patterns which bind no fields are allowable (the path is check
1026 ast
::PatEnum(_
, Some(ref fields
)) => {
1027 match ty
::pat_ty(self.tcx
, pattern
).sty
{
1028 ty
::ty_struct(id
, _
) => {
1029 for (i
, field
) in fields
.iter().enumerate() {
1030 if let ast
::PatWild(..) = field
.node
{
1033 self.check_field(field
.span
, id
, UnnamedField(i
));
1036 ty
::ty_enum(..) => {
1037 // enum fields have no privacy at this time
1046 visit
::walk_pat(self, pattern
);
1049 fn visit_foreign_item(&mut self, fi
: &ast
::ForeignItem
) {
1050 self.in_foreign
= true;
1051 visit
::walk_foreign_item(self, fi
);
1052 self.in_foreign
= false;
1055 fn visit_path(&mut self, path
: &ast
::Path
, id
: ast
::NodeId
) {
1056 self.check_path(path
.span
, id
, path
.segments
.last().unwrap().identifier
.name
);
1057 visit
::walk_path(self, path
);
1061 ////////////////////////////////////////////////////////////////////////////////
1062 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1063 ////////////////////////////////////////////////////////////////////////////////
1065 struct SanePrivacyVisitor
<'a
, 'tcx
: 'a
> {
1066 tcx
: &'a ty
::ctxt
<'tcx
>,
1070 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for SanePrivacyVisitor
<'a
, 'tcx
> {
1071 fn visit_item(&mut self, item
: &ast
::Item
) {
1073 self.check_all_inherited(item
);
1075 self.check_sane_privacy(item
);
1078 let in_fn
= self.in_fn
;
1079 let orig_in_fn
= replace(&mut self.in_fn
, match item
.node
{
1080 ast
::ItemMod(..) => false, // modules turn privacy back on
1081 _
=> in_fn
, // otherwise we inherit
1083 visit
::walk_item(self, item
);
1084 self.in_fn
= orig_in_fn
;
1087 fn visit_fn(&mut self, fk
: visit
::FnKind
<'v
>, fd
: &'v ast
::FnDecl
,
1088 b
: &'v ast
::Block
, s
: Span
, _
: ast
::NodeId
) {
1089 // This catches both functions and methods
1090 let orig_in_fn
= replace(&mut self.in_fn
, true);
1091 visit
::walk_fn(self, fk
, fd
, b
, s
);
1092 self.in_fn
= orig_in_fn
;
1096 impl<'a
, 'tcx
> SanePrivacyVisitor
<'a
, 'tcx
> {
1097 /// Validates all of the visibility qualifiers placed on the item given. This
1098 /// ensures that there are no extraneous qualifiers that don't actually do
1099 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1100 /// later on down the road...
1101 fn check_sane_privacy(&self, item
: &ast
::Item
) {
1103 let check_inherited
= |sp
: Span
, vis
: ast
::Visibility
, note
: &str| {
1104 if vis
!= ast
::Inherited
{
1105 tcx
.sess
.span_err(sp
, "unnecessary visibility qualifier");
1106 if !note
.is_empty() {
1107 tcx
.sess
.span_note(sp
, note
);
1112 // implementations of traits don't need visibility qualifiers because
1113 // that's controlled by having the trait in scope.
1114 ast
::ItemImpl(_
, _
, _
, Some(..), _
, ref impl_items
) => {
1115 check_inherited(item
.span
, item
.vis
,
1116 "visibility qualifiers have no effect on trait \
1118 for impl_item
in impl_items
{
1119 check_inherited(impl_item
.span
, impl_item
.vis
, "");
1123 ast
::ItemImpl(..) => {
1124 check_inherited(item
.span
, item
.vis
,
1125 "place qualifiers on individual methods instead");
1127 ast
::ItemForeignMod(..) => {
1128 check_inherited(item
.span
, item
.vis
,
1129 "place qualifiers on individual functions \
1133 ast
::ItemEnum(ref def
, _
) => {
1134 for v
in &def
.variants
{
1137 if item
.vis
== ast
::Public
{
1138 tcx
.sess
.span_err(v
.span
, "unnecessary `pub` \
1142 ast
::Inherited
=> {}
1147 ast
::ItemTrait(..) | ast
::ItemDefaultImpl(..) |
1148 ast
::ItemConst(..) | ast
::ItemStatic(..) | ast
::ItemStruct(..) |
1149 ast
::ItemFn(..) | ast
::ItemMod(..) | ast
::ItemTy(..) |
1150 ast
::ItemExternCrate(_
) | ast
::ItemUse(_
) | ast
::ItemMac(..) => {}
1154 /// When inside of something like a function or a method, visibility has no
1155 /// control over anything so this forbids any mention of any visibility
1156 fn check_all_inherited(&self, item
: &ast
::Item
) {
1158 fn check_inherited(tcx
: &ty
::ctxt
, sp
: Span
, vis
: ast
::Visibility
) {
1159 if vis
!= ast
::Inherited
{
1160 tcx
.sess
.span_err(sp
, "visibility has no effect inside functions");
1163 let check_struct
= |def
: &ast
::StructDef
| {
1164 for f
in &def
.fields
{
1166 ast
::NamedField(_
, p
) => check_inherited(tcx
, f
.span
, p
),
1167 ast
::UnnamedField(..) => {}
1171 check_inherited(tcx
, item
.span
, item
.vis
);
1173 ast
::ItemImpl(_
, _
, _
, _
, _
, ref impl_items
) => {
1174 for impl_item
in impl_items
{
1175 match impl_item
.node
{
1176 ast
::MethodImplItem(..) => {
1177 check_inherited(tcx
, impl_item
.span
, impl_item
.vis
);
1183 ast
::ItemForeignMod(ref fm
) => {
1184 for i
in &fm
.items
{
1185 check_inherited(tcx
, i
.span
, i
.vis
);
1188 ast
::ItemEnum(ref def
, _
) => {
1189 for v
in &def
.variants
{
1190 check_inherited(tcx
, v
.span
, v
.node
.vis
);
1194 ast
::ItemStruct(ref def
, _
) => check_struct(&**def
),
1196 ast
::ItemExternCrate(_
) | ast
::ItemUse(_
) |
1197 ast
::ItemTrait(..) | ast
::ItemDefaultImpl(..) |
1198 ast
::ItemStatic(..) | ast
::ItemConst(..) |
1199 ast
::ItemFn(..) | ast
::ItemMod(..) | ast
::ItemTy(..) |
1200 ast
::ItemMac(..) => {}
1205 struct VisiblePrivateTypesVisitor
<'a
, 'tcx
: 'a
> {
1206 tcx
: &'a ty
::ctxt
<'tcx
>,
1207 exported_items
: &'a ExportedItems
,
1208 public_items
: &'a PublicItems
,
1212 struct CheckTypeForPrivatenessVisitor
<'a
, 'b
: 'a
, 'tcx
: 'b
> {
1213 inner
: &'a VisiblePrivateTypesVisitor
<'b
, 'tcx
>,
1214 /// whether the type refers to private types.
1215 contains_private
: bool
,
1216 /// whether we've recurred at all (i.e. if we're pointing at the
1217 /// first type on which visit_ty was called).
1218 at_outer_type
: bool
,
1219 // whether that first type is a public path.
1220 outer_type_is_public_path
: bool
,
1223 impl<'a
, 'tcx
> VisiblePrivateTypesVisitor
<'a
, 'tcx
> {
1224 fn path_is_private_type(&self, path_id
: ast
::NodeId
) -> bool
{
1225 let did
= match self.tcx
.def_map
.borrow().get(&path_id
).map(|d
| d
.full_def()) {
1226 // `int` etc. (None doesn't seem to occur.)
1227 None
| Some(def
::DefPrimTy(..)) => return false,
1228 Some(def
) => def
.def_id(),
1230 // A path can only be private if:
1231 // it's in this crate...
1236 // .. and it corresponds to a private type in the AST (this returns
1237 // None for type parameters)
1238 match self.tcx
.map
.find(did
.node
) {
1239 Some(ast_map
::NodeItem(ref item
)) => item
.vis
!= ast
::Public
,
1240 Some(_
) | None
=> false,
1244 fn trait_is_public(&self, trait_id
: ast
::NodeId
) -> bool
{
1245 // FIXME: this would preferably be using `exported_items`, but all
1246 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1247 self.public_items
.contains(&trait_id
)
1250 fn check_ty_param_bound(&self,
1251 ty_param_bound
: &ast
::TyParamBound
) {
1252 if let ast
::TraitTyParamBound(ref trait_ref
, _
) = *ty_param_bound
{
1253 if !self.tcx
.sess
.features
.borrow().visible_private_types
&&
1254 self.path_is_private_type(trait_ref
.trait_ref
.ref_id
) {
1255 let span
= trait_ref
.trait_ref
.path
.span
;
1256 self.tcx
.sess
.span_err(span
, "private trait in exported type \
1262 fn item_is_public(&self, id
: &ast
::NodeId
, vis
: ast
::Visibility
) -> bool
{
1263 self.exported_items
.contains(id
) || vis
== ast
::Public
1267 impl<'a
, 'b
, 'tcx
, 'v
> Visitor
<'v
> for CheckTypeForPrivatenessVisitor
<'a
, 'b
, 'tcx
> {
1268 fn visit_ty(&mut self, ty
: &ast
::Ty
) {
1269 if let ast
::TyPath(..) = ty
.node
{
1270 if self.inner
.path_is_private_type(ty
.id
) {
1271 self.contains_private
= true;
1272 // found what we're looking for so let's stop
1275 } else if self.at_outer_type
{
1276 self.outer_type_is_public_path
= true;
1279 self.at_outer_type
= false;
1280 visit
::walk_ty(self, ty
)
1283 // don't want to recurse into [, .. expr]
1284 fn visit_expr(&mut self, _
: &ast
::Expr
) {}
1287 impl<'a
, 'tcx
, 'v
> Visitor
<'v
> for VisiblePrivateTypesVisitor
<'a
, 'tcx
> {
1288 fn visit_item(&mut self, item
: &ast
::Item
) {
1290 // contents of a private mod can be reexported, so we need
1291 // to check internals.
1292 ast
::ItemMod(_
) => {}
1294 // An `extern {}` doesn't introduce a new privacy
1295 // namespace (the contents have their own privacies).
1296 ast
::ItemForeignMod(_
) => {}
1298 ast
::ItemTrait(_
, _
, ref bounds
, _
) => {
1299 if !self.trait_is_public(item
.id
) {
1303 for bound
in &**bounds
{
1304 self.check_ty_param_bound(bound
)
1308 // impls need some special handling to try to offer useful
1309 // error messages without (too many) false positives
1310 // (i.e. we could just return here to not check them at
1311 // all, or some worse estimation of whether an impl is
1312 // publicly visible).
1313 ast
::ItemImpl(_
, _
, ref g
, ref trait_ref
, ref self_
, ref impl_items
) => {
1314 // `impl [... for] Private` is never visible.
1315 let self_contains_private
;
1316 // impl [... for] Public<...>, but not `impl [... for]
1317 // Vec<Public>` or `(Public,)` etc.
1318 let self_is_public_path
;
1320 // check the properties of the Self type:
1322 let mut visitor
= CheckTypeForPrivatenessVisitor
{
1324 contains_private
: false,
1325 at_outer_type
: true,
1326 outer_type_is_public_path
: false,
1328 visitor
.visit_ty(&**self_
);
1329 self_contains_private
= visitor
.contains_private
;
1330 self_is_public_path
= visitor
.outer_type_is_public_path
;
1333 // miscellaneous info about the impl
1335 // `true` iff this is `impl Private for ...`.
1336 let not_private_trait
=
1337 trait_ref
.as_ref().map_or(true, // no trait counts as public trait
1339 let did
= ty
::trait_ref_to_def_id(self.tcx
, tr
);
1341 !is_local(did
) || self.trait_is_public(did
.node
)
1344 // `true` iff this is a trait impl or at least one method is public.
1346 // `impl Public { $( fn ...() {} )* }` is not visible.
1348 // This is required over just using the methods' privacy
1349 // directly because we might have `impl<T: Foo<Private>> ...`,
1350 // and we shouldn't warn about the generics if all the methods
1351 // are private (because `T` won't be visible externally).
1352 let trait_or_some_public_method
=
1353 trait_ref
.is_some() ||
1356 match impl_item
.node
{
1357 ast
::ConstImplItem(..) |
1358 ast
::MethodImplItem(..) => {
1359 self.exported_items
.contains(&impl_item
.id
)
1361 ast
::TypeImplItem(_
) |
1362 ast
::MacImplItem(_
) => false,
1366 if !self_contains_private
&&
1367 not_private_trait
&&
1368 trait_or_some_public_method
{
1370 visit
::walk_generics(self, g
);
1374 for impl_item
in impl_items
{
1375 // This is where we choose whether to walk down
1376 // further into the impl to check its items. We
1377 // should only walk into public items so that we
1378 // don't erroneously report errors for private
1379 // types in private items.
1380 match impl_item
.node
{
1381 ast
::ConstImplItem(..) |
1382 ast
::MethodImplItem(..)
1383 if self.item_is_public(&impl_item
.id
, impl_item
.vis
) =>
1385 visit
::walk_impl_item(self, impl_item
)
1387 ast
::TypeImplItem(..) => {
1388 visit
::walk_impl_item(self, impl_item
)
1395 // Any private types in a trait impl fall into three
1397 // 1. mentioned in the trait definition
1398 // 2. mentioned in the type params/generics
1399 // 3. mentioned in the associated types of the impl
1401 // Those in 1. can only occur if the trait is in
1402 // this crate and will've been warned about on the
1403 // trait definition (there's no need to warn twice
1404 // so we don't check the methods).
1406 // Those in 2. are warned via walk_generics and this
1408 visit
::walk_path(self, &tr
.path
);
1410 // Those in 3. are warned with this call.
1411 for impl_item
in impl_items
{
1412 if let ast
::TypeImplItem(ref ty
) = impl_item
.node
{
1418 } else if trait_ref
.is_none() && self_is_public_path
{
1419 // impl Public<Private> { ... }. Any public static
1420 // methods will be visible as `Public::foo`.
1421 let mut found_pub_static
= false;
1422 for impl_item
in impl_items
{
1423 match impl_item
.node
{
1424 ast
::ConstImplItem(..) => {
1425 if self.item_is_public(&impl_item
.id
, impl_item
.vis
) {
1426 found_pub_static
= true;
1427 visit
::walk_impl_item(self, impl_item
);
1430 ast
::MethodImplItem(ref sig
, _
) => {
1431 if sig
.explicit_self
.node
== ast
::SelfStatic
&&
1432 self.item_is_public(&impl_item
.id
, impl_item
.vis
) {
1433 found_pub_static
= true;
1434 visit
::walk_impl_item(self, impl_item
);
1440 if found_pub_static
{
1441 visit
::walk_generics(self, g
)
1447 // `type ... = ...;` can contain private types, because
1448 // we're introducing a new name.
1449 ast
::ItemTy(..) => return,
1451 // not at all public, so we don't care
1452 _
if !self.item_is_public(&item
.id
, item
.vis
) => {
1459 // We've carefully constructed it so that if we're here, then
1460 // any `visit_ty`'s will be called on things that are in
1461 // public signatures, i.e. things that we're interested in for
1463 debug
!("VisiblePrivateTypesVisitor entering item {:?}", item
);
1464 visit
::walk_item(self, item
);
1467 fn visit_generics(&mut self, generics
: &ast
::Generics
) {
1468 for ty_param
in &*generics
.ty_params
{
1469 for bound
in &*ty_param
.bounds
{
1470 self.check_ty_param_bound(bound
)
1473 for predicate
in &generics
.where_clause
.predicates
{
1475 &ast
::WherePredicate
::BoundPredicate(ref bound_pred
) => {
1476 for bound
in &*bound_pred
.bounds
{
1477 self.check_ty_param_bound(bound
)
1480 &ast
::WherePredicate
::RegionPredicate(_
) => {}
1481 &ast
::WherePredicate
::EqPredicate(ref eq_pred
) => {
1482 self.visit_ty(&*eq_pred
.ty
);
1488 fn visit_foreign_item(&mut self, item
: &ast
::ForeignItem
) {
1489 if self.exported_items
.contains(&item
.id
) {
1490 visit
::walk_foreign_item(self, item
)
1494 fn visit_ty(&mut self, t
: &ast
::Ty
) {
1495 debug
!("VisiblePrivateTypesVisitor checking ty {:?}", t
);
1496 if let ast
::TyPath(_
, ref p
) = t
.node
{
1497 if !self.tcx
.sess
.features
.borrow().visible_private_types
&&
1498 self.path_is_private_type(t
.id
) {
1499 self.tcx
.sess
.span_err(p
.span
, "private type in exported type signature");
1502 visit
::walk_ty(self, t
)
1505 fn visit_variant(&mut self, v
: &ast
::Variant
, g
: &ast
::Generics
) {
1506 if self.exported_items
.contains(&v
.node
.id
) {
1507 self.in_variant
= true;
1508 visit
::walk_variant(self, v
, g
);
1509 self.in_variant
= false;
1513 fn visit_struct_field(&mut self, s
: &ast
::StructField
) {
1515 ast
::NamedField(_
, vis
) if vis
== ast
::Public
|| self.in_variant
=> {
1516 visit
::walk_struct_field(self, s
);
1523 // we don't need to introspect into these at all: an
1524 // expression/block context can't possibly contain exported things.
1525 // (Making them no-ops stops us from traversing the whole AST without
1526 // having to be super careful about our `walk_...` calls above.)
1527 fn visit_block(&mut self, _
: &ast
::Block
) {}
1528 fn visit_expr(&mut self, _
: &ast
::Expr
) {}
1531 pub fn check_crate(tcx
: &ty
::ctxt
,
1532 export_map
: &def
::ExportMap
,
1533 external_exports
: ExternalExports
)
1534 -> (ExportedItems
, PublicItems
) {
1535 let krate
= tcx
.map
.krate();
1537 // Figure out who everyone's parent is
1538 let mut visitor
= ParentVisitor
{
1540 curparent
: ast
::DUMMY_NODE_ID
,
1542 visit
::walk_crate(&mut visitor
, krate
);
1544 // Use the parent map to check the privacy of everything
1545 let mut visitor
= PrivacyVisitor
{
1546 curitem
: ast
::DUMMY_NODE_ID
,
1549 parents
: visitor
.parents
,
1550 external_exports
: external_exports
,
1552 visit
::walk_crate(&mut visitor
, krate
);
1554 // Sanity check to make sure that all privacy usage and controls are
1556 let mut visitor
= SanePrivacyVisitor
{
1560 visit
::walk_crate(&mut visitor
, krate
);
1562 tcx
.sess
.abort_if_errors();
1564 // Build up a set of all exported items in the AST. This is a set of all
1565 // items which are reachable from external crates based on visibility.
1566 let mut visitor
= EmbargoVisitor
{
1568 exported_items
: NodeSet(),
1569 public_items
: NodeSet(),
1570 reexports
: NodeSet(),
1571 export_map
: export_map
,
1572 prev_exported
: true,
1576 let before
= visitor
.exported_items
.len();
1577 visit
::walk_crate(&mut visitor
, krate
);
1578 if before
== visitor
.exported_items
.len() {
1583 let EmbargoVisitor { exported_items, public_items, .. }
= visitor
;
1586 let mut visitor
= VisiblePrivateTypesVisitor
{
1588 exported_items
: &exported_items
,
1589 public_items
: &public_items
,
1592 visit
::walk_crate(&mut visitor
, krate
);
1594 return (exported_items
, public_items
);