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/")]
23 #![feature(rustc_diagnostic_macros)]
24 #![feature(rustc_private)]
25 #![feature(staged_api)]
27 #[macro_use] extern crate log;
28 #[macro_use] extern crate syntax;
32 use self::PrivacyResult::*;
33 use self::FieldName::*;
35 use std::mem::replace;
37 use rustc::metadata::csearch;
38 use rustc::middle::def;
39 use rustc::middle::privacy::ImportUse::*;
40 use rustc::middle::privacy::LastPrivate::*;
41 use rustc::middle::privacy::PrivateDep::*;
42 use rustc::middle::privacy::{ExternalExports, ExportedItems, PublicItems};
43 use rustc::middle::ty::{MethodTypeParam, MethodStatic};
44 use rustc::middle::ty::{MethodCall, MethodMap, MethodOrigin, MethodParam};
45 use rustc::middle::ty::{MethodStaticClosure, MethodObject};
46 use rustc::middle::ty::{MethodTraitObject};
47 use rustc::middle::ty::{self, Ty};
48 use rustc::util::nodemap::{NodeMap, NodeSet};
50 use syntax::{ast, ast_map};
51 use syntax::ast_util::{is_local, local_def, PostExpansionMethod};
52 use syntax::codemap::Span;
53 use syntax::parse::token;
54 use syntax::visit::{self, Visitor};
56 type Context<'a, 'tcx> = (&'a MethodMap<'tcx>, &'a def::ExportMap);
58 /// Result of a checking operation - None => no errors were found. Some => an
59 /// error and contains the span and message for reporting that error and
60 /// optionally the same for a note about the error.
61 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
63 ////////////////////////////////////////////////////////////////////////////////
64 /// The parent visitor, used to determine what's the parent of what (node-wise)
65 ////////////////////////////////////////////////////////////////////////////////
67 struct ParentVisitor {
68 parents: NodeMap<ast::NodeId>,
69 curparent: ast::NodeId,
72 impl<'v> Visitor<'v> for ParentVisitor {
73 fn visit_item(&mut self, item: &ast::Item) {
74 self.parents.insert(item.id, self.curparent);
76 let prev = self.curparent;
78 ast::ItemMod(..) => { self.curparent = item.id; }
79 // Enum variants are parented to the enum definition itself because
80 // they inherit privacy
81 ast::ItemEnum(ref def, _) => {
82 for variant in &def.variants {
83 // The parent is considered the enclosing enum because the
84 // enum will dictate the privacy visibility of this variant
86 self.parents.insert(variant.node.id, item.id);
90 // Trait methods are always considered "public", but if the trait is
91 // private then we need some private item in the chain from the
92 // method to the root. In this case, if the trait is private, then
93 // parent all the methods to the trait to indicate that they're
95 ast::ItemTrait(_, _, _, ref methods) if item.vis != ast::Public => {
98 ast::ProvidedMethod(ref m) => {
99 self.parents.insert(m.id, item.id);
101 ast::RequiredMethod(ref m) => {
102 self.parents.insert(m.id, item.id);
104 ast::TypeTraitItem(_) => {}
111 visit::walk_item(self, item);
112 self.curparent = prev;
115 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
116 self.parents.insert(a.id, self.curparent);
117 visit::walk_foreign_item(self, a);
120 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
121 c: &'v ast::Block, d: Span, id: ast::NodeId) {
122 // We already took care of some trait methods above, otherwise things
123 // like impl methods and pub trait methods are parented to the
124 // containing module, not the containing trait.
125 if !self.parents.contains_key(&id) {
126 self.parents.insert(id, self.curparent);
128 visit::walk_fn(self, a, b, c, d);
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()[ty.id].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 {
284 ast::MethodImplItem(ref method) => {
286 match method.pe_explicit_self().node {
287 ast::SelfStatic => public_ty,
289 } && method.pe_vis() == ast::Public;
290 if meth_public || tr.is_some() {
291 self.exported_items.insert(method.id);
294 ast::TypeImplItem(_) => {}
300 // Default methods on traits are all public so long as the trait
302 ast::ItemTrait(_, _, _, ref methods) if public_first => {
303 for method in methods {
305 ast::ProvidedMethod(ref m) => {
306 debug!("provided {}", m.id);
307 self.exported_items.insert(m.id);
309 ast::RequiredMethod(ref m) => {
310 debug!("required {}", m.id);
311 self.exported_items.insert(m.id);
313 ast::TypeTraitItem(ref t) => {
314 debug!("typedef {}", t.ty_param.id);
315 self.exported_items.insert(t.ty_param.id);
321 // Struct constructors are public if the struct is all public.
322 ast::ItemStruct(ref def, _) if public_first => {
324 Some(id) => { self.exported_items.insert(id); }
327 // fields can be public or private, so lets check
328 for field in &def.fields {
329 let vis = match field.node.kind {
330 ast::NamedField(_, vis) | ast::UnnamedField(vis) => vis
332 if vis == ast::Public {
333 self.public_items.insert(field.node.id);
338 ast::ItemTy(ref ty, _) if public_first => {
339 if let ast::TyPath(..) = ty.node {
340 match self.tcx.def_map.borrow()[ty.id].full_def() {
341 def::DefPrimTy(..) | def::DefTyParam(..) => {},
343 let did = def.def_id();
345 self.exported_items.insert(did.node);
355 visit::walk_item(self, item);
357 self.prev_exported = orig_all_exported;
358 self.prev_public = orig_all_pub;
361 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
362 if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) {
363 self.exported_items.insert(a.id);
367 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) {
368 // This code is here instead of in visit_item so that the
369 // crate module gets processed as well.
370 if self.prev_exported {
371 assert!(self.export_map.contains_key(&id), "wut {}", id);
372 for export in &self.export_map[id] {
373 if is_local(export.def_id) {
374 self.reexports.insert(export.def_id.node);
378 visit::walk_mod(self, m)
382 ////////////////////////////////////////////////////////////////////////////////
383 /// The privacy visitor, where privacy checks take place (violations reported)
384 ////////////////////////////////////////////////////////////////////////////////
386 struct PrivacyVisitor<'a, 'tcx: 'a> {
387 tcx: &'a ty::ctxt<'tcx>,
388 curitem: ast::NodeId,
390 parents: NodeMap<ast::NodeId>,
391 external_exports: ExternalExports,
397 DisallowedBy(ast::NodeId),
401 UnnamedField(uint), // index
402 // (Name, not Ident, because struct fields are not macro-hygienic)
403 NamedField(ast::Name),
406 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
407 // used when debugging
408 fn nodestr(&self, id: ast::NodeId) -> String {
409 self.tcx.map.node_to_string(id).to_string()
412 // Determines whether the given definition is public from the point of view
413 // of the current item.
414 fn def_privacy(&self, did: ast::DefId) -> PrivacyResult {
416 if self.external_exports.contains(&did) {
417 debug!("privacy - {:?} was externally exported", did);
420 debug!("privacy - is {:?} a public method", did);
422 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
423 Some(&ty::MethodTraitItem(ref meth)) => {
424 debug!("privacy - well at least it's a method: {:?}",
426 match meth.container {
427 ty::TraitContainer(id) => {
428 debug!("privacy - recursing on trait {:?}", id);
431 ty::ImplContainer(id) => {
432 match ty::impl_trait_ref(self.tcx, id) {
434 debug!("privacy - impl of trait {:?}", id);
435 self.def_privacy(t.def_id)
438 debug!("privacy - found a method {:?}",
440 if meth.vis == ast::Public {
450 Some(&ty::TypeTraitItem(ref typedef)) => {
451 match typedef.container {
452 ty::TraitContainer(id) => {
453 debug!("privacy - recursing on trait {:?}", id);
456 ty::ImplContainer(id) => {
457 match ty::impl_trait_ref(self.tcx, id) {
459 debug!("privacy - impl of trait {:?}", id);
460 self.def_privacy(t.def_id)
463 debug!("privacy - found a typedef {:?}",
465 if typedef.vis == ast::Public {
476 debug!("privacy - nope, not even a method");
482 debug!("privacy - local {} not public all the way down",
483 self.tcx.map.node_to_string(did.node));
484 // return quickly for things in the same module
485 if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
486 debug!("privacy - same parent, we're done here");
490 // We now know that there is at least one private member between the
491 // destination and the root.
492 let mut closest_private_id = did.node;
494 debug!("privacy - examining {}", self.nodestr(closest_private_id));
495 let vis = match self.tcx.map.find(closest_private_id) {
496 // If this item is a method, then we know for sure that it's an
497 // actual method and not a static method. The reason for this is
498 // that these cases are only hit in the ExprMethodCall
499 // expression, and ExprCall will have its path checked later
500 // (the path of the trait/impl) if it's a static method.
502 // With this information, then we can completely ignore all
503 // trait methods. The privacy violation would be if the trait
504 // couldn't get imported, not if the method couldn't be used
505 // (all trait methods are public).
507 // However, if this is an impl method, then we dictate this
508 // decision solely based on the privacy of the method
510 // FIXME(#10573) is this the right behavior? Why not consider
511 // where the method was defined?
512 Some(ast_map::NodeImplItem(ii)) => {
514 ast::MethodImplItem(ref m) => {
515 let imp = self.tcx.map
516 .get_parent_did(closest_private_id);
517 match ty::impl_trait_ref(self.tcx, imp) {
518 Some(..) => return Allowable,
519 _ if m.pe_vis() == ast::Public => {
525 ast::TypeImplItem(_) => return Allowable,
528 Some(ast_map::NodeTraitItem(_)) => {
532 // This is not a method call, extract the visibility as one
533 // would normally look at it
534 Some(ast_map::NodeItem(it)) => it.vis,
535 Some(ast_map::NodeForeignItem(_)) => {
536 self.tcx.map.get_foreign_vis(closest_private_id)
538 Some(ast_map::NodeVariant(..)) => {
539 ast::Public // need to move up a level (to the enum)
543 if vis != ast::Public { break }
544 // if we've reached the root, then everything was allowable and this
546 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
547 closest_private_id = self.parents[closest_private_id];
549 // If we reached the top, then we were public all the way down and
550 // we can allow this access.
551 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
553 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
554 if self.private_accessible(closest_private_id) {
557 DisallowedBy(closest_private_id)
561 /// For a local private node in the AST, this function will determine
562 /// whether the node is accessible by the current module that iteration is
564 fn private_accessible(&self, id: ast::NodeId) -> bool {
565 let parent = self.parents[id];
566 debug!("privacy - accessible parent {}", self.nodestr(parent));
568 // After finding `did`'s closest private member, we roll ourselves back
569 // to see if this private member's parent is anywhere in our ancestry.
570 // By the privacy rules, we can access all of our ancestor's private
571 // members, so that's why we test the parent, and not the did itself.
572 let mut cur = self.curitem;
574 debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
576 // If the relevant parent is in our history, then we're allowed
577 // to look inside any of our ancestor's immediate private items,
578 // so this access is valid.
579 x if x == parent => return true,
581 // If we've reached the root, then we couldn't access this item
582 // in the first place
583 ast::DUMMY_NODE_ID => return false,
589 cur = self.parents[cur];
593 fn report_error(&self, result: CheckResult) -> bool {
596 Some((span, msg, note)) => {
597 self.tcx.sess.span_err(span, &msg[..]);
599 Some((span, msg)) => {
600 self.tcx.sess.span_note(span, &msg[..])
609 /// Guarantee that a particular definition is public. Returns a CheckResult
610 /// which contains any errors found. These can be reported using `report_error`.
611 /// If the result is `None`, no errors were found.
612 fn ensure_public(&self, span: Span, to_check: ast::DefId,
613 source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
614 let id = match self.def_privacy(to_check) {
615 ExternallyDenied => {
616 return Some((span, format!("{} is private", msg), None))
618 Allowable => return None,
619 DisallowedBy(id) => id,
622 // If we're disallowed by a particular id, then we attempt to give a
623 // nice error message to say why it was disallowed. It was either
624 // because the item itself is private or because its parent is private
625 // and its parent isn't in our ancestry.
626 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
627 return Some((span, format!("{} is private", msg), None));
629 (span, format!("{} is inaccessible", msg))
631 let item = match self.tcx.map.find(id) {
632 Some(ast_map::NodeItem(item)) => {
634 // If an impl disallowed this item, then this is resolve's
635 // way of saying that a struct/enum's static method was
636 // invoked, and the struct/enum itself is private. Crawl
637 // back up the chains to find the relevant struct/enum that
639 ast::ItemImpl(_, _, _, _, ref ty, _) => {
641 ast::TyPath(..) => {}
642 _ => return Some((err_span, err_msg, None)),
644 let def = self.tcx.def_map.borrow()[ty.id].full_def();
645 let did = def.def_id();
646 assert!(is_local(did));
647 match self.tcx.map.get(did.node) {
648 ast_map::NodeItem(item) => item,
649 _ => self.tcx.sess.span_bug(item.span,
650 "path is not an item")
656 Some(..) | None => return Some((err_span, err_msg, None)),
658 let desc = match item.node {
659 ast::ItemMod(..) => "module",
660 ast::ItemTrait(..) => "trait",
661 ast::ItemStruct(..) => "struct",
662 ast::ItemEnum(..) => "enum",
663 _ => return Some((err_span, err_msg, None))
665 let msg = format!("{} `{}` is private", desc,
666 token::get_ident(item.ident));
667 Some((err_span, err_msg, Some((span, msg))))
670 // Checks that a field is in scope.
671 fn check_field(&mut self,
675 let fields = ty::lookup_struct_fields(self.tcx, id);
676 let field = match name {
677 NamedField(f_name) => {
678 debug!("privacy - check named field {} in struct {:?}", f_name, id);
679 fields.iter().find(|f| f.name == f_name).unwrap()
681 UnnamedField(idx) => &fields[idx]
683 if field.vis == ast::Public ||
684 (is_local(field.id) && self.private_accessible(field.id.node)) {
688 let struct_type = ty::lookup_item_type(self.tcx, id).ty;
689 let struct_desc = match struct_type.sty {
690 ty::ty_struct(_, _) =>
691 format!("struct `{}`", ty::item_path_str(self.tcx, id)),
692 // struct variant fields have inherited visibility
693 ty::ty_enum(..) => return,
694 _ => self.tcx.sess.span_bug(span, "can't find struct for field")
696 let msg = match name {
697 NamedField(name) => format!("field `{}` of {} is private",
698 token::get_name(name), struct_desc),
699 UnnamedField(idx) => format!("field #{} of {} is private",
700 idx + 1, struct_desc),
702 self.tcx.sess.span_err(span, &msg[..]);
705 // Given the ID of a method, checks to ensure it's in scope.
706 fn check_static_method(&mut self,
708 method_id: ast::DefId,
710 // If the method is a default method, we need to use the def_id of
711 // the default implementation.
712 let method_id = match ty::impl_or_trait_item(self.tcx, method_id) {
713 ty::MethodTraitItem(method_type) => {
714 method_type.provided_source.unwrap_or(method_id)
716 ty::TypeTraitItem(_) => method_id,
719 let string = token::get_ident(name);
720 self.report_error(self.ensure_public(span,
723 &format!("method `{}`",
727 // Checks that a path is in scope.
728 fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Ident) {
729 debug!("privacy - path {}", self.nodestr(path_id));
730 let path_res = self.tcx.def_map.borrow()[path_id];
731 let ck = |tyname: &str| {
732 let ck_public = |def: ast::DefId| {
733 debug!("privacy - ck_public {:?}", def);
734 let name = token::get_ident(last);
735 let origdid = path_res.def_id();
736 self.ensure_public(span,
739 &format!("{} `{}`", tyname, name))
742 match path_res.last_private {
743 LastMod(AllPublic) => {},
744 LastMod(DependsOn(def)) => {
745 self.report_error(ck_public(def));
747 LastImport { value_priv,
748 value_used: check_value,
750 type_used: check_type } => {
751 // This dance with found_error is because we don't want to
752 // report a privacy error twice for the same directive.
753 let found_error = match (type_priv, check_type) {
754 (Some(DependsOn(def)), Used) => {
755 !self.report_error(ck_public(def))
760 match (value_priv, check_value) {
761 (Some(DependsOn(def)), Used) => {
762 self.report_error(ck_public(def));
767 // If an import is not used in either namespace, we still
768 // want to check that it could be legal. Therefore we check
769 // in both namespaces and only report an error if both would
770 // be illegal. We only report one error, even if it is
771 // illegal to import from both namespaces.
772 match (value_priv, check_value, type_priv, check_type) {
773 (Some(p), Unused, None, _) |
774 (None, _, Some(p), Unused) => {
777 DependsOn(def) => ck_public(def),
780 self.report_error(p);
783 (Some(v), Unused, Some(t), Unused) => {
786 DependsOn(def) => ck_public(def),
790 DependsOn(def) => ck_public(def),
792 if let (Some(_), Some(t)) = (v, t) {
793 self.report_error(Some(t));
801 // FIXME(#12334) Imports can refer to definitions in both the type and
802 // value namespaces. The privacy information is aware of this, but the
803 // def map is not. Therefore the names we work out below will not always
804 // be accurate and we can get slightly wonky error messages (but type
805 // checking is always correct).
806 match path_res.full_def() {
807 def::DefFn(..) => ck("function"),
808 def::DefStatic(..) => ck("static"),
809 def::DefConst(..) => ck("const"),
810 def::DefVariant(..) => ck("variant"),
811 def::DefTy(_, false) => ck("type"),
812 def::DefTy(_, true) => ck("enum"),
813 def::DefTrait(..) => ck("trait"),
814 def::DefStruct(..) => ck("struct"),
815 def::DefMethod(..) => ck("method"),
816 def::DefMod(..) => ck("module"),
821 // Checks that a method is in scope.
822 fn check_method(&mut self, span: Span, origin: &MethodOrigin,
825 MethodStatic(method_id) => {
826 self.check_static_method(span, method_id, ident)
828 MethodStaticClosure(_) => {}
829 // Trait methods are always all public. The only controlling factor
830 // is whether the trait itself is accessible or not.
831 MethodTypeParam(MethodParam { ref trait_ref, .. }) |
832 MethodTraitObject(MethodObject { ref trait_ref, .. }) => {
833 self.report_error(self.ensure_public(span, trait_ref.def_id,
834 None, "source trait"));
840 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
841 fn visit_item(&mut self, item: &ast::Item) {
842 if let ast::ItemUse(ref vpath) = item.node {
843 if let ast::ViewPathList(ref prefix, ref list) = vpath.node {
846 ast::PathListIdent { id, name } => {
847 debug!("privacy - ident item {}", id);
848 self.check_path(pid.span, id, name);
850 ast::PathListMod { id } => {
851 debug!("privacy - mod item {}", id);
852 let name = prefix.segments.last().unwrap().identifier;
853 self.check_path(pid.span, id, name);
859 let orig_curitem = replace(&mut self.curitem, item.id);
860 visit::walk_item(self, item);
861 self.curitem = orig_curitem;
864 fn visit_expr(&mut self, expr: &ast::Expr) {
866 ast::ExprField(ref base, ident) => {
867 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
868 self.check_field(expr.span, id, NamedField(ident.node.name));
871 ast::ExprTupField(ref base, idx) => {
872 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
873 self.check_field(expr.span, id, UnnamedField(idx.node));
876 ast::ExprMethodCall(ident, _, _) => {
877 let method_call = MethodCall::expr(expr.id);
878 match self.tcx.method_map.borrow().get(&method_call) {
880 self.tcx.sess.span_bug(expr.span,
881 "method call not in \
885 debug!("(privacy checking) checking impl method");
886 self.check_method(expr.span, &method.origin, ident.node);
890 ast::ExprStruct(_, ref fields, _) => {
891 match ty::expr_ty(self.tcx, expr).sty {
892 ty::ty_struct(ctor_id, _) => {
893 // RFC 736: ensure all unmentioned fields are visible.
894 // Rather than computing the set of unmentioned fields
895 // (i.e. `all_fields - fields`), just check them all.
896 let all_fields = ty::lookup_struct_fields(self.tcx, ctor_id);
897 for field in all_fields {
898 self.check_field(expr.span, ctor_id,
899 NamedField(field.name));
902 ty::ty_enum(_, _) => {
903 match self.tcx.def_map.borrow()[expr.id].full_def() {
904 def::DefVariant(_, variant_id, _) => {
905 for field in fields {
906 self.check_field(expr.span, variant_id,
907 NamedField(field.ident.node.name));
910 _ => self.tcx.sess.span_bug(expr.span,
917 _ => self.tcx.sess.span_bug(expr.span, "struct expr \
922 ast::ExprPath(..) => {
923 let guard = |did: ast::DefId| {
924 let fields = ty::lookup_struct_fields(self.tcx, did);
925 let any_priv = fields.iter().any(|f| {
926 f.vis != ast::Public && (
928 !self.private_accessible(f.id.node))
931 self.tcx.sess.span_err(expr.span,
932 "cannot invoke tuple struct constructor \
933 with private fields");
936 match self.tcx.def_map.borrow().get(&expr.id).map(|d| d.full_def()) {
937 Some(def::DefStruct(did)) => {
938 guard(if is_local(did) {
939 local_def(self.tcx.map.get_parent(did.node))
941 // "tuple structs" with zero fields (such as
942 // `pub struct Foo;`) don't have a ctor_id, hence
943 // the unwrap_or to the same struct id.
945 csearch::get_tuple_struct_definition_if_ctor(
946 &self.tcx.sess.cstore, did);
947 maybe_did.unwrap_or(did)
956 visit::walk_expr(self, expr);
959 fn visit_pat(&mut self, pattern: &ast::Pat) {
960 // Foreign functions do not have their patterns mapped in the def_map,
961 // and there's nothing really relevant there anyway, so don't bother
962 // checking privacy. If you can name the type then you can pass it to an
963 // external C function anyway.
964 if self.in_foreign { return }
967 ast::PatStruct(_, ref fields, _) => {
968 match ty::pat_ty(self.tcx, pattern).sty {
969 ty::ty_struct(id, _) => {
970 for field in fields {
971 self.check_field(pattern.span, id,
972 NamedField(field.node.ident.name));
975 ty::ty_enum(_, _) => {
976 match self.tcx.def_map.borrow().get(&pattern.id).map(|d| d.full_def()) {
977 Some(def::DefVariant(_, variant_id, _)) => {
978 for field in fields {
979 self.check_field(pattern.span, variant_id,
980 NamedField(field.node.ident.name));
983 _ => self.tcx.sess.span_bug(pattern.span,
990 _ => self.tcx.sess.span_bug(pattern.span,
991 "struct pattern didn't have \
996 // Patterns which bind no fields are allowable (the path is check
998 ast::PatEnum(_, Some(ref fields)) => {
999 match ty::pat_ty(self.tcx, pattern).sty {
1000 ty::ty_struct(id, _) => {
1001 for (i, field) in fields.iter().enumerate() {
1002 if let ast::PatWild(..) = field.node {
1005 self.check_field(field.span, id, UnnamedField(i));
1008 ty::ty_enum(..) => {
1009 // enum fields have no privacy at this time
1018 visit::walk_pat(self, pattern);
1021 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
1022 self.in_foreign = true;
1023 visit::walk_foreign_item(self, fi);
1024 self.in_foreign = false;
1027 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
1028 self.check_path(path.span, id, path.segments.last().unwrap().identifier);
1029 visit::walk_path(self, path);
1033 ////////////////////////////////////////////////////////////////////////////////
1034 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1035 ////////////////////////////////////////////////////////////////////////////////
1037 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1038 tcx: &'a ty::ctxt<'tcx>,
1042 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1043 fn visit_item(&mut self, item: &ast::Item) {
1045 self.check_all_inherited(item);
1047 self.check_sane_privacy(item);
1050 let in_fn = self.in_fn;
1051 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1052 ast::ItemMod(..) => false, // modules turn privacy back on
1053 _ => in_fn, // otherwise we inherit
1055 visit::walk_item(self, item);
1056 self.in_fn = orig_in_fn;
1059 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1060 b: &'v ast::Block, s: Span, _: ast::NodeId) {
1061 // This catches both functions and methods
1062 let orig_in_fn = replace(&mut self.in_fn, true);
1063 visit::walk_fn(self, fk, fd, b, s);
1064 self.in_fn = orig_in_fn;
1068 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1069 /// Validates all of the visibility qualifiers placed on the item given. This
1070 /// ensures that there are no extraneous qualifiers that don't actually do
1071 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1072 /// later on down the road...
1073 fn check_sane_privacy(&self, item: &ast::Item) {
1075 let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
1076 if vis != ast::Inherited {
1077 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1079 tcx.sess.span_note(sp, note);
1084 // implementations of traits don't need visibility qualifiers because
1085 // that's controlled by having the trait in scope.
1086 ast::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1087 check_inherited(item.span, item.vis,
1088 "visibility qualifiers have no effect on trait \
1090 for impl_item in impl_items {
1092 ast::MethodImplItem(ref m) => {
1093 check_inherited(m.span, m.pe_vis(), "");
1095 ast::TypeImplItem(_) => {}
1100 ast::ItemImpl(..) => {
1101 check_inherited(item.span, item.vis,
1102 "place qualifiers on individual methods instead");
1104 ast::ItemForeignMod(..) => {
1105 check_inherited(item.span, item.vis,
1106 "place qualifiers on individual functions \
1110 ast::ItemEnum(ref def, _) => {
1111 for v in &def.variants {
1114 if item.vis == ast::Public {
1115 tcx.sess.span_err(v.span, "unnecessary `pub` \
1119 ast::Inherited => {}
1124 ast::ItemTrait(_, _, _, ref methods) => {
1127 ast::ProvidedMethod(ref m) => {
1128 check_inherited(m.span, m.pe_vis(),
1129 "unnecessary visibility");
1131 ast::RequiredMethod(ref m) => {
1132 check_inherited(m.span, m.vis,
1133 "unnecessary visibility");
1135 ast::TypeTraitItem(_) => {}
1140 ast::ItemDefaultImpl(..) |
1141 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemStruct(..) |
1142 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1143 ast::ItemExternCrate(_) | ast::ItemUse(_) | ast::ItemMac(..) => {}
1147 /// When inside of something like a function or a method, visibility has no
1148 /// control over anything so this forbids any mention of any visibility
1149 fn check_all_inherited(&self, item: &ast::Item) {
1151 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
1152 if vis != ast::Inherited {
1153 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1156 let check_struct = |def: &ast::StructDef| {
1157 for f in &def.fields {
1159 ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
1160 ast::UnnamedField(..) => {}
1164 check_inherited(tcx, item.span, item.vis);
1166 ast::ItemImpl(_, _, _, _, _, ref impl_items) => {
1167 for impl_item in impl_items {
1169 ast::MethodImplItem(ref m) => {
1170 check_inherited(tcx, m.span, m.pe_vis());
1172 ast::TypeImplItem(_) => {}
1176 ast::ItemForeignMod(ref fm) => {
1177 for i in &fm.items {
1178 check_inherited(tcx, i.span, i.vis);
1181 ast::ItemEnum(ref def, _) => {
1182 for v in &def.variants {
1183 check_inherited(tcx, v.span, v.node.vis);
1187 ast::ItemStruct(ref def, _) => check_struct(&**def),
1189 ast::ItemTrait(_, _, _, ref methods) => {
1192 ast::RequiredMethod(..) => {}
1193 ast::ProvidedMethod(ref m) => check_inherited(tcx, m.span,
1195 ast::TypeTraitItem(_) => {}
1200 ast::ItemDefaultImpl(..) | ast::ItemExternCrate(_) | ast::ItemUse(_) |
1201 ast::ItemStatic(..) | ast::ItemConst(..) |
1202 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1203 ast::ItemMac(..) => {}
1208 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1209 tcx: &'a ty::ctxt<'tcx>,
1210 exported_items: &'a ExportedItems,
1211 public_items: &'a PublicItems,
1215 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1216 inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1217 /// whether the type refers to private types.
1218 contains_private: bool,
1219 /// whether we've recurred at all (i.e. if we're pointing at the
1220 /// first type on which visit_ty was called).
1221 at_outer_type: bool,
1222 // whether that first type is a public path.
1223 outer_type_is_public_path: bool,
1226 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1227 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1228 let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) {
1229 // `int` etc. (None doesn't seem to occur.)
1230 None | Some(def::DefPrimTy(..)) => return false,
1231 Some(def) => def.def_id()
1233 // A path can only be private if:
1234 // it's in this crate...
1238 // .. and it corresponds to a private type in the AST (this returns
1239 // None for type parameters)
1240 match self.tcx.map.find(did.node) {
1241 Some(ast_map::NodeItem(ref item)) => item.vis != ast::Public,
1242 Some(_) | None => false,
1246 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1247 // FIXME: this would preferably be using `exported_items`, but all
1248 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1249 self.public_items.contains(&trait_id)
1252 fn check_ty_param_bound(&self,
1253 ty_param_bound: &ast::TyParamBound) {
1254 if let ast::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1255 if !self.tcx.sess.features.borrow().visible_private_types &&
1256 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1257 let span = trait_ref.trait_ref.path.span;
1258 self.tcx.sess.span_err(span,
1259 "private trait in exported type \
1266 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1267 fn visit_ty(&mut self, ty: &ast::Ty) {
1268 if let ast::TyPath(..) = ty.node {
1269 if self.inner.path_is_private_type(ty.id) {
1270 self.contains_private = true;
1271 // found what we're looking for so let's stop
1274 } else if self.at_outer_type {
1275 self.outer_type_is_public_path = true;
1278 self.at_outer_type = false;
1279 visit::walk_ty(self, ty)
1282 // don't want to recurse into [, .. expr]
1283 fn visit_expr(&mut self, _: &ast::Expr) {}
1286 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1287 fn visit_item(&mut self, item: &ast::Item) {
1289 // contents of a private mod can be reexported, so we need
1290 // to check internals.
1291 ast::ItemMod(_) => {}
1293 // An `extern {}` doesn't introduce a new privacy
1294 // namespace (the contents have their own privacies).
1295 ast::ItemForeignMod(_) => {}
1297 ast::ItemTrait(_, _, ref bounds, _) => {
1298 if !self.trait_is_public(item.id) {
1302 for bound in &**bounds {
1303 self.check_ty_param_bound(bound)
1307 // impls need some special handling to try to offer useful
1308 // error messages without (too many) false positives
1309 // (i.e. we could just return here to not check them at
1310 // all, or some worse estimation of whether an impl is
1311 // publicly visible.
1312 ast::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1313 // `impl [... for] Private` is never visible.
1314 let self_contains_private;
1315 // impl [... for] Public<...>, but not `impl [... for]
1316 // ~[Public]` or `(Public,)` etc.
1317 let self_is_public_path;
1319 // check the properties of the Self type:
1321 let mut visitor = CheckTypeForPrivatenessVisitor {
1323 contains_private: false,
1324 at_outer_type: true,
1325 outer_type_is_public_path: false,
1327 visitor.visit_ty(&**self_);
1328 self_contains_private = visitor.contains_private;
1329 self_is_public_path = visitor.outer_type_is_public_path;
1332 // miscellaneous info about the impl
1334 // `true` iff this is `impl Private for ...`.
1335 let not_private_trait =
1336 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1338 let did = ty::trait_ref_to_def_id(self.tcx, tr);
1340 !is_local(did) || self.trait_is_public(did.node)
1343 // `true` iff this is a trait impl or at least one method is public.
1345 // `impl Public { $( fn ...() {} )* }` is not visible.
1347 // This is required over just using the methods' privacy
1348 // directly because we might have `impl<T: Foo<Private>> ...`,
1349 // and we shouldn't warn about the generics if all the methods
1350 // are private (because `T` won't be visible externally).
1351 let trait_or_some_public_method =
1352 trait_ref.is_some() ||
1356 ast::MethodImplItem(ref m) => {
1357 self.exported_items.contains(&m.id)
1359 ast::TypeImplItem(_) => false,
1363 if !self_contains_private &&
1364 not_private_trait &&
1365 trait_or_some_public_method {
1367 visit::walk_generics(self, g);
1371 for impl_item in impl_items {
1373 ast::MethodImplItem(ref method) => {
1374 visit::walk_method_helper(self, &**method)
1376 ast::TypeImplItem(_) => {}
1381 // Any private types in a trait impl fall into three
1383 // 1. mentioned in the trait definition
1384 // 2. mentioned in the type params/generics
1385 // 3. mentioned in the associated types of the impl
1387 // Those in 1. can only occur if the trait is in
1388 // this crate and will've been warned about on the
1389 // trait definition (there's no need to warn twice
1390 // so we don't check the methods).
1392 // Those in 2. are warned via walk_generics and this
1394 visit::walk_path(self, &tr.path);
1396 // Those in 3. are warned with this call.
1397 for impl_item in impl_items {
1399 ast::MethodImplItem(..) => {},
1400 ast::TypeImplItem(ref typedef) => {
1401 self.visit_ty(&typedef.typ);
1407 } else if trait_ref.is_none() && self_is_public_path {
1408 // impl Public<Private> { ... }. Any public static
1409 // methods will be visible as `Public::foo`.
1410 let mut found_pub_static = false;
1411 for impl_item in impl_items {
1413 ast::MethodImplItem(ref method) => {
1414 if method.pe_explicit_self().node ==
1417 .contains(&method.id) {
1418 found_pub_static = true;
1419 visit::walk_method_helper(self, &**method);
1422 ast::TypeImplItem(_) => {}
1425 if found_pub_static {
1426 visit::walk_generics(self, g)
1432 // `type ... = ...;` can contain private types, because
1433 // we're introducing a new name.
1434 ast::ItemTy(..) => return,
1436 // not at all public, so we don't care
1437 _ if !self.exported_items.contains(&item.id) => return,
1442 // we've carefully constructed it so that if we're here, then
1443 // any `visit_ty`'s will be called on things that are in
1444 // public signatures, i.e. things that we're interested in for
1446 visit::walk_item(self, item);
1449 fn visit_generics(&mut self, generics: &ast::Generics) {
1450 for ty_param in &*generics.ty_params {
1451 for bound in &*ty_param.bounds {
1452 self.check_ty_param_bound(bound)
1455 for predicate in &generics.where_clause.predicates {
1457 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
1458 for bound in &*bound_pred.bounds {
1459 self.check_ty_param_bound(bound)
1462 &ast::WherePredicate::RegionPredicate(_) => {}
1463 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
1464 self.visit_ty(&*eq_pred.ty);
1470 fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
1471 if self.exported_items.contains(&item.id) {
1472 visit::walk_foreign_item(self, item)
1476 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1477 b: &'v ast::Block, s: Span, id: ast::NodeId) {
1478 // needs special handling for methods.
1479 if self.exported_items.contains(&id) {
1480 visit::walk_fn(self, fk, fd, b, s);
1484 fn visit_ty(&mut self, t: &ast::Ty) {
1485 if let ast::TyPath(_, ref p) = t.node {
1486 if !self.tcx.sess.features.borrow().visible_private_types &&
1487 self.path_is_private_type(t.id) {
1488 self.tcx.sess.span_err(p.span,
1489 "private type in exported type signature");
1492 visit::walk_ty(self, t)
1495 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
1496 if self.exported_items.contains(&v.node.id) {
1497 self.in_variant = true;
1498 visit::walk_variant(self, v, g);
1499 self.in_variant = false;
1503 fn visit_struct_field(&mut self, s: &ast::StructField) {
1505 ast::NamedField(_, vis) if vis == ast::Public || self.in_variant => {
1506 visit::walk_struct_field(self, s);
1513 // we don't need to introspect into these at all: an
1514 // expression/block context can't possibly contain exported things.
1515 // (Making them no-ops stops us from traversing the whole AST without
1516 // having to be super careful about our `walk_...` calls above.)
1517 fn visit_block(&mut self, _: &ast::Block) {}
1518 fn visit_expr(&mut self, _: &ast::Expr) {}
1521 pub fn check_crate(tcx: &ty::ctxt,
1522 export_map: &def::ExportMap,
1523 external_exports: ExternalExports)
1524 -> (ExportedItems, PublicItems) {
1525 let krate = tcx.map.krate();
1527 // Figure out who everyone's parent is
1528 let mut visitor = ParentVisitor {
1530 curparent: ast::DUMMY_NODE_ID,
1532 visit::walk_crate(&mut visitor, krate);
1534 // Use the parent map to check the privacy of everything
1535 let mut visitor = PrivacyVisitor {
1536 curitem: ast::DUMMY_NODE_ID,
1539 parents: visitor.parents,
1540 external_exports: external_exports,
1542 visit::walk_crate(&mut visitor, krate);
1544 // Sanity check to make sure that all privacy usage and controls are
1546 let mut visitor = SanePrivacyVisitor {
1550 visit::walk_crate(&mut visitor, krate);
1552 tcx.sess.abort_if_errors();
1554 // Build up a set of all exported items in the AST. This is a set of all
1555 // items which are reachable from external crates based on visibility.
1556 let mut visitor = EmbargoVisitor {
1558 exported_items: NodeSet(),
1559 public_items: NodeSet(),
1560 reexports: NodeSet(),
1561 export_map: export_map,
1562 prev_exported: true,
1566 let before = visitor.exported_items.len();
1567 visit::walk_crate(&mut visitor, krate);
1568 if before == visitor.exported_items.len() {
1573 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1576 let mut visitor = VisiblePrivateTypesVisitor {
1578 exported_items: &exported_items,
1579 public_items: &public_items,
1582 visit::walk_crate(&mut visitor, krate);
1584 return (exported_items, public_items);