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", issue = "27812")]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20 html_root_url = "https://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;
37 use rustc::middle::def;
38 use rustc::middle::def_id::DefId;
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::{self, Ty};
44 use rustc::util::nodemap::{NodeMap, NodeSet};
47 use syntax::codemap::Span;
48 use syntax::visit::{self, Visitor};
50 type Context<'a, 'tcx> = (&'a ty::MethodMap<'tcx>, &'a def::ExportMap);
52 /// Result of a checking operation - None => no errors were found. Some => an
53 /// error and contains the span and message for reporting that error and
54 /// optionally the same for a note about the error.
55 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
57 ////////////////////////////////////////////////////////////////////////////////
58 /// The parent visitor, used to determine what's the parent of what (node-wise)
59 ////////////////////////////////////////////////////////////////////////////////
61 struct ParentVisitor {
62 parents: NodeMap<ast::NodeId>,
63 curparent: ast::NodeId,
66 impl<'v> Visitor<'v> for ParentVisitor {
67 fn visit_item(&mut self, item: &ast::Item) {
68 self.parents.insert(item.id, self.curparent);
70 let prev = self.curparent;
72 ast::ItemMod(..) => { self.curparent = item.id; }
73 // Enum variants are parented to the enum definition itself because
74 // they inherit privacy
75 ast::ItemEnum(ref def, _) => {
76 for variant in &def.variants {
77 // The parent is considered the enclosing enum because the
78 // enum will dictate the privacy visibility of this variant
80 self.parents.insert(variant.node.id, item.id);
84 // Trait methods are always considered "public", but if the trait is
85 // private then we need some private item in the chain from the
86 // method to the root. In this case, if the trait is private, then
87 // parent all the methods to the trait to indicate that they're
89 ast::ItemTrait(_, _, _, ref trait_items) if item.vis != ast::Public => {
90 for trait_item in trait_items {
91 self.parents.insert(trait_item.id, item.id);
97 visit::walk_item(self, item);
98 self.curparent = prev;
101 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
102 self.parents.insert(a.id, self.curparent);
103 visit::walk_foreign_item(self, a);
106 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
107 c: &'v ast::Block, d: Span, id: ast::NodeId) {
108 // We already took care of some trait methods above, otherwise things
109 // like impl methods and pub trait methods are parented to the
110 // containing module, not the containing trait.
111 if !self.parents.contains_key(&id) {
112 self.parents.insert(id, self.curparent);
114 visit::walk_fn(self, a, b, c, d);
117 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
118 // visit_fn handles methods, but associated consts have to be handled
120 if !self.parents.contains_key(&ii.id) {
121 self.parents.insert(ii.id, self.curparent);
123 visit::walk_impl_item(self, ii);
126 fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
127 _: &'v ast::Generics, n: ast::NodeId) {
128 // Struct constructors are parented to their struct definitions because
129 // they essentially are the struct definitions.
131 Some(id) => { self.parents.insert(id, n); }
135 // While we have the id of the struct definition, go ahead and parent
137 for field in &s.fields {
138 self.parents.insert(field.node.id, self.curparent);
140 visit::walk_struct_def(self, s)
144 ////////////////////////////////////////////////////////////////////////////////
145 /// The embargo visitor, used to determine the exports of the ast
146 ////////////////////////////////////////////////////////////////////////////////
148 struct EmbargoVisitor<'a, 'tcx: 'a> {
149 tcx: &'a ty::ctxt<'tcx>,
150 export_map: &'a def::ExportMap,
152 // This flag is an indicator of whether the previous item in the
153 // hierarchical chain was exported or not. This is the indicator of whether
154 // children should be exported as well. Note that this can flip from false
155 // to true if a reexported module is entered (or an action similar).
158 // This is a list of all exported items in the AST. An exported item is any
159 // function/method/item which is usable by external crates. This essentially
160 // means that the result is "public all the way down", but the "path down"
161 // may jump across private boundaries through reexport statements.
162 exported_items: ExportedItems,
164 // This sets contains all the destination nodes which are publicly
165 // re-exported. This is *not* a set of all reexported nodes, only a set of
166 // all nodes which are reexported *and* reachable from external crates. This
167 // means that the destination of the reexport is exported, and hence the
168 // destination must also be exported.
171 // These two fields are closely related to one another in that they are only
172 // used for generation of the 'PublicItems' set, not for privacy checking at
174 public_items: PublicItems,
178 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
179 // There are checks inside of privacy which depend on knowing whether a
180 // trait should be exported or not. The two current consumers of this are:
182 // 1. Should default methods of a trait be exported?
183 // 2. Should the methods of an implementation of a trait be exported?
185 // The answer to both of these questions partly rely on whether the trait
186 // itself is exported or not. If the trait is somehow exported, then the
187 // answers to both questions must be yes. Right now this question involves
188 // more analysis than is currently done in rustc, so we conservatively
189 // answer "yes" so that all traits need to be exported.
190 fn exported_trait(&self, _id: ast::NodeId) -> bool {
195 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
196 fn visit_item(&mut self, item: &ast::Item) {
197 let orig_all_pub = self.prev_public;
198 self.prev_public = orig_all_pub && item.vis == ast::Public;
199 if self.prev_public {
200 self.public_items.insert(item.id);
203 let orig_all_exported = self.prev_exported;
205 // impls/extern blocks do not break the "public chain" because they
206 // cannot have visibility qualifiers on them anyway
207 ast::ItemImpl(..) | ast::ItemDefaultImpl(..) | ast::ItemForeignMod(..) => {}
209 // Traits are a little special in that even if they themselves are
210 // not public they may still be exported.
211 ast::ItemTrait(..) => {
212 self.prev_exported = self.exported_trait(item.id);
215 // Private by default, hence we only retain the "public chain" if
216 // `pub` is explicitly listed.
219 (orig_all_exported && item.vis == ast::Public) ||
220 self.reexports.contains(&item.id);
224 let public_first = self.prev_exported &&
225 self.exported_items.insert(item.id);
228 // Enum variants inherit from their parent, so if the enum is
229 // public all variants are public unless they're explicitly priv
230 ast::ItemEnum(ref def, _) if public_first => {
231 for variant in &def.variants {
232 self.exported_items.insert(variant.node.id);
233 self.public_items.insert(variant.node.id);
237 // Implementations are a little tricky to determine what's exported
238 // out of them. Here's a few cases which are currently defined:
240 // * Impls for private types do not need to export their methods
241 // (either public or private methods)
243 // * Impls for public types only have public methods exported
245 // * Public trait impls for public types must have all methods
248 // * Private trait impls for public types can be ignored
250 // * Public trait impls for private types have their methods
251 // exported. I'm not entirely certain that this is the correct
252 // thing to do, but I have seen use cases of where this will cause
253 // undefined symbols at linkage time if this case is not handled.
255 // * Private trait impls for private types can be completely ignored
256 ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
257 let public_ty = match ty.node {
259 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
260 def::DefPrimTy(..) => true,
262 let did = def.def_id();
264 self.exported_items.contains(&did.node)
270 let tr = self.tcx.impl_trait_ref(DefId::local(item.id));
271 let public_trait = tr.clone().map_or(false, |tr| {
272 !tr.def_id.is_local() ||
273 self.exported_items.contains(&tr.def_id.node)
276 if public_ty || public_trait {
277 for impl_item in impl_items {
278 match impl_item.node {
279 ast::ConstImplItem(..) => {
280 if (public_ty && impl_item.vis == ast::Public)
282 self.exported_items.insert(impl_item.id);
285 ast::MethodImplItem(ref sig, _) => {
286 let meth_public = match sig.explicit_self.node {
287 ast::SelfStatic => public_ty,
289 } && impl_item.vis == ast::Public;
290 if meth_public || tr.is_some() {
291 self.exported_items.insert(impl_item.id);
294 ast::TypeImplItem(_) |
295 ast::MacImplItem(_) => {}
301 // Default methods on traits are all public so long as the trait
303 ast::ItemTrait(_, _, _, ref trait_items) if public_first => {
304 for trait_item in trait_items {
305 debug!("trait item {}", trait_item.id);
306 self.exported_items.insert(trait_item.id);
310 // Struct constructors are public if the struct is all public.
311 ast::ItemStruct(ref def, _) if public_first => {
313 Some(id) => { self.exported_items.insert(id); }
316 // fields can be public or private, so lets check
317 for field in &def.fields {
318 let vis = match field.node.kind {
319 ast::NamedField(_, vis) | ast::UnnamedField(vis) => vis
321 if vis == ast::Public {
322 self.public_items.insert(field.node.id);
327 ast::ItemTy(ref ty, _) if public_first => {
328 if let ast::TyPath(..) = ty.node {
329 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
330 def::DefPrimTy(..) | def::DefTyParam(..) => {},
332 let did = def.def_id();
334 self.exported_items.insert(did.node);
344 visit::walk_item(self, item);
346 self.prev_exported = orig_all_exported;
347 self.prev_public = orig_all_pub;
350 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
351 if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) {
352 self.exported_items.insert(a.id);
356 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) {
357 // This code is here instead of in visit_item so that the
358 // crate module gets processed as well.
359 if self.prev_exported {
360 assert!(self.export_map.contains_key(&id), "wut {}", id);
361 for export in self.export_map.get(&id).unwrap() {
362 if export.def_id.is_local() {
363 self.reexports.insert(export.def_id.node);
367 visit::walk_mod(self, m)
371 ////////////////////////////////////////////////////////////////////////////////
372 /// The privacy visitor, where privacy checks take place (violations reported)
373 ////////////////////////////////////////////////////////////////////////////////
375 struct PrivacyVisitor<'a, 'tcx: 'a> {
376 tcx: &'a ty::ctxt<'tcx>,
377 curitem: ast::NodeId,
379 parents: NodeMap<ast::NodeId>,
380 external_exports: ExternalExports,
386 DisallowedBy(ast::NodeId),
390 UnnamedField(usize), // index
391 // (Name, not Ident, because struct fields are not macro-hygienic)
392 NamedField(ast::Name),
395 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
396 // used when debugging
397 fn nodestr(&self, id: ast::NodeId) -> String {
398 self.tcx.map.node_to_string(id).to_string()
401 // Determines whether the given definition is public from the point of view
402 // of the current item.
403 fn def_privacy(&self, did: DefId) -> PrivacyResult {
405 if self.external_exports.contains(&did) {
406 debug!("privacy - {:?} was externally exported", did);
409 debug!("privacy - is {:?} a public method", did);
411 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
412 Some(&ty::ConstTraitItem(ref ac)) => {
413 debug!("privacy - it's a const: {:?}", *ac);
415 ty::TraitContainer(id) => {
416 debug!("privacy - recursing on trait {:?}", id);
419 ty::ImplContainer(id) => {
420 match self.tcx.impl_trait_ref(id) {
422 debug!("privacy - impl of trait {:?}", id);
423 self.def_privacy(t.def_id)
426 debug!("privacy - found inherent \
427 associated constant {:?}",
429 if ac.vis == ast::Public {
439 Some(&ty::MethodTraitItem(ref meth)) => {
440 debug!("privacy - well at least it's a method: {:?}",
442 match meth.container {
443 ty::TraitContainer(id) => {
444 debug!("privacy - recursing on trait {:?}", id);
447 ty::ImplContainer(id) => {
448 match self.tcx.impl_trait_ref(id) {
450 debug!("privacy - impl of trait {:?}", id);
451 self.def_privacy(t.def_id)
454 debug!("privacy - found a method {:?}",
456 if meth.vis == ast::Public {
466 Some(&ty::TypeTraitItem(ref typedef)) => {
467 match typedef.container {
468 ty::TraitContainer(id) => {
469 debug!("privacy - recursing on trait {:?}", id);
472 ty::ImplContainer(id) => {
473 match self.tcx.impl_trait_ref(id) {
475 debug!("privacy - impl of trait {:?}", id);
476 self.def_privacy(t.def_id)
479 debug!("privacy - found a typedef {:?}",
481 if typedef.vis == ast::Public {
492 debug!("privacy - nope, not even a method");
498 debug!("privacy - local {} not public all the way down",
499 self.tcx.map.node_to_string(did.node));
500 // return quickly for things in the same module
501 if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
502 debug!("privacy - same parent, we're done here");
506 // We now know that there is at least one private member between the
507 // destination and the root.
508 let mut closest_private_id = did.node;
510 debug!("privacy - examining {}", self.nodestr(closest_private_id));
511 let vis = match self.tcx.map.find(closest_private_id) {
512 // If this item is a method, then we know for sure that it's an
513 // actual method and not a static method. The reason for this is
514 // that these cases are only hit in the ExprMethodCall
515 // expression, and ExprCall will have its path checked later
516 // (the path of the trait/impl) if it's a static method.
518 // With this information, then we can completely ignore all
519 // trait methods. The privacy violation would be if the trait
520 // couldn't get imported, not if the method couldn't be used
521 // (all trait methods are public).
523 // However, if this is an impl method, then we dictate this
524 // decision solely based on the privacy of the method
526 // FIXME(#10573) is this the right behavior? Why not consider
527 // where the method was defined?
528 Some(ast_map::NodeImplItem(ii)) => {
530 ast::ConstImplItem(..) |
531 ast::MethodImplItem(..) => {
532 let imp = self.tcx.map
533 .get_parent_did(closest_private_id);
534 match self.tcx.impl_trait_ref(imp) {
535 Some(..) => return Allowable,
536 _ if ii.vis == ast::Public => {
542 ast::TypeImplItem(_) |
543 ast::MacImplItem(_) => return Allowable,
546 Some(ast_map::NodeTraitItem(_)) => {
550 // This is not a method call, extract the visibility as one
551 // would normally look at it
552 Some(ast_map::NodeItem(it)) => it.vis,
553 Some(ast_map::NodeForeignItem(_)) => {
554 self.tcx.map.get_foreign_vis(closest_private_id)
556 Some(ast_map::NodeVariant(..)) => {
557 ast::Public // need to move up a level (to the enum)
561 if vis != ast::Public { break }
562 // if we've reached the root, then everything was allowable and this
564 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
565 closest_private_id = *self.parents.get(&closest_private_id).unwrap();
567 // If we reached the top, then we were public all the way down and
568 // we can allow this access.
569 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
571 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
572 if self.private_accessible(closest_private_id) {
575 DisallowedBy(closest_private_id)
579 /// For a local private node in the AST, this function will determine
580 /// whether the node is accessible by the current module that iteration is
582 fn private_accessible(&self, id: ast::NodeId) -> bool {
583 let parent = *self.parents.get(&id).unwrap();
584 debug!("privacy - accessible parent {}", self.nodestr(parent));
586 // After finding `did`'s closest private member, we roll ourselves back
587 // to see if this private member's parent is anywhere in our ancestry.
588 // By the privacy rules, we can access all of our ancestor's private
589 // members, so that's why we test the parent, and not the did itself.
590 let mut cur = self.curitem;
592 debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
594 // If the relevant parent is in our history, then we're allowed
595 // to look inside any of our ancestor's immediate private items,
596 // so this access is valid.
597 x if x == parent => return true,
599 // If we've reached the root, then we couldn't access this item
600 // in the first place
601 ast::DUMMY_NODE_ID => return false,
607 cur = *self.parents.get(&cur).unwrap();
611 fn report_error(&self, result: CheckResult) -> bool {
614 Some((span, msg, note)) => {
615 self.tcx.sess.span_err(span, &msg[..]);
617 Some((span, msg)) => {
618 self.tcx.sess.span_note(span, &msg[..])
627 /// Guarantee that a particular definition is public. Returns a CheckResult
628 /// which contains any errors found. These can be reported using `report_error`.
629 /// If the result is `None`, no errors were found.
630 fn ensure_public(&self, span: Span, to_check: DefId,
631 source_did: Option<DefId>, msg: &str) -> CheckResult {
632 let id = match self.def_privacy(to_check) {
633 ExternallyDenied => {
634 return Some((span, format!("{} is private", msg), None))
636 Allowable => return None,
637 DisallowedBy(id) => id,
640 // If we're disallowed by a particular id, then we attempt to give a
641 // nice error message to say why it was disallowed. It was either
642 // because the item itself is private or because its parent is private
643 // and its parent isn't in our ancestry.
644 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
645 return Some((span, format!("{} is private", msg), None));
647 (span, format!("{} is inaccessible", msg))
649 let item = match self.tcx.map.find(id) {
650 Some(ast_map::NodeItem(item)) => {
652 // If an impl disallowed this item, then this is resolve's
653 // way of saying that a struct/enum's static method was
654 // invoked, and the struct/enum itself is private. Crawl
655 // back up the chains to find the relevant struct/enum that
657 ast::ItemImpl(_, _, _, _, ref ty, _) => {
659 ast::TyPath(..) => {}
660 _ => return Some((err_span, err_msg, None)),
662 let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
663 let did = def.def_id();
664 assert!(did.is_local());
665 match self.tcx.map.get(did.node) {
666 ast_map::NodeItem(item) => item,
667 _ => self.tcx.sess.span_bug(item.span,
668 "path is not an item")
674 Some(..) | None => return Some((err_span, err_msg, None)),
676 let desc = match item.node {
677 ast::ItemMod(..) => "module",
678 ast::ItemTrait(..) => "trait",
679 ast::ItemStruct(..) => "struct",
680 ast::ItemEnum(..) => "enum",
681 _ => return Some((err_span, err_msg, None))
683 let msg = format!("{} `{}` is private", desc, item.ident);
684 Some((err_span, err_msg, Some((span, msg))))
687 // Checks that a field is in scope.
688 fn check_field(&mut self,
690 def: ty::AdtDef<'tcx>,
691 v: ty::VariantDef<'tcx>,
693 let field = match name {
694 NamedField(f_name) => {
695 debug!("privacy - check named field {} in struct {:?}", f_name, def);
696 v.field_named(f_name)
698 UnnamedField(idx) => &v.fields[idx]
700 if field.vis == ast::Public ||
701 (field.did.is_local() && self.private_accessible(field.did.node)) {
705 let struct_desc = match def.adt_kind() {
706 ty::AdtKind::Struct =>
707 format!("struct `{}`", self.tcx.item_path_str(def.did)),
708 // struct variant fields have inherited visibility
709 ty::AdtKind::Enum => return
711 let msg = match name {
712 NamedField(name) => format!("field `{}` of {} is private",
714 UnnamedField(idx) => format!("field #{} of {} is private",
715 idx + 1, struct_desc),
717 self.tcx.sess.span_err(span, &msg[..]);
720 // Given the ID of a method, checks to ensure it's in scope.
721 fn check_static_method(&mut self,
725 // If the method is a default method, we need to use the def_id of
726 // the default implementation.
727 let method_id = match self.tcx.impl_or_trait_item(method_id) {
728 ty::MethodTraitItem(method_type) => {
729 method_type.provided_source.unwrap_or(method_id)
734 "got non-method item in check_static_method")
738 self.report_error(self.ensure_public(span,
741 &format!("method `{}`",
745 // Checks that a path is in scope.
746 fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Name) {
747 debug!("privacy - path {}", self.nodestr(path_id));
748 let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap();
749 let ck = |tyname: &str| {
750 let ck_public = |def: DefId| {
751 debug!("privacy - ck_public {:?}", def);
752 let origdid = path_res.def_id();
753 self.ensure_public(span,
756 &format!("{} `{}`", tyname, last))
759 match path_res.last_private {
760 LastMod(AllPublic) => {},
761 LastMod(DependsOn(def)) => {
762 self.report_error(ck_public(def));
764 LastImport { value_priv,
765 value_used: check_value,
767 type_used: check_type } => {
768 // This dance with found_error is because we don't want to
769 // report a privacy error twice for the same directive.
770 let found_error = match (type_priv, check_type) {
771 (Some(DependsOn(def)), Used) => {
772 !self.report_error(ck_public(def))
777 match (value_priv, check_value) {
778 (Some(DependsOn(def)), Used) => {
779 self.report_error(ck_public(def));
784 // If an import is not used in either namespace, we still
785 // want to check that it could be legal. Therefore we check
786 // in both namespaces and only report an error if both would
787 // be illegal. We only report one error, even if it is
788 // illegal to import from both namespaces.
789 match (value_priv, check_value, type_priv, check_type) {
790 (Some(p), Unused, None, _) |
791 (None, _, Some(p), Unused) => {
794 DependsOn(def) => ck_public(def),
797 self.report_error(p);
800 (Some(v), Unused, Some(t), Unused) => {
803 DependsOn(def) => ck_public(def),
807 DependsOn(def) => ck_public(def),
809 if let (Some(_), Some(t)) = (v, t) {
810 self.report_error(Some(t));
818 // FIXME(#12334) Imports can refer to definitions in both the type and
819 // value namespaces. The privacy information is aware of this, but the
820 // def map is not. Therefore the names we work out below will not always
821 // be accurate and we can get slightly wonky error messages (but type
822 // checking is always correct).
823 match path_res.full_def() {
824 def::DefFn(..) => ck("function"),
825 def::DefStatic(..) => ck("static"),
826 def::DefConst(..) => ck("const"),
827 def::DefAssociatedConst(..) => ck("associated const"),
828 def::DefVariant(..) => ck("variant"),
829 def::DefTy(_, false) => ck("type"),
830 def::DefTy(_, true) => ck("enum"),
831 def::DefTrait(..) => ck("trait"),
832 def::DefStruct(..) => ck("struct"),
833 def::DefMethod(..) => ck("method"),
834 def::DefMod(..) => ck("module"),
839 // Checks that a method is in scope.
840 fn check_method(&mut self, span: Span, method_def_id: DefId,
842 match self.tcx.impl_or_trait_item(method_def_id).container() {
843 ty::ImplContainer(_) => {
844 self.check_static_method(span, method_def_id, name)
846 // Trait methods are always all public. The only controlling factor
847 // is whether the trait itself is accessible or not.
848 ty::TraitContainer(trait_def_id) => {
849 self.report_error(self.ensure_public(span, trait_def_id,
850 None, "source trait"));
856 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
857 fn visit_item(&mut self, item: &ast::Item) {
858 if let ast::ItemUse(ref vpath) = item.node {
859 if let ast::ViewPathList(ref prefix, ref list) = vpath.node {
862 ast::PathListIdent { id, name, .. } => {
863 debug!("privacy - ident item {}", id);
864 self.check_path(pid.span, id, name.name);
866 ast::PathListMod { id, .. } => {
867 debug!("privacy - mod item {}", id);
868 let name = prefix.segments.last().unwrap().identifier.name;
869 self.check_path(pid.span, id, name);
875 let orig_curitem = replace(&mut self.curitem, item.id);
876 visit::walk_item(self, item);
877 self.curitem = orig_curitem;
880 fn visit_expr(&mut self, expr: &ast::Expr) {
882 ast::ExprField(ref base, ident) => {
883 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
884 self.check_field(expr.span,
886 def.struct_variant(),
887 NamedField(ident.node.name));
890 ast::ExprTupField(ref base, idx) => {
891 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
892 self.check_field(expr.span,
894 def.struct_variant(),
895 UnnamedField(idx.node));
898 ast::ExprMethodCall(ident, _, _) => {
899 let method_call = ty::MethodCall::expr(expr.id);
900 let method = self.tcx.tables.borrow().method_map[&method_call];
901 debug!("(privacy checking) checking impl method");
902 self.check_method(expr.span, method.def_id, ident.node.name);
904 ast::ExprStruct(..) => {
905 let adt = self.tcx.expr_ty(expr).ty_adt_def().unwrap();
906 let variant = adt.variant_of_def(self.tcx.resolve_expr(expr));
907 // RFC 736: ensure all unmentioned fields are visible.
908 // Rather than computing the set of unmentioned fields
909 // (i.e. `all_fields - fields`), just check them all.
910 for field in &variant.fields {
911 self.check_field(expr.span, adt, variant, NamedField(field.name));
914 ast::ExprPath(..) => {
916 if let def::DefStruct(_) = self.tcx.resolve_expr(expr) {
917 let expr_ty = self.tcx.expr_ty(expr);
918 let def = match expr_ty.sty {
919 ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
920 output: ty::FnConverging(ty), ..
923 }.ty_adt_def().unwrap();
924 let any_priv = def.struct_variant().fields.iter().any(|f| {
925 f.vis != ast::Public && (
927 !self.private_accessible(f.did.node))
930 self.tcx.sess.span_err(expr.span,
931 "cannot invoke tuple struct constructor \
932 with private fields");
939 visit::walk_expr(self, expr);
942 fn visit_pat(&mut self, pattern: &ast::Pat) {
943 // Foreign functions do not have their patterns mapped in the def_map,
944 // and there's nothing really relevant there anyway, so don't bother
945 // checking privacy. If you can name the type then you can pass it to an
946 // external C function anyway.
947 if self.in_foreign { return }
950 ast::PatStruct(_, ref fields, _) => {
951 let adt = self.tcx.pat_ty(pattern).ty_adt_def().unwrap();
952 let def = self.tcx.def_map.borrow().get(&pattern.id).unwrap().full_def();
953 let variant = adt.variant_of_def(def);
954 for field in fields {
955 self.check_field(pattern.span, adt, variant,
956 NamedField(field.node.ident.name));
960 // Patterns which bind no fields are allowable (the path is check
962 ast::PatEnum(_, Some(ref fields)) => {
963 match self.tcx.pat_ty(pattern).sty {
964 ty::TyStruct(def, _) => {
965 for (i, field) in fields.iter().enumerate() {
966 if let ast::PatWild(..) = field.node {
969 self.check_field(field.span,
971 def.struct_variant(),
976 // enum fields have no privacy at this time
985 visit::walk_pat(self, pattern);
988 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
989 self.in_foreign = true;
990 visit::walk_foreign_item(self, fi);
991 self.in_foreign = false;
994 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
995 self.check_path(path.span, id, path.segments.last().unwrap().identifier.name);
996 visit::walk_path(self, path);
1000 ////////////////////////////////////////////////////////////////////////////////
1001 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1002 ////////////////////////////////////////////////////////////////////////////////
1004 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1005 tcx: &'a ty::ctxt<'tcx>,
1009 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1010 fn visit_item(&mut self, item: &ast::Item) {
1012 self.check_all_inherited(item);
1014 self.check_sane_privacy(item);
1017 let in_fn = self.in_fn;
1018 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1019 ast::ItemMod(..) => false, // modules turn privacy back on
1020 _ => in_fn, // otherwise we inherit
1022 visit::walk_item(self, item);
1023 self.in_fn = orig_in_fn;
1026 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1027 b: &'v ast::Block, s: Span, _: ast::NodeId) {
1028 // This catches both functions and methods
1029 let orig_in_fn = replace(&mut self.in_fn, true);
1030 visit::walk_fn(self, fk, fd, b, s);
1031 self.in_fn = orig_in_fn;
1035 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1036 /// Validates all of the visibility qualifiers placed on the item given. This
1037 /// ensures that there are no extraneous qualifiers that don't actually do
1038 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1039 /// later on down the road...
1040 fn check_sane_privacy(&self, item: &ast::Item) {
1042 let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
1043 if vis != ast::Inherited {
1044 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1045 if !note.is_empty() {
1046 tcx.sess.span_note(sp, note);
1051 // implementations of traits don't need visibility qualifiers because
1052 // that's controlled by having the trait in scope.
1053 ast::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1054 check_inherited(item.span, item.vis,
1055 "visibility qualifiers have no effect on trait \
1057 for impl_item in impl_items {
1058 check_inherited(impl_item.span, impl_item.vis, "");
1062 ast::ItemImpl(..) => {
1063 check_inherited(item.span, item.vis,
1064 "place qualifiers on individual methods instead");
1066 ast::ItemForeignMod(..) => {
1067 check_inherited(item.span, item.vis,
1068 "place qualifiers on individual functions \
1072 ast::ItemEnum(ref def, _) => {
1073 for v in &def.variants {
1076 if item.vis == ast::Public {
1077 tcx.sess.span_err(v.span, "unnecessary `pub` \
1081 ast::Inherited => {}
1086 ast::ItemTrait(..) | ast::ItemDefaultImpl(..) |
1087 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemStruct(..) |
1088 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1089 ast::ItemExternCrate(_) | ast::ItemUse(_) | ast::ItemMac(..) => {}
1093 /// When inside of something like a function or a method, visibility has no
1094 /// control over anything so this forbids any mention of any visibility
1095 fn check_all_inherited(&self, item: &ast::Item) {
1097 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
1098 if vis != ast::Inherited {
1099 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1102 let check_struct = |def: &ast::StructDef| {
1103 for f in &def.fields {
1105 ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
1106 ast::UnnamedField(..) => {}
1110 check_inherited(tcx, item.span, item.vis);
1112 ast::ItemImpl(_, _, _, _, _, ref impl_items) => {
1113 for impl_item in impl_items {
1114 match impl_item.node {
1115 ast::MethodImplItem(..) => {
1116 check_inherited(tcx, impl_item.span, impl_item.vis);
1122 ast::ItemForeignMod(ref fm) => {
1123 for i in &fm.items {
1124 check_inherited(tcx, i.span, i.vis);
1127 ast::ItemEnum(ref def, _) => {
1128 for v in &def.variants {
1129 check_inherited(tcx, v.span, v.node.vis);
1133 ast::ItemStruct(ref def, _) => check_struct(&**def),
1135 ast::ItemExternCrate(_) | ast::ItemUse(_) |
1136 ast::ItemTrait(..) | ast::ItemDefaultImpl(..) |
1137 ast::ItemStatic(..) | ast::ItemConst(..) |
1138 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1139 ast::ItemMac(..) => {}
1144 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1145 tcx: &'a ty::ctxt<'tcx>,
1146 exported_items: &'a ExportedItems,
1147 public_items: &'a PublicItems,
1151 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1152 inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1153 /// whether the type refers to private types.
1154 contains_private: bool,
1155 /// whether we've recurred at all (i.e. if we're pointing at the
1156 /// first type on which visit_ty was called).
1157 at_outer_type: bool,
1158 // whether that first type is a public path.
1159 outer_type_is_public_path: bool,
1162 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1163 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1164 let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) {
1165 // `int` etc. (None doesn't seem to occur.)
1166 None | Some(def::DefPrimTy(..)) => return false,
1167 Some(def) => def.def_id(),
1169 // A path can only be private if:
1170 // it's in this crate...
1171 if !did.is_local() {
1175 // .. and it corresponds to a private type in the AST (this returns
1176 // None for type parameters)
1177 match self.tcx.map.find(did.node) {
1178 Some(ast_map::NodeItem(ref item)) => item.vis != ast::Public,
1179 Some(_) | None => false,
1183 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1184 // FIXME: this would preferably be using `exported_items`, but all
1185 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1186 self.public_items.contains(&trait_id)
1189 fn check_ty_param_bound(&self,
1190 ty_param_bound: &ast::TyParamBound) {
1191 if let ast::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1192 if !self.tcx.sess.features.borrow().visible_private_types &&
1193 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1194 let span = trait_ref.trait_ref.path.span;
1195 self.tcx.sess.span_err(span, "private trait in exported type \
1201 fn item_is_public(&self, id: &ast::NodeId, vis: ast::Visibility) -> bool {
1202 self.exported_items.contains(id) || vis == ast::Public
1206 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1207 fn visit_ty(&mut self, ty: &ast::Ty) {
1208 if let ast::TyPath(..) = ty.node {
1209 if self.inner.path_is_private_type(ty.id) {
1210 self.contains_private = true;
1211 // found what we're looking for so let's stop
1214 } else if self.at_outer_type {
1215 self.outer_type_is_public_path = true;
1218 self.at_outer_type = false;
1219 visit::walk_ty(self, ty)
1222 // don't want to recurse into [, .. expr]
1223 fn visit_expr(&mut self, _: &ast::Expr) {}
1226 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1227 fn visit_item(&mut self, item: &ast::Item) {
1229 // contents of a private mod can be reexported, so we need
1230 // to check internals.
1231 ast::ItemMod(_) => {}
1233 // An `extern {}` doesn't introduce a new privacy
1234 // namespace (the contents have their own privacies).
1235 ast::ItemForeignMod(_) => {}
1237 ast::ItemTrait(_, _, ref bounds, _) => {
1238 if !self.trait_is_public(item.id) {
1242 for bound in bounds.iter() {
1243 self.check_ty_param_bound(bound)
1247 // impls need some special handling to try to offer useful
1248 // error messages without (too many) false positives
1249 // (i.e. we could just return here to not check them at
1250 // all, or some worse estimation of whether an impl is
1251 // publicly visible).
1252 ast::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1253 // `impl [... for] Private` is never visible.
1254 let self_contains_private;
1255 // impl [... for] Public<...>, but not `impl [... for]
1256 // Vec<Public>` or `(Public,)` etc.
1257 let self_is_public_path;
1259 // check the properties of the Self type:
1261 let mut visitor = CheckTypeForPrivatenessVisitor {
1263 contains_private: false,
1264 at_outer_type: true,
1265 outer_type_is_public_path: false,
1267 visitor.visit_ty(&**self_);
1268 self_contains_private = visitor.contains_private;
1269 self_is_public_path = visitor.outer_type_is_public_path;
1272 // miscellaneous info about the impl
1274 // `true` iff this is `impl Private for ...`.
1275 let not_private_trait =
1276 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1278 let did = self.tcx.trait_ref_to_def_id(tr);
1280 !did.is_local() || self.trait_is_public(did.node)
1283 // `true` iff this is a trait impl or at least one method is public.
1285 // `impl Public { $( fn ...() {} )* }` is not visible.
1287 // This is required over just using the methods' privacy
1288 // directly because we might have `impl<T: Foo<Private>> ...`,
1289 // and we shouldn't warn about the generics if all the methods
1290 // are private (because `T` won't be visible externally).
1291 let trait_or_some_public_method =
1292 trait_ref.is_some() ||
1295 match impl_item.node {
1296 ast::ConstImplItem(..) |
1297 ast::MethodImplItem(..) => {
1298 self.exported_items.contains(&impl_item.id)
1300 ast::TypeImplItem(_) |
1301 ast::MacImplItem(_) => false,
1305 if !self_contains_private &&
1306 not_private_trait &&
1307 trait_or_some_public_method {
1309 visit::walk_generics(self, g);
1313 for impl_item in impl_items {
1314 // This is where we choose whether to walk down
1315 // further into the impl to check its items. We
1316 // should only walk into public items so that we
1317 // don't erroneously report errors for private
1318 // types in private items.
1319 match impl_item.node {
1320 ast::ConstImplItem(..) |
1321 ast::MethodImplItem(..)
1322 if self.item_is_public(&impl_item.id, impl_item.vis) =>
1324 visit::walk_impl_item(self, impl_item)
1326 ast::TypeImplItem(..) => {
1327 visit::walk_impl_item(self, impl_item)
1334 // Any private types in a trait impl fall into three
1336 // 1. mentioned in the trait definition
1337 // 2. mentioned in the type params/generics
1338 // 3. mentioned in the associated types of the impl
1340 // Those in 1. can only occur if the trait is in
1341 // this crate and will've been warned about on the
1342 // trait definition (there's no need to warn twice
1343 // so we don't check the methods).
1345 // Those in 2. are warned via walk_generics and this
1347 visit::walk_path(self, &tr.path);
1349 // Those in 3. are warned with this call.
1350 for impl_item in impl_items {
1351 if let ast::TypeImplItem(ref ty) = impl_item.node {
1357 } else if trait_ref.is_none() && self_is_public_path {
1358 // impl Public<Private> { ... }. Any public static
1359 // methods will be visible as `Public::foo`.
1360 let mut found_pub_static = false;
1361 for impl_item in impl_items {
1362 match impl_item.node {
1363 ast::ConstImplItem(..) => {
1364 if self.item_is_public(&impl_item.id, impl_item.vis) {
1365 found_pub_static = true;
1366 visit::walk_impl_item(self, impl_item);
1369 ast::MethodImplItem(ref sig, _) => {
1370 if sig.explicit_self.node == ast::SelfStatic &&
1371 self.item_is_public(&impl_item.id, impl_item.vis) {
1372 found_pub_static = true;
1373 visit::walk_impl_item(self, impl_item);
1379 if found_pub_static {
1380 visit::walk_generics(self, g)
1386 // `type ... = ...;` can contain private types, because
1387 // we're introducing a new name.
1388 ast::ItemTy(..) => return,
1390 // not at all public, so we don't care
1391 _ if !self.item_is_public(&item.id, item.vis) => {
1398 // We've carefully constructed it so that if we're here, then
1399 // any `visit_ty`'s will be called on things that are in
1400 // public signatures, i.e. things that we're interested in for
1402 debug!("VisiblePrivateTypesVisitor entering item {:?}", item);
1403 visit::walk_item(self, item);
1406 fn visit_generics(&mut self, generics: &ast::Generics) {
1407 for ty_param in generics.ty_params.iter() {
1408 for bound in ty_param.bounds.iter() {
1409 self.check_ty_param_bound(bound)
1412 for predicate in &generics.where_clause.predicates {
1414 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
1415 for bound in bound_pred.bounds.iter() {
1416 self.check_ty_param_bound(bound)
1419 &ast::WherePredicate::RegionPredicate(_) => {}
1420 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
1421 self.visit_ty(&*eq_pred.ty);
1427 fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
1428 if self.exported_items.contains(&item.id) {
1429 visit::walk_foreign_item(self, item)
1433 fn visit_ty(&mut self, t: &ast::Ty) {
1434 debug!("VisiblePrivateTypesVisitor checking ty {:?}", t);
1435 if let ast::TyPath(_, ref p) = t.node {
1436 if !self.tcx.sess.features.borrow().visible_private_types &&
1437 self.path_is_private_type(t.id) {
1438 self.tcx.sess.span_err(p.span, "private type in exported type signature");
1441 visit::walk_ty(self, t)
1444 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
1445 if self.exported_items.contains(&v.node.id) {
1446 self.in_variant = true;
1447 visit::walk_variant(self, v, g);
1448 self.in_variant = false;
1452 fn visit_struct_field(&mut self, s: &ast::StructField) {
1454 ast::NamedField(_, vis) if vis == ast::Public || self.in_variant => {
1455 visit::walk_struct_field(self, s);
1462 // we don't need to introspect into these at all: an
1463 // expression/block context can't possibly contain exported things.
1464 // (Making them no-ops stops us from traversing the whole AST without
1465 // having to be super careful about our `walk_...` calls above.)
1466 fn visit_block(&mut self, _: &ast::Block) {}
1467 fn visit_expr(&mut self, _: &ast::Expr) {}
1470 pub fn check_crate(tcx: &ty::ctxt,
1471 export_map: &def::ExportMap,
1472 external_exports: ExternalExports)
1473 -> (ExportedItems, PublicItems) {
1474 let krate = tcx.map.krate();
1476 // Figure out who everyone's parent is
1477 let mut visitor = ParentVisitor {
1479 curparent: ast::DUMMY_NODE_ID,
1481 visit::walk_crate(&mut visitor, krate);
1483 // Use the parent map to check the privacy of everything
1484 let mut visitor = PrivacyVisitor {
1485 curitem: ast::DUMMY_NODE_ID,
1488 parents: visitor.parents,
1489 external_exports: external_exports,
1491 visit::walk_crate(&mut visitor, krate);
1493 // Sanity check to make sure that all privacy usage and controls are
1495 let mut visitor = SanePrivacyVisitor {
1499 visit::walk_crate(&mut visitor, krate);
1501 tcx.sess.abort_if_errors();
1503 // Build up a set of all exported items in the AST. This is a set of all
1504 // items which are reachable from external crates based on visibility.
1505 let mut visitor = EmbargoVisitor {
1507 exported_items: NodeSet(),
1508 public_items: NodeSet(),
1509 reexports: NodeSet(),
1510 export_map: export_map,
1511 prev_exported: true,
1515 let before = visitor.exported_items.len();
1516 visit::walk_crate(&mut visitor, krate);
1517 if before == visitor.exported_items.len() {
1522 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1525 let mut visitor = VisiblePrivateTypesVisitor {
1527 exported_items: &exported_items,
1528 public_items: &public_items,
1531 visit::walk_crate(&mut visitor, krate);
1533 return (exported_items, public_items);