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};
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 trait_items) if item.vis != ast::Public => {
96 for trait_item in trait_items {
97 self.parents.insert(trait_item.id, item.id);
103 visit::walk_item(self, item);
104 self.curparent = prev;
107 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
108 self.parents.insert(a.id, self.curparent);
109 visit::walk_foreign_item(self, a);
112 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
113 c: &'v ast::Block, d: Span, id: ast::NodeId) {
114 // We already took care of some trait methods above, otherwise things
115 // like impl methods and pub trait methods are parented to the
116 // containing module, not the containing trait.
117 if !self.parents.contains_key(&id) {
118 self.parents.insert(id, self.curparent);
120 visit::walk_fn(self, a, b, c, d);
123 fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
124 _: &'v ast::Generics, n: ast::NodeId) {
125 // Struct constructors are parented to their struct definitions because
126 // they essentially are the struct definitions.
128 Some(id) => { self.parents.insert(id, n); }
132 // While we have the id of the struct definition, go ahead and parent
134 for field in &s.fields {
135 self.parents.insert(field.node.id, self.curparent);
137 visit::walk_struct_def(self, s)
141 ////////////////////////////////////////////////////////////////////////////////
142 /// The embargo visitor, used to determine the exports of the ast
143 ////////////////////////////////////////////////////////////////////////////////
145 struct EmbargoVisitor<'a, 'tcx: 'a> {
146 tcx: &'a ty::ctxt<'tcx>,
147 export_map: &'a def::ExportMap,
149 // This flag is an indicator of whether the previous item in the
150 // hierarchical chain was exported or not. This is the indicator of whether
151 // children should be exported as well. Note that this can flip from false
152 // to true if a reexported module is entered (or an action similar).
155 // This is a list of all exported items in the AST. An exported item is any
156 // function/method/item which is usable by external crates. This essentially
157 // means that the result is "public all the way down", but the "path down"
158 // may jump across private boundaries through reexport statements.
159 exported_items: ExportedItems,
161 // This sets contains all the destination nodes which are publicly
162 // re-exported. This is *not* a set of all reexported nodes, only a set of
163 // all nodes which are reexported *and* reachable from external crates. This
164 // means that the destination of the reexport is exported, and hence the
165 // destination must also be exported.
168 // These two fields are closely related to one another in that they are only
169 // used for generation of the 'PublicItems' set, not for privacy checking at
171 public_items: PublicItems,
175 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
176 // There are checks inside of privacy which depend on knowing whether a
177 // trait should be exported or not. The two current consumers of this are:
179 // 1. Should default methods of a trait be exported?
180 // 2. Should the methods of an implementation of a trait be exported?
182 // The answer to both of these questions partly rely on whether the trait
183 // itself is exported or not. If the trait is somehow exported, then the
184 // answers to both questions must be yes. Right now this question involves
185 // more analysis than is currently done in rustc, so we conservatively
186 // answer "yes" so that all traits need to be exported.
187 fn exported_trait(&self, _id: ast::NodeId) -> bool {
192 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
193 fn visit_item(&mut self, item: &ast::Item) {
194 let orig_all_pub = self.prev_public;
195 self.prev_public = orig_all_pub && item.vis == ast::Public;
196 if self.prev_public {
197 self.public_items.insert(item.id);
200 let orig_all_exported = self.prev_exported;
202 // impls/extern blocks do not break the "public chain" because they
203 // cannot have visibility qualifiers on them anyway
204 ast::ItemImpl(..) | ast::ItemDefaultImpl(..) | ast::ItemForeignMod(..) => {}
206 // Traits are a little special in that even if they themselves are
207 // not public they may still be exported.
208 ast::ItemTrait(..) => {
209 self.prev_exported = self.exported_trait(item.id);
212 // Private by default, hence we only retain the "public chain" if
213 // `pub` is explicitly listed.
216 (orig_all_exported && item.vis == ast::Public) ||
217 self.reexports.contains(&item.id);
221 let public_first = self.prev_exported &&
222 self.exported_items.insert(item.id);
225 // Enum variants inherit from their parent, so if the enum is
226 // public all variants are public unless they're explicitly priv
227 ast::ItemEnum(ref def, _) if public_first => {
228 for variant in &def.variants {
229 self.exported_items.insert(variant.node.id);
230 self.public_items.insert(variant.node.id);
234 // Implementations are a little tricky to determine what's exported
235 // out of them. Here's a few cases which are currently defined:
237 // * Impls for private types do not need to export their methods
238 // (either public or private methods)
240 // * Impls for public types only have public methods exported
242 // * Public trait impls for public types must have all methods
245 // * Private trait impls for public types can be ignored
247 // * Public trait impls for private types have their methods
248 // exported. I'm not entirely certain that this is the correct
249 // thing to do, but I have seen use cases of where this will cause
250 // undefined symbols at linkage time if this case is not handled.
252 // * Private trait impls for private types can be completely ignored
253 ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
254 let public_ty = match ty.node {
256 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
257 def::DefPrimTy(..) => true,
259 let did = def.def_id();
261 self.exported_items.contains(&did.node)
267 let tr = ty::impl_trait_ref(self.tcx, local_def(item.id));
268 let public_trait = tr.clone().map_or(false, |tr| {
269 !is_local(tr.def_id) ||
270 self.exported_items.contains(&tr.def_id.node)
273 if public_ty || public_trait {
274 for impl_item in impl_items {
275 match impl_item.node {
276 ast::MethodImplItem(ref sig, _) => {
277 let meth_public = match sig.explicit_self.node {
278 ast::SelfStatic => public_ty,
280 } && impl_item.vis == ast::Public;
281 if meth_public || tr.is_some() {
282 self.exported_items.insert(impl_item.id);
285 ast::TypeImplItem(_) |
286 ast::MacImplItem(_) => {}
292 // Default methods on traits are all public so long as the trait
294 ast::ItemTrait(_, _, _, ref trait_items) if public_first => {
295 for trait_item in trait_items {
296 debug!("trait item {}", trait_item.id);
297 self.exported_items.insert(trait_item.id);
301 // Struct constructors are public if the struct is all public.
302 ast::ItemStruct(ref def, _) if public_first => {
304 Some(id) => { self.exported_items.insert(id); }
307 // fields can be public or private, so lets check
308 for field in &def.fields {
309 let vis = match field.node.kind {
310 ast::NamedField(_, vis) | ast::UnnamedField(vis) => vis
312 if vis == ast::Public {
313 self.public_items.insert(field.node.id);
318 ast::ItemTy(ref ty, _) if public_first => {
319 if let ast::TyPath(..) = ty.node {
320 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
321 def::DefPrimTy(..) | def::DefTyParam(..) => {},
323 let did = def.def_id();
325 self.exported_items.insert(did.node);
335 visit::walk_item(self, item);
337 self.prev_exported = orig_all_exported;
338 self.prev_public = orig_all_pub;
341 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
342 if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) {
343 self.exported_items.insert(a.id);
347 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) {
348 // This code is here instead of in visit_item so that the
349 // crate module gets processed as well.
350 if self.prev_exported {
351 assert!(self.export_map.contains_key(&id), "wut {}", id);
352 for export in self.export_map.get(&id).unwrap() {
353 if is_local(export.def_id) {
354 self.reexports.insert(export.def_id.node);
358 visit::walk_mod(self, m)
362 ////////////////////////////////////////////////////////////////////////////////
363 /// The privacy visitor, where privacy checks take place (violations reported)
364 ////////////////////////////////////////////////////////////////////////////////
366 struct PrivacyVisitor<'a, 'tcx: 'a> {
367 tcx: &'a ty::ctxt<'tcx>,
368 curitem: ast::NodeId,
370 parents: NodeMap<ast::NodeId>,
371 external_exports: ExternalExports,
377 DisallowedBy(ast::NodeId),
381 UnnamedField(uint), // index
382 // (Name, not Ident, because struct fields are not macro-hygienic)
383 NamedField(ast::Name),
386 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
387 // used when debugging
388 fn nodestr(&self, id: ast::NodeId) -> String {
389 self.tcx.map.node_to_string(id).to_string()
392 // Determines whether the given definition is public from the point of view
393 // of the current item.
394 fn def_privacy(&self, did: ast::DefId) -> PrivacyResult {
396 if self.external_exports.contains(&did) {
397 debug!("privacy - {:?} was externally exported", did);
400 debug!("privacy - is {:?} a public method", did);
402 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
403 Some(&ty::MethodTraitItem(ref meth)) => {
404 debug!("privacy - well at least it's a method: {:?}",
406 match meth.container {
407 ty::TraitContainer(id) => {
408 debug!("privacy - recursing on trait {:?}", id);
411 ty::ImplContainer(id) => {
412 match ty::impl_trait_ref(self.tcx, id) {
414 debug!("privacy - impl of trait {:?}", id);
415 self.def_privacy(t.def_id)
418 debug!("privacy - found a method {:?}",
420 if meth.vis == ast::Public {
430 Some(&ty::TypeTraitItem(ref typedef)) => {
431 match typedef.container {
432 ty::TraitContainer(id) => {
433 debug!("privacy - recursing on trait {:?}", id);
436 ty::ImplContainer(id) => {
437 match ty::impl_trait_ref(self.tcx, id) {
439 debug!("privacy - impl of trait {:?}", id);
440 self.def_privacy(t.def_id)
443 debug!("privacy - found a typedef {:?}",
445 if typedef.vis == ast::Public {
456 debug!("privacy - nope, not even a method");
462 debug!("privacy - local {} not public all the way down",
463 self.tcx.map.node_to_string(did.node));
464 // return quickly for things in the same module
465 if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
466 debug!("privacy - same parent, we're done here");
470 // We now know that there is at least one private member between the
471 // destination and the root.
472 let mut closest_private_id = did.node;
474 debug!("privacy - examining {}", self.nodestr(closest_private_id));
475 let vis = match self.tcx.map.find(closest_private_id) {
476 // If this item is a method, then we know for sure that it's an
477 // actual method and not a static method. The reason for this is
478 // that these cases are only hit in the ExprMethodCall
479 // expression, and ExprCall will have its path checked later
480 // (the path of the trait/impl) if it's a static method.
482 // With this information, then we can completely ignore all
483 // trait methods. The privacy violation would be if the trait
484 // couldn't get imported, not if the method couldn't be used
485 // (all trait methods are public).
487 // However, if this is an impl method, then we dictate this
488 // decision solely based on the privacy of the method
490 // FIXME(#10573) is this the right behavior? Why not consider
491 // where the method was defined?
492 Some(ast_map::NodeImplItem(ii)) => {
494 ast::MethodImplItem(..) => {
495 let imp = self.tcx.map
496 .get_parent_did(closest_private_id);
497 match ty::impl_trait_ref(self.tcx, imp) {
498 Some(..) => return Allowable,
499 _ if ii.vis == ast::Public => {
505 ast::TypeImplItem(_) |
506 ast::MacImplItem(_) => return Allowable,
509 Some(ast_map::NodeTraitItem(_)) => {
513 // This is not a method call, extract the visibility as one
514 // would normally look at it
515 Some(ast_map::NodeItem(it)) => it.vis,
516 Some(ast_map::NodeForeignItem(_)) => {
517 self.tcx.map.get_foreign_vis(closest_private_id)
519 Some(ast_map::NodeVariant(..)) => {
520 ast::Public // need to move up a level (to the enum)
524 if vis != ast::Public { break }
525 // if we've reached the root, then everything was allowable and this
527 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
528 closest_private_id = *self.parents.get(&closest_private_id).unwrap();
530 // If we reached the top, then we were public all the way down and
531 // we can allow this access.
532 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
534 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
535 if self.private_accessible(closest_private_id) {
538 DisallowedBy(closest_private_id)
542 /// For a local private node in the AST, this function will determine
543 /// whether the node is accessible by the current module that iteration is
545 fn private_accessible(&self, id: ast::NodeId) -> bool {
546 let parent = *self.parents.get(&id).unwrap();
547 debug!("privacy - accessible parent {}", self.nodestr(parent));
549 // After finding `did`'s closest private member, we roll ourselves back
550 // to see if this private member's parent is anywhere in our ancestry.
551 // By the privacy rules, we can access all of our ancestor's private
552 // members, so that's why we test the parent, and not the did itself.
553 let mut cur = self.curitem;
555 debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
557 // If the relevant parent is in our history, then we're allowed
558 // to look inside any of our ancestor's immediate private items,
559 // so this access is valid.
560 x if x == parent => return true,
562 // If we've reached the root, then we couldn't access this item
563 // in the first place
564 ast::DUMMY_NODE_ID => return false,
570 cur = *self.parents.get(&cur).unwrap();
574 fn report_error(&self, result: CheckResult) -> bool {
577 Some((span, msg, note)) => {
578 self.tcx.sess.span_err(span, &msg[..]);
580 Some((span, msg)) => {
581 self.tcx.sess.span_note(span, &msg[..])
590 /// Guarantee that a particular definition is public. Returns a CheckResult
591 /// which contains any errors found. These can be reported using `report_error`.
592 /// If the result is `None`, no errors were found.
593 fn ensure_public(&self, span: Span, to_check: ast::DefId,
594 source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
595 let id = match self.def_privacy(to_check) {
596 ExternallyDenied => {
597 return Some((span, format!("{} is private", msg), None))
599 Allowable => return None,
600 DisallowedBy(id) => id,
603 // If we're disallowed by a particular id, then we attempt to give a
604 // nice error message to say why it was disallowed. It was either
605 // because the item itself is private or because its parent is private
606 // and its parent isn't in our ancestry.
607 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
608 return Some((span, format!("{} is private", msg), None));
610 (span, format!("{} is inaccessible", msg))
612 let item = match self.tcx.map.find(id) {
613 Some(ast_map::NodeItem(item)) => {
615 // If an impl disallowed this item, then this is resolve's
616 // way of saying that a struct/enum's static method was
617 // invoked, and the struct/enum itself is private. Crawl
618 // back up the chains to find the relevant struct/enum that
620 ast::ItemImpl(_, _, _, _, ref ty, _) => {
622 ast::TyPath(..) => {}
623 _ => return Some((err_span, err_msg, None)),
625 let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
626 let did = def.def_id();
627 assert!(is_local(did));
628 match self.tcx.map.get(did.node) {
629 ast_map::NodeItem(item) => item,
630 _ => self.tcx.sess.span_bug(item.span,
631 "path is not an item")
637 Some(..) | None => return Some((err_span, err_msg, None)),
639 let desc = match item.node {
640 ast::ItemMod(..) => "module",
641 ast::ItemTrait(..) => "trait",
642 ast::ItemStruct(..) => "struct",
643 ast::ItemEnum(..) => "enum",
644 _ => return Some((err_span, err_msg, None))
646 let msg = format!("{} `{}` is private", desc,
647 token::get_ident(item.ident));
648 Some((err_span, err_msg, Some((span, msg))))
651 // Checks that a field is in scope.
652 fn check_field(&mut self,
656 let fields = ty::lookup_struct_fields(self.tcx, id);
657 let field = match name {
658 NamedField(f_name) => {
659 debug!("privacy - check named field {} in struct {:?}", f_name, id);
660 fields.iter().find(|f| f.name == f_name).unwrap()
662 UnnamedField(idx) => &fields[idx]
664 if field.vis == ast::Public ||
665 (is_local(field.id) && self.private_accessible(field.id.node)) {
669 let struct_type = ty::lookup_item_type(self.tcx, id).ty;
670 let struct_desc = match struct_type.sty {
671 ty::ty_struct(_, _) =>
672 format!("struct `{}`", ty::item_path_str(self.tcx, id)),
673 // struct variant fields have inherited visibility
674 ty::ty_enum(..) => return,
675 _ => self.tcx.sess.span_bug(span, "can't find struct for field")
677 let msg = match name {
678 NamedField(name) => format!("field `{}` of {} is private",
679 token::get_name(name), struct_desc),
680 UnnamedField(idx) => format!("field #{} of {} is private",
681 idx + 1, struct_desc),
683 self.tcx.sess.span_err(span, &msg[..]);
686 // Given the ID of a method, checks to ensure it's in scope.
687 fn check_static_method(&mut self,
689 method_id: ast::DefId,
691 // If the method is a default method, we need to use the def_id of
692 // the default implementation.
693 let method_id = match ty::impl_or_trait_item(self.tcx, method_id) {
694 ty::MethodTraitItem(method_type) => {
695 method_type.provided_source.unwrap_or(method_id)
697 ty::TypeTraitItem(_) => method_id,
700 let string = token::get_ident(name);
701 self.report_error(self.ensure_public(span,
704 &format!("method `{}`",
708 // Checks that a path is in scope.
709 fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Ident) {
710 debug!("privacy - path {}", self.nodestr(path_id));
711 let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap();
712 let ck = |tyname: &str| {
713 let ck_public = |def: ast::DefId| {
714 debug!("privacy - ck_public {:?}", def);
715 let name = token::get_ident(last);
716 let origdid = path_res.def_id();
717 self.ensure_public(span,
720 &format!("{} `{}`", tyname, name))
723 match path_res.last_private {
724 LastMod(AllPublic) => {},
725 LastMod(DependsOn(def)) => {
726 self.report_error(ck_public(def));
728 LastImport { value_priv,
729 value_used: check_value,
731 type_used: check_type } => {
732 // This dance with found_error is because we don't want to
733 // report a privacy error twice for the same directive.
734 let found_error = match (type_priv, check_type) {
735 (Some(DependsOn(def)), Used) => {
736 !self.report_error(ck_public(def))
741 match (value_priv, check_value) {
742 (Some(DependsOn(def)), Used) => {
743 self.report_error(ck_public(def));
748 // If an import is not used in either namespace, we still
749 // want to check that it could be legal. Therefore we check
750 // in both namespaces and only report an error if both would
751 // be illegal. We only report one error, even if it is
752 // illegal to import from both namespaces.
753 match (value_priv, check_value, type_priv, check_type) {
754 (Some(p), Unused, None, _) |
755 (None, _, Some(p), Unused) => {
758 DependsOn(def) => ck_public(def),
761 self.report_error(p);
764 (Some(v), Unused, Some(t), Unused) => {
767 DependsOn(def) => ck_public(def),
771 DependsOn(def) => ck_public(def),
773 if let (Some(_), Some(t)) = (v, t) {
774 self.report_error(Some(t));
782 // FIXME(#12334) Imports can refer to definitions in both the type and
783 // value namespaces. The privacy information is aware of this, but the
784 // def map is not. Therefore the names we work out below will not always
785 // be accurate and we can get slightly wonky error messages (but type
786 // checking is always correct).
787 match path_res.full_def() {
788 def::DefFn(..) => ck("function"),
789 def::DefStatic(..) => ck("static"),
790 def::DefConst(..) => ck("const"),
791 def::DefVariant(..) => ck("variant"),
792 def::DefTy(_, false) => ck("type"),
793 def::DefTy(_, true) => ck("enum"),
794 def::DefTrait(..) => ck("trait"),
795 def::DefStruct(..) => ck("struct"),
796 def::DefMethod(..) => ck("method"),
797 def::DefMod(..) => ck("module"),
802 // Checks that a method is in scope.
803 fn check_method(&mut self, span: Span, origin: &MethodOrigin,
806 MethodStatic(method_id) => {
807 self.check_static_method(span, method_id, ident)
809 MethodStaticClosure(_) => {}
810 // Trait methods are always all public. The only controlling factor
811 // is whether the trait itself is accessible or not.
812 MethodTypeParam(MethodParam { ref trait_ref, .. }) |
813 MethodTraitObject(MethodObject { ref trait_ref, .. }) => {
814 self.report_error(self.ensure_public(span, trait_ref.def_id,
815 None, "source trait"));
821 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
822 fn visit_item(&mut self, item: &ast::Item) {
823 if let ast::ItemUse(ref vpath) = item.node {
824 if let ast::ViewPathList(ref prefix, ref list) = vpath.node {
827 ast::PathListIdent { id, name } => {
828 debug!("privacy - ident item {}", id);
829 self.check_path(pid.span, id, name);
831 ast::PathListMod { id } => {
832 debug!("privacy - mod item {}", id);
833 let name = prefix.segments.last().unwrap().identifier;
834 self.check_path(pid.span, id, name);
840 let orig_curitem = replace(&mut self.curitem, item.id);
841 visit::walk_item(self, item);
842 self.curitem = orig_curitem;
845 fn visit_expr(&mut self, expr: &ast::Expr) {
847 ast::ExprField(ref base, ident) => {
848 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
849 self.check_field(expr.span, id, NamedField(ident.node.name));
852 ast::ExprTupField(ref base, idx) => {
853 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
854 self.check_field(expr.span, id, UnnamedField(idx.node));
857 ast::ExprMethodCall(ident, _, _) => {
858 let method_call = MethodCall::expr(expr.id);
859 match self.tcx.method_map.borrow().get(&method_call) {
861 self.tcx.sess.span_bug(expr.span,
862 "method call not in \
866 debug!("(privacy checking) checking impl method");
867 self.check_method(expr.span, &method.origin, ident.node);
871 ast::ExprStruct(_, ref fields, _) => {
872 match ty::expr_ty(self.tcx, expr).sty {
873 ty::ty_struct(ctor_id, _) => {
874 // RFC 736: ensure all unmentioned fields are visible.
875 // Rather than computing the set of unmentioned fields
876 // (i.e. `all_fields - fields`), just check them all.
877 let all_fields = ty::lookup_struct_fields(self.tcx, ctor_id);
878 for field in all_fields {
879 self.check_field(expr.span, ctor_id,
880 NamedField(field.name));
883 ty::ty_enum(_, _) => {
884 match self.tcx.def_map.borrow().get(&expr.id).unwrap().full_def() {
885 def::DefVariant(_, variant_id, _) => {
886 for field in fields {
887 self.check_field(expr.span, variant_id,
888 NamedField(field.ident.node.name));
891 _ => self.tcx.sess.span_bug(expr.span,
898 _ => self.tcx.sess.span_bug(expr.span, "struct expr \
903 ast::ExprPath(..) => {
904 let guard = |did: ast::DefId| {
905 let fields = ty::lookup_struct_fields(self.tcx, did);
906 let any_priv = fields.iter().any(|f| {
907 f.vis != ast::Public && (
909 !self.private_accessible(f.id.node))
912 self.tcx.sess.span_err(expr.span,
913 "cannot invoke tuple struct constructor \
914 with private fields");
917 match self.tcx.def_map.borrow().get(&expr.id).map(|d| d.full_def()) {
918 Some(def::DefStruct(did)) => {
919 guard(if is_local(did) {
920 local_def(self.tcx.map.get_parent(did.node))
922 // "tuple structs" with zero fields (such as
923 // `pub struct Foo;`) don't have a ctor_id, hence
924 // the unwrap_or to the same struct id.
926 csearch::get_tuple_struct_definition_if_ctor(
927 &self.tcx.sess.cstore, did);
928 maybe_did.unwrap_or(did)
937 visit::walk_expr(self, expr);
940 fn visit_pat(&mut self, pattern: &ast::Pat) {
941 // Foreign functions do not have their patterns mapped in the def_map,
942 // and there's nothing really relevant there anyway, so don't bother
943 // checking privacy. If you can name the type then you can pass it to an
944 // external C function anyway.
945 if self.in_foreign { return }
948 ast::PatStruct(_, ref fields, _) => {
949 match ty::pat_ty(self.tcx, pattern).sty {
950 ty::ty_struct(id, _) => {
951 for field in fields {
952 self.check_field(pattern.span, id,
953 NamedField(field.node.ident.name));
956 ty::ty_enum(_, _) => {
957 match self.tcx.def_map.borrow().get(&pattern.id).map(|d| d.full_def()) {
958 Some(def::DefVariant(_, variant_id, _)) => {
959 for field in fields {
960 self.check_field(pattern.span, variant_id,
961 NamedField(field.node.ident.name));
964 _ => self.tcx.sess.span_bug(pattern.span,
971 _ => self.tcx.sess.span_bug(pattern.span,
972 "struct pattern didn't have \
977 // Patterns which bind no fields are allowable (the path is check
979 ast::PatEnum(_, Some(ref fields)) => {
980 match ty::pat_ty(self.tcx, pattern).sty {
981 ty::ty_struct(id, _) => {
982 for (i, field) in fields.iter().enumerate() {
983 if let ast::PatWild(..) = field.node {
986 self.check_field(field.span, id, UnnamedField(i));
990 // enum fields have no privacy at this time
999 visit::walk_pat(self, pattern);
1002 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
1003 self.in_foreign = true;
1004 visit::walk_foreign_item(self, fi);
1005 self.in_foreign = false;
1008 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
1009 self.check_path(path.span, id, path.segments.last().unwrap().identifier);
1010 visit::walk_path(self, path);
1014 ////////////////////////////////////////////////////////////////////////////////
1015 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1016 ////////////////////////////////////////////////////////////////////////////////
1018 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1019 tcx: &'a ty::ctxt<'tcx>,
1023 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1024 fn visit_item(&mut self, item: &ast::Item) {
1026 self.check_all_inherited(item);
1028 self.check_sane_privacy(item);
1031 let in_fn = self.in_fn;
1032 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1033 ast::ItemMod(..) => false, // modules turn privacy back on
1034 _ => in_fn, // otherwise we inherit
1036 visit::walk_item(self, item);
1037 self.in_fn = orig_in_fn;
1040 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1041 b: &'v ast::Block, s: Span, _: ast::NodeId) {
1042 // This catches both functions and methods
1043 let orig_in_fn = replace(&mut self.in_fn, true);
1044 visit::walk_fn(self, fk, fd, b, s);
1045 self.in_fn = orig_in_fn;
1049 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1050 /// Validates all of the visibility qualifiers placed on the item given. This
1051 /// ensures that there are no extraneous qualifiers that don't actually do
1052 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1053 /// later on down the road...
1054 fn check_sane_privacy(&self, item: &ast::Item) {
1056 let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
1057 if vis != ast::Inherited {
1058 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1060 tcx.sess.span_note(sp, note);
1065 // implementations of traits don't need visibility qualifiers because
1066 // that's controlled by having the trait in scope.
1067 ast::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1068 check_inherited(item.span, item.vis,
1069 "visibility qualifiers have no effect on trait \
1071 for impl_item in impl_items {
1072 check_inherited(impl_item.span, impl_item.vis, "");
1076 ast::ItemImpl(..) => {
1077 check_inherited(item.span, item.vis,
1078 "place qualifiers on individual methods instead");
1080 ast::ItemForeignMod(..) => {
1081 check_inherited(item.span, item.vis,
1082 "place qualifiers on individual functions \
1086 ast::ItemEnum(ref def, _) => {
1087 for v in &def.variants {
1090 if item.vis == ast::Public {
1091 tcx.sess.span_err(v.span, "unnecessary `pub` \
1095 ast::Inherited => {}
1100 ast::ItemTrait(..) | ast::ItemDefaultImpl(..) |
1101 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemStruct(..) |
1102 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1103 ast::ItemExternCrate(_) | ast::ItemUse(_) | ast::ItemMac(..) => {}
1107 /// When inside of something like a function or a method, visibility has no
1108 /// control over anything so this forbids any mention of any visibility
1109 fn check_all_inherited(&self, item: &ast::Item) {
1111 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
1112 if vis != ast::Inherited {
1113 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1116 let check_struct = |def: &ast::StructDef| {
1117 for f in &def.fields {
1119 ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
1120 ast::UnnamedField(..) => {}
1124 check_inherited(tcx, item.span, item.vis);
1126 ast::ItemImpl(_, _, _, _, _, ref impl_items) => {
1127 for impl_item in impl_items {
1128 match impl_item.node {
1129 ast::MethodImplItem(..) => {
1130 check_inherited(tcx, impl_item.span, impl_item.vis);
1132 ast::TypeImplItem(_) |
1133 ast::MacImplItem(_) => {}
1137 ast::ItemForeignMod(ref fm) => {
1138 for i in &fm.items {
1139 check_inherited(tcx, i.span, i.vis);
1142 ast::ItemEnum(ref def, _) => {
1143 for v in &def.variants {
1144 check_inherited(tcx, v.span, v.node.vis);
1148 ast::ItemStruct(ref def, _) => check_struct(&**def),
1150 ast::ItemExternCrate(_) | ast::ItemUse(_) |
1151 ast::ItemTrait(..) | ast::ItemDefaultImpl(..) |
1152 ast::ItemStatic(..) | ast::ItemConst(..) |
1153 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1154 ast::ItemMac(..) => {}
1159 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1160 tcx: &'a ty::ctxt<'tcx>,
1161 exported_items: &'a ExportedItems,
1162 public_items: &'a PublicItems,
1166 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1167 inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1168 /// whether the type refers to private types.
1169 contains_private: bool,
1170 /// whether we've recurred at all (i.e. if we're pointing at the
1171 /// first type on which visit_ty was called).
1172 at_outer_type: bool,
1173 // whether that first type is a public path.
1174 outer_type_is_public_path: bool,
1177 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1178 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1179 let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) {
1180 // `int` etc. (None doesn't seem to occur.)
1181 None | Some(def::DefPrimTy(..)) => return false,
1182 Some(def) => def.def_id()
1184 // A path can only be private if:
1185 // it's in this crate...
1190 // .. and it corresponds to a private type in the AST (this returns
1191 // None for type parameters)
1192 match self.tcx.map.find(did.node) {
1193 Some(ast_map::NodeItem(ref item)) => item.vis != ast::Public,
1194 Some(_) | None => false,
1198 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1199 // FIXME: this would preferably be using `exported_items`, but all
1200 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1201 self.public_items.contains(&trait_id)
1204 fn check_ty_param_bound(&self,
1205 ty_param_bound: &ast::TyParamBound) {
1206 if let ast::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1207 if !self.tcx.sess.features.borrow().visible_private_types &&
1208 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1209 let span = trait_ref.trait_ref.path.span;
1210 self.tcx.sess.span_err(span, "private trait in exported type \
1216 fn item_is_public(&self, id: &ast::NodeId, vis: ast::Visibility) -> bool {
1217 self.exported_items.contains(id) || vis == ast::Public
1221 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1222 fn visit_ty(&mut self, ty: &ast::Ty) {
1223 if let ast::TyPath(..) = ty.node {
1224 if self.inner.path_is_private_type(ty.id) {
1225 self.contains_private = true;
1226 // found what we're looking for so let's stop
1229 } else if self.at_outer_type {
1230 self.outer_type_is_public_path = true;
1233 self.at_outer_type = false;
1234 visit::walk_ty(self, ty)
1237 // don't want to recurse into [, .. expr]
1238 fn visit_expr(&mut self, _: &ast::Expr) {}
1241 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1242 fn visit_item(&mut self, item: &ast::Item) {
1244 // contents of a private mod can be reexported, so we need
1245 // to check internals.
1246 ast::ItemMod(_) => {}
1248 // An `extern {}` doesn't introduce a new privacy
1249 // namespace (the contents have their own privacies).
1250 ast::ItemForeignMod(_) => {}
1252 ast::ItemTrait(_, _, ref bounds, _) => {
1253 if !self.trait_is_public(item.id) {
1257 for bound in &**bounds {
1258 self.check_ty_param_bound(bound)
1262 // impls need some special handling to try to offer useful
1263 // error messages without (too many) false positives
1264 // (i.e. we could just return here to not check them at
1265 // all, or some worse estimation of whether an impl is
1266 // publicly visible).
1267 ast::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1268 // `impl [... for] Private` is never visible.
1269 let self_contains_private;
1270 // impl [... for] Public<...>, but not `impl [... for]
1271 // ~[Public]` or `(Public,)` etc.
1272 let self_is_public_path;
1274 // check the properties of the Self type:
1276 let mut visitor = CheckTypeForPrivatenessVisitor {
1278 contains_private: false,
1279 at_outer_type: true,
1280 outer_type_is_public_path: false,
1282 visitor.visit_ty(&**self_);
1283 self_contains_private = visitor.contains_private;
1284 self_is_public_path = visitor.outer_type_is_public_path;
1287 // miscellaneous info about the impl
1289 // `true` iff this is `impl Private for ...`.
1290 let not_private_trait =
1291 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1293 let did = ty::trait_ref_to_def_id(self.tcx, tr);
1295 !is_local(did) || self.trait_is_public(did.node)
1298 // `true` iff this is a trait impl or at least one method is public.
1300 // `impl Public { $( fn ...() {} )* }` is not visible.
1302 // This is required over just using the methods' privacy
1303 // directly because we might have `impl<T: Foo<Private>> ...`,
1304 // and we shouldn't warn about the generics if all the methods
1305 // are private (because `T` won't be visible externally).
1306 let trait_or_some_public_method =
1307 trait_ref.is_some() ||
1310 match impl_item.node {
1311 ast::MethodImplItem(..) => {
1312 self.exported_items.contains(&impl_item.id)
1314 ast::TypeImplItem(_) |
1315 ast::MacImplItem(_) => false,
1319 if !self_contains_private &&
1320 not_private_trait &&
1321 trait_or_some_public_method {
1323 visit::walk_generics(self, g);
1327 for impl_item in impl_items {
1328 // This is where we choose whether to walk down
1329 // further into the impl to check its items. We
1330 // should only walk into public items so that we
1331 // don't erroneously report errors for private
1332 // types in private items.
1333 match impl_item.node {
1334 ast::MethodImplItem(..)
1335 if self.item_is_public(&impl_item.id, impl_item.vis) =>
1337 visit::walk_impl_item(self, impl_item)
1339 ast::TypeImplItem(..) => {
1340 visit::walk_impl_item(self, impl_item)
1347 // Any private types in a trait impl fall into three
1349 // 1. mentioned in the trait definition
1350 // 2. mentioned in the type params/generics
1351 // 3. mentioned in the associated types of the impl
1353 // Those in 1. can only occur if the trait is in
1354 // this crate and will've been warned about on the
1355 // trait definition (there's no need to warn twice
1356 // so we don't check the methods).
1358 // Those in 2. are warned via walk_generics and this
1360 visit::walk_path(self, &tr.path);
1362 // Those in 3. are warned with this call.
1363 for impl_item in impl_items {
1364 match impl_item.node {
1365 ast::TypeImplItem(ref ty) => {
1368 ast::MethodImplItem(..) |
1369 ast::MacImplItem(_) => {},
1374 } else if trait_ref.is_none() && self_is_public_path {
1375 // impl Public<Private> { ... }. Any public static
1376 // methods will be visible as `Public::foo`.
1377 let mut found_pub_static = false;
1378 for impl_item in impl_items {
1379 match impl_item.node {
1380 ast::MethodImplItem(ref sig, _) => {
1381 if sig.explicit_self.node == ast::SelfStatic &&
1382 self.item_is_public(&impl_item.id, impl_item.vis) {
1383 found_pub_static = true;
1384 visit::walk_impl_item(self, impl_item);
1387 ast::TypeImplItem(_) |
1388 ast::MacImplItem(_) => {}
1391 if found_pub_static {
1392 visit::walk_generics(self, g)
1398 // `type ... = ...;` can contain private types, because
1399 // we're introducing a new name.
1400 ast::ItemTy(..) => return,
1402 // not at all public, so we don't care
1403 _ if !self.item_is_public(&item.id, item.vis) => {
1410 // We've carefully constructed it so that if we're here, then
1411 // any `visit_ty`'s will be called on things that are in
1412 // public signatures, i.e. things that we're interested in for
1414 debug!("VisiblePrivateTypesVisitor entering item {:?}", item);
1415 visit::walk_item(self, item);
1418 fn visit_generics(&mut self, generics: &ast::Generics) {
1419 for ty_param in &*generics.ty_params {
1420 for bound in &*ty_param.bounds {
1421 self.check_ty_param_bound(bound)
1424 for predicate in &generics.where_clause.predicates {
1426 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
1427 for bound in &*bound_pred.bounds {
1428 self.check_ty_param_bound(bound)
1431 &ast::WherePredicate::RegionPredicate(_) => {}
1432 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
1433 self.visit_ty(&*eq_pred.ty);
1439 fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
1440 if self.exported_items.contains(&item.id) {
1441 visit::walk_foreign_item(self, item)
1445 fn visit_ty(&mut self, t: &ast::Ty) {
1446 debug!("VisiblePrivateTypesVisitor checking ty {:?}", t);
1447 if let ast::TyPath(_, ref p) = t.node {
1448 if !self.tcx.sess.features.borrow().visible_private_types &&
1449 self.path_is_private_type(t.id) {
1450 self.tcx.sess.span_err(p.span, "private type in exported type signature");
1453 visit::walk_ty(self, t)
1456 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
1457 if self.exported_items.contains(&v.node.id) {
1458 self.in_variant = true;
1459 visit::walk_variant(self, v, g);
1460 self.in_variant = false;
1464 fn visit_struct_field(&mut self, s: &ast::StructField) {
1466 ast::NamedField(_, vis) if vis == ast::Public || self.in_variant => {
1467 visit::walk_struct_field(self, s);
1474 // we don't need to introspect into these at all: an
1475 // expression/block context can't possibly contain exported things.
1476 // (Making them no-ops stops us from traversing the whole AST without
1477 // having to be super careful about our `walk_...` calls above.)
1478 fn visit_block(&mut self, _: &ast::Block) {}
1479 fn visit_expr(&mut self, _: &ast::Expr) {}
1482 pub fn check_crate(tcx: &ty::ctxt,
1483 export_map: &def::ExportMap,
1484 external_exports: ExternalExports)
1485 -> (ExportedItems, PublicItems) {
1486 let krate = tcx.map.krate();
1488 // Figure out who everyone's parent is
1489 let mut visitor = ParentVisitor {
1491 curparent: ast::DUMMY_NODE_ID,
1493 visit::walk_crate(&mut visitor, krate);
1495 // Use the parent map to check the privacy of everything
1496 let mut visitor = PrivacyVisitor {
1497 curitem: ast::DUMMY_NODE_ID,
1500 parents: visitor.parents,
1501 external_exports: external_exports,
1503 visit::walk_crate(&mut visitor, krate);
1505 // Sanity check to make sure that all privacy usage and controls are
1507 let mut visitor = SanePrivacyVisitor {
1511 visit::walk_crate(&mut visitor, krate);
1513 tcx.sess.abort_if_errors();
1515 // Build up a set of all exported items in the AST. This is a set of all
1516 // items which are reachable from external crates based on visibility.
1517 let mut visitor = EmbargoVisitor {
1519 exported_items: NodeSet(),
1520 public_items: NodeSet(),
1521 reexports: NodeSet(),
1522 export_map: export_map,
1523 prev_exported: true,
1527 let before = visitor.exported_items.len();
1528 visit::walk_crate(&mut visitor, krate);
1529 if before == visitor.exported_items.len() {
1534 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1537 let mut visitor = VisiblePrivateTypesVisitor {
1539 exported_items: &exported_items,
1540 public_items: &public_items,
1543 visit::walk_crate(&mut visitor, krate);
1545 return (exported_items, public_items);