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;
30 extern crate rustc_front;
32 use self::PrivacyResult::*;
33 use self::FieldName::*;
35 use std::mem::replace;
38 use rustc_front::visit::{self, Visitor};
40 use rustc::middle::def;
41 use rustc::middle::def_id::DefId;
42 use rustc::middle::privacy::ImportUse::*;
43 use rustc::middle::privacy::LastPrivate::*;
44 use rustc::middle::privacy::PrivateDep::*;
45 use rustc::middle::privacy::{ExternalExports, ExportedItems, PublicItems};
46 use rustc::middle::ty::{self, Ty};
47 use rustc::util::nodemap::{NodeMap, NodeSet};
48 use rustc::front::map as ast_map;
51 use syntax::codemap::Span;
53 type Context<'a, 'tcx> = (&'a ty::MethodMap<'tcx>, &'a def::ExportMap);
55 /// Result of a checking operation - None => no errors were found. Some => an
56 /// error and contains the span and message for reporting that error and
57 /// optionally the same for a note about the error.
58 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
60 ////////////////////////////////////////////////////////////////////////////////
61 /// The parent visitor, used to determine what's the parent of what (node-wise)
62 ////////////////////////////////////////////////////////////////////////////////
64 struct ParentVisitor {
65 parents: NodeMap<ast::NodeId>,
66 curparent: ast::NodeId,
69 impl<'v> Visitor<'v> for ParentVisitor {
70 fn visit_item(&mut self, item: &hir::Item) {
71 self.parents.insert(item.id, self.curparent);
73 let prev = self.curparent;
75 hir::ItemMod(..) => { self.curparent = item.id; }
76 // Enum variants are parented to the enum definition itself because
77 // they inherit privacy
78 hir::ItemEnum(ref def, _) => {
79 for variant in &def.variants {
80 // The parent is considered the enclosing enum because the
81 // enum will dictate the privacy visibility of this variant
83 self.parents.insert(variant.node.id, item.id);
87 // Trait methods are always considered "public", but if the trait is
88 // private then we need some private item in the chain from the
89 // method to the root. In this case, if the trait is private, then
90 // parent all the methods to the trait to indicate that they're
92 hir::ItemTrait(_, _, _, ref trait_items) if item.vis != hir::Public => {
93 for trait_item in trait_items {
94 self.parents.insert(trait_item.id, item.id);
100 visit::walk_item(self, item);
101 self.curparent = prev;
104 fn visit_foreign_item(&mut self, a: &hir::ForeignItem) {
105 self.parents.insert(a.id, self.curparent);
106 visit::walk_foreign_item(self, a);
109 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v hir::FnDecl,
110 c: &'v hir::Block, d: Span, id: ast::NodeId) {
111 // We already took care of some trait methods above, otherwise things
112 // like impl methods and pub trait methods are parented to the
113 // containing module, not the containing trait.
114 if !self.parents.contains_key(&id) {
115 self.parents.insert(id, self.curparent);
117 visit::walk_fn(self, a, b, c, d);
120 fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) {
121 // visit_fn handles methods, but associated consts have to be handled
123 if !self.parents.contains_key(&ii.id) {
124 self.parents.insert(ii.id, self.curparent);
126 visit::walk_impl_item(self, ii);
129 fn visit_struct_def(&mut self, s: &hir::StructDef, _: ast::Ident,
130 _: &'v hir::Generics, n: ast::NodeId) {
131 // Struct constructors are parented to their struct definitions because
132 // they essentially are the struct definitions.
134 Some(id) => { self.parents.insert(id, n); }
138 // While we have the id of the struct definition, go ahead and parent
140 for field in &s.fields {
141 self.parents.insert(field.node.id, self.curparent);
143 visit::walk_struct_def(self, s)
147 ////////////////////////////////////////////////////////////////////////////////
148 /// The embargo visitor, used to determine the exports of the ast
149 ////////////////////////////////////////////////////////////////////////////////
151 struct EmbargoVisitor<'a, 'tcx: 'a> {
152 tcx: &'a ty::ctxt<'tcx>,
153 export_map: &'a def::ExportMap,
155 // This flag is an indicator of whether the previous item in the
156 // hierarchical chain was exported or not. This is the indicator of whether
157 // children should be exported as well. Note that this can flip from false
158 // to true if a reexported module is entered (or an action similar).
161 // This is a list of all exported items in the AST. An exported item is any
162 // function/method/item which is usable by external crates. This essentially
163 // means that the result is "public all the way down", but the "path down"
164 // may jump across private boundaries through reexport statements.
165 exported_items: ExportedItems,
167 // This sets contains all the destination nodes which are publicly
168 // re-exported. This is *not* a set of all reexported nodes, only a set of
169 // all nodes which are reexported *and* reachable from external crates. This
170 // means that the destination of the reexport is exported, and hence the
171 // destination must also be exported.
174 // These two fields are closely related to one another in that they are only
175 // used for generation of the 'PublicItems' set, not for privacy checking at
177 public_items: PublicItems,
181 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
182 // There are checks inside of privacy which depend on knowing whether a
183 // trait should be exported or not. The two current consumers of this are:
185 // 1. Should default methods of a trait be exported?
186 // 2. Should the methods of an implementation of a trait be exported?
188 // The answer to both of these questions partly rely on whether the trait
189 // itself is exported or not. If the trait is somehow exported, then the
190 // answers to both questions must be yes. Right now this question involves
191 // more analysis than is currently done in rustc, so we conservatively
192 // answer "yes" so that all traits need to be exported.
193 fn exported_trait(&self, _id: ast::NodeId) -> bool {
198 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
199 fn visit_item(&mut self, item: &hir::Item) {
200 let orig_all_pub = self.prev_public;
201 self.prev_public = orig_all_pub && item.vis == hir::Public;
202 if self.prev_public {
203 self.public_items.insert(item.id);
206 let orig_all_exported = self.prev_exported;
208 // impls/extern blocks do not break the "public chain" because they
209 // cannot have visibility qualifiers on them anyway
210 hir::ItemImpl(..) | hir::ItemDefaultImpl(..) | hir::ItemForeignMod(..) => {}
212 // Traits are a little special in that even if they themselves are
213 // not public they may still be exported.
214 hir::ItemTrait(..) => {
215 self.prev_exported = self.exported_trait(item.id);
218 // Private by default, hence we only retain the "public chain" if
219 // `pub` is explicitly listed.
222 (orig_all_exported && item.vis == hir::Public) ||
223 self.reexports.contains(&item.id);
227 let public_first = self.prev_exported &&
228 self.exported_items.insert(item.id);
231 // Enum variants inherit from their parent, so if the enum is
232 // public all variants are public unless they're explicitly priv
233 hir::ItemEnum(ref def, _) if public_first => {
234 for variant in &def.variants {
235 self.exported_items.insert(variant.node.id);
236 self.public_items.insert(variant.node.id);
240 // Implementations are a little tricky to determine what's exported
241 // out of them. Here's a few cases which are currently defined:
243 // * Impls for private types do not need to export their methods
244 // (either public or private methods)
246 // * Impls for public types only have public methods exported
248 // * Public trait impls for public types must have all methods
251 // * Private trait impls for public types can be ignored
253 // * Public trait impls for private types have their methods
254 // exported. I'm not entirely certain that this is the correct
255 // thing to do, but I have seen use cases of where this will cause
256 // undefined symbols at linkage time if this case is not handled.
258 // * Private trait impls for private types can be completely ignored
259 hir::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
260 let public_ty = match ty.node {
262 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
263 def::DefPrimTy(..) => true,
265 let did = def.def_id();
267 self.exported_items.contains(&did.node)
273 let tr = self.tcx.impl_trait_ref(DefId::local(item.id));
274 let public_trait = tr.clone().map_or(false, |tr| {
275 !tr.def_id.is_local() ||
276 self.exported_items.contains(&tr.def_id.node)
279 if public_ty || public_trait {
280 for impl_item in impl_items {
281 match impl_item.node {
282 hir::ConstImplItem(..) => {
283 if (public_ty && impl_item.vis == hir::Public)
285 self.exported_items.insert(impl_item.id);
288 hir::MethodImplItem(ref sig, _) => {
289 let meth_public = match sig.explicit_self.node {
290 hir::SelfStatic => public_ty,
292 } && impl_item.vis == hir::Public;
293 if meth_public || tr.is_some() {
294 self.exported_items.insert(impl_item.id);
297 hir::TypeImplItem(_) => {}
303 // Default methods on traits are all public so long as the trait
305 hir::ItemTrait(_, _, _, ref trait_items) if public_first => {
306 for trait_item in trait_items {
307 debug!("trait item {}", trait_item.id);
308 self.exported_items.insert(trait_item.id);
312 // Struct constructors are public if the struct is all public.
313 hir::ItemStruct(ref def, _) if public_first => {
315 Some(id) => { self.exported_items.insert(id); }
318 // fields can be public or private, so lets check
319 for field in &def.fields {
320 let vis = match field.node.kind {
321 hir::NamedField(_, vis) | hir::UnnamedField(vis) => vis
323 if vis == hir::Public {
324 self.public_items.insert(field.node.id);
329 hir::ItemTy(ref ty, _) if public_first => {
330 if let hir::TyPath(..) = ty.node {
331 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
332 def::DefPrimTy(..) | def::DefTyParam(..) => {},
334 let did = def.def_id();
336 self.exported_items.insert(did.node);
346 visit::walk_item(self, item);
348 self.prev_exported = orig_all_exported;
349 self.prev_public = orig_all_pub;
352 fn visit_foreign_item(&mut self, a: &hir::ForeignItem) {
353 if (self.prev_exported && a.vis == hir::Public) || self.reexports.contains(&a.id) {
354 self.exported_items.insert(a.id);
358 fn visit_mod(&mut self, m: &hir::Mod, _sp: Span, id: ast::NodeId) {
359 // This code is here instead of in visit_item so that the
360 // crate module gets processed as well.
361 if self.prev_exported {
362 assert!(self.export_map.contains_key(&id), "wut {}", id);
363 for export in self.export_map.get(&id).unwrap() {
364 if export.def_id.is_local() {
365 self.reexports.insert(export.def_id.node);
369 visit::walk_mod(self, m)
373 ////////////////////////////////////////////////////////////////////////////////
374 /// The privacy visitor, where privacy checks take place (violations reported)
375 ////////////////////////////////////////////////////////////////////////////////
377 struct PrivacyVisitor<'a, 'tcx: 'a> {
378 tcx: &'a ty::ctxt<'tcx>,
379 curitem: ast::NodeId,
381 parents: NodeMap<ast::NodeId>,
382 external_exports: ExternalExports,
388 DisallowedBy(ast::NodeId),
392 UnnamedField(usize), // index
393 // (Name, not Ident, because struct fields are not macro-hygienic)
394 NamedField(ast::Name),
397 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
398 // used when debugging
399 fn nodestr(&self, id: ast::NodeId) -> String {
400 self.tcx.map.node_to_string(id).to_string()
403 // Determines whether the given definition is public from the point of view
404 // of the current item.
405 fn def_privacy(&self, did: DefId) -> PrivacyResult {
407 if self.external_exports.contains(&did) {
408 debug!("privacy - {:?} was externally exported", did);
411 debug!("privacy - is {:?} a public method", did);
413 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
414 Some(&ty::ConstTraitItem(ref ac)) => {
415 debug!("privacy - it's a const: {:?}", *ac);
417 ty::TraitContainer(id) => {
418 debug!("privacy - recursing on trait {:?}", id);
421 ty::ImplContainer(id) => {
422 match self.tcx.impl_trait_ref(id) {
424 debug!("privacy - impl of trait {:?}", id);
425 self.def_privacy(t.def_id)
428 debug!("privacy - found inherent \
429 associated constant {:?}",
431 if ac.vis == hir::Public {
441 Some(&ty::MethodTraitItem(ref meth)) => {
442 debug!("privacy - well at least it's a method: {:?}",
444 match meth.container {
445 ty::TraitContainer(id) => {
446 debug!("privacy - recursing on trait {:?}", id);
449 ty::ImplContainer(id) => {
450 match self.tcx.impl_trait_ref(id) {
452 debug!("privacy - impl of trait {:?}", id);
453 self.def_privacy(t.def_id)
456 debug!("privacy - found a method {:?}",
458 if meth.vis == hir::Public {
468 Some(&ty::TypeTraitItem(ref typedef)) => {
469 match typedef.container {
470 ty::TraitContainer(id) => {
471 debug!("privacy - recursing on trait {:?}", id);
474 ty::ImplContainer(id) => {
475 match self.tcx.impl_trait_ref(id) {
477 debug!("privacy - impl of trait {:?}", id);
478 self.def_privacy(t.def_id)
481 debug!("privacy - found a typedef {:?}",
483 if typedef.vis == hir::Public {
494 debug!("privacy - nope, not even a method");
500 debug!("privacy - local {} not public all the way down",
501 self.tcx.map.node_to_string(did.node));
502 // return quickly for things in the same module
503 if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
504 debug!("privacy - same parent, we're done here");
508 // We now know that there is at least one private member between the
509 // destination and the root.
510 let mut closest_private_id = did.node;
512 debug!("privacy - examining {}", self.nodestr(closest_private_id));
513 let vis = match self.tcx.map.find(closest_private_id) {
514 // If this item is a method, then we know for sure that it's an
515 // actual method and not a static method. The reason for this is
516 // that these cases are only hit in the ExprMethodCall
517 // expression, and ExprCall will have its path checked later
518 // (the path of the trait/impl) if it's a static method.
520 // With this information, then we can completely ignore all
521 // trait methods. The privacy violation would be if the trait
522 // couldn't get imported, not if the method couldn't be used
523 // (all trait methods are public).
525 // However, if this is an impl method, then we dictate this
526 // decision solely based on the privacy of the method
528 // FIXME(#10573) is this the right behavior? Why not consider
529 // where the method was defined?
530 Some(ast_map::NodeImplItem(ii)) => {
532 hir::ConstImplItem(..) |
533 hir::MethodImplItem(..) => {
534 let imp = self.tcx.map
535 .get_parent_did(closest_private_id);
536 match self.tcx.impl_trait_ref(imp) {
537 Some(..) => return Allowable,
538 _ if ii.vis == hir::Public => {
544 hir::TypeImplItem(_) => return Allowable,
547 Some(ast_map::NodeTraitItem(_)) => {
551 // This is not a method call, extract the visibility as one
552 // would normally look at it
553 Some(ast_map::NodeItem(it)) => it.vis,
554 Some(ast_map::NodeForeignItem(_)) => {
555 self.tcx.map.get_foreign_vis(closest_private_id)
557 Some(ast_map::NodeVariant(..)) => {
558 hir::Public // need to move up a level (to the enum)
562 if vis != hir::Public { break }
563 // if we've reached the root, then everything was allowable and this
565 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
566 closest_private_id = *self.parents.get(&closest_private_id).unwrap();
568 // If we reached the top, then we were public all the way down and
569 // we can allow this access.
570 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
572 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
573 if self.private_accessible(closest_private_id) {
576 DisallowedBy(closest_private_id)
580 /// For a local private node in the AST, this function will determine
581 /// whether the node is accessible by the current module that iteration is
583 fn private_accessible(&self, id: ast::NodeId) -> bool {
584 let parent = *self.parents.get(&id).unwrap();
585 debug!("privacy - accessible parent {}", self.nodestr(parent));
587 // After finding `did`'s closest private member, we roll ourselves back
588 // to see if this private member's parent is anywhere in our ancestry.
589 // By the privacy rules, we can access all of our ancestor's private
590 // members, so that's why we test the parent, and not the did itself.
591 let mut cur = self.curitem;
593 debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
595 // If the relevant parent is in our history, then we're allowed
596 // to look inside any of our ancestor's immediate private items,
597 // so this access is valid.
598 x if x == parent => return true,
600 // If we've reached the root, then we couldn't access this item
601 // in the first place
602 ast::DUMMY_NODE_ID => return false,
608 cur = *self.parents.get(&cur).unwrap();
612 fn report_error(&self, result: CheckResult) -> bool {
615 Some((span, msg, note)) => {
616 self.tcx.sess.span_err(span, &msg[..]);
618 Some((span, msg)) => {
619 self.tcx.sess.span_note(span, &msg[..])
628 /// Guarantee that a particular definition is public. Returns a CheckResult
629 /// which contains any errors found. These can be reported using `report_error`.
630 /// If the result is `None`, no errors were found.
631 fn ensure_public(&self, span: Span, to_check: DefId,
632 source_did: Option<DefId>, msg: &str) -> CheckResult {
633 let id = match self.def_privacy(to_check) {
634 ExternallyDenied => {
635 return Some((span, format!("{} is private", msg), None))
637 Allowable => return None,
638 DisallowedBy(id) => id,
641 // If we're disallowed by a particular id, then we attempt to give a
642 // nice error message to say why it was disallowed. It was either
643 // because the item itself is private or because its parent is private
644 // and its parent isn't in our ancestry.
645 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
646 return Some((span, format!("{} is private", msg), None));
648 (span, format!("{} is inaccessible", msg))
650 let item = match self.tcx.map.find(id) {
651 Some(ast_map::NodeItem(item)) => {
653 // If an impl disallowed this item, then this is resolve's
654 // way of saying that a struct/enum's static method was
655 // invoked, and the struct/enum itself is private. Crawl
656 // back up the chains to find the relevant struct/enum that
658 hir::ItemImpl(_, _, _, _, ref ty, _) => {
660 hir::TyPath(..) => {}
661 _ => return Some((err_span, err_msg, None)),
663 let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
664 let did = def.def_id();
665 assert!(did.is_local());
666 match self.tcx.map.get(did.node) {
667 ast_map::NodeItem(item) => item,
668 _ => self.tcx.sess.span_bug(item.span,
669 "path is not an item")
675 Some(..) | None => return Some((err_span, err_msg, None)),
677 let desc = match item.node {
678 hir::ItemMod(..) => "module",
679 hir::ItemTrait(..) => "trait",
680 hir::ItemStruct(..) => "struct",
681 hir::ItemEnum(..) => "enum",
682 _ => return Some((err_span, err_msg, None))
684 let msg = format!("{} `{}` is private", desc, item.ident);
685 Some((err_span, err_msg, Some((span, msg))))
688 // Checks that a field is in scope.
689 fn check_field(&mut self,
691 def: ty::AdtDef<'tcx>,
692 v: ty::VariantDef<'tcx>,
694 let field = match name {
695 NamedField(f_name) => {
696 debug!("privacy - check named field {} in struct {:?}", f_name, def);
697 v.field_named(f_name)
699 UnnamedField(idx) => &v.fields[idx]
701 if field.vis == hir::Public ||
702 (field.did.is_local() && self.private_accessible(field.did.node)) {
706 let struct_desc = match def.adt_kind() {
707 ty::AdtKind::Struct =>
708 format!("struct `{}`", self.tcx.item_path_str(def.did)),
709 // struct variant fields have inherited visibility
710 ty::AdtKind::Enum => return
712 let msg = match name {
713 NamedField(name) => format!("field `{}` of {} is private",
715 UnnamedField(idx) => format!("field #{} of {} is private",
716 idx + 1, struct_desc),
718 self.tcx.sess.span_err(span, &msg[..]);
721 // Given the ID of a method, checks to ensure it's in scope.
722 fn check_static_method(&mut self,
726 // If the method is a default method, we need to use the def_id of
727 // the default implementation.
728 let method_id = match self.tcx.impl_or_trait_item(method_id) {
729 ty::MethodTraitItem(method_type) => {
730 method_type.provided_source.unwrap_or(method_id)
735 "got non-method item in check_static_method")
739 self.report_error(self.ensure_public(span,
742 &format!("method `{}`",
746 // Checks that a path is in scope.
747 fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Name) {
748 debug!("privacy - path {}", self.nodestr(path_id));
749 let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap();
750 let ck = |tyname: &str| {
751 let ck_public = |def: DefId| {
752 debug!("privacy - ck_public {:?}", def);
753 let origdid = path_res.def_id();
754 self.ensure_public(span,
757 &format!("{} `{}`", tyname, last))
760 match path_res.last_private {
761 LastMod(AllPublic) => {},
762 LastMod(DependsOn(def)) => {
763 self.report_error(ck_public(def));
765 LastImport { value_priv,
766 value_used: check_value,
768 type_used: check_type } => {
769 // This dance with found_error is because we don't want to
770 // report a privacy error twice for the same directive.
771 let found_error = match (type_priv, check_type) {
772 (Some(DependsOn(def)), Used) => {
773 !self.report_error(ck_public(def))
778 match (value_priv, check_value) {
779 (Some(DependsOn(def)), Used) => {
780 self.report_error(ck_public(def));
785 // If an import is not used in either namespace, we still
786 // want to check that it could be legal. Therefore we check
787 // in both namespaces and only report an error if both would
788 // be illegal. We only report one error, even if it is
789 // illegal to import from both namespaces.
790 match (value_priv, check_value, type_priv, check_type) {
791 (Some(p), Unused, None, _) |
792 (None, _, Some(p), Unused) => {
795 DependsOn(def) => ck_public(def),
798 self.report_error(p);
801 (Some(v), Unused, Some(t), Unused) => {
804 DependsOn(def) => ck_public(def),
808 DependsOn(def) => ck_public(def),
810 if let (Some(_), Some(t)) = (v, t) {
811 self.report_error(Some(t));
819 // FIXME(#12334) Imports can refer to definitions in both the type and
820 // value namespaces. The privacy information is aware of this, but the
821 // def map is not. Therefore the names we work out below will not always
822 // be accurate and we can get slightly wonky error messages (but type
823 // checking is always correct).
824 match path_res.full_def() {
825 def::DefFn(..) => ck("function"),
826 def::DefStatic(..) => ck("static"),
827 def::DefConst(..) => ck("const"),
828 def::DefAssociatedConst(..) => ck("associated const"),
829 def::DefVariant(..) => ck("variant"),
830 def::DefTy(_, false) => ck("type"),
831 def::DefTy(_, true) => ck("enum"),
832 def::DefTrait(..) => ck("trait"),
833 def::DefStruct(..) => ck("struct"),
834 def::DefMethod(..) => ck("method"),
835 def::DefMod(..) => ck("module"),
840 // Checks that a method is in scope.
841 fn check_method(&mut self, span: Span, method_def_id: DefId,
843 match self.tcx.impl_or_trait_item(method_def_id).container() {
844 ty::ImplContainer(_) => {
845 self.check_static_method(span, method_def_id, name)
847 // Trait methods are always all public. The only controlling factor
848 // is whether the trait itself is accessible or not.
849 ty::TraitContainer(trait_def_id) => {
850 self.report_error(self.ensure_public(span, trait_def_id,
851 None, "source trait"));
857 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
858 fn visit_item(&mut self, item: &hir::Item) {
859 if let hir::ItemUse(ref vpath) = item.node {
860 if let hir::ViewPathList(ref prefix, ref list) = vpath.node {
863 hir::PathListIdent { id, name, .. } => {
864 debug!("privacy - ident item {}", id);
865 self.check_path(pid.span, id, name.name);
867 hir::PathListMod { id, .. } => {
868 debug!("privacy - mod item {}", id);
869 let name = prefix.segments.last().unwrap().identifier.name;
870 self.check_path(pid.span, id, name);
876 let orig_curitem = replace(&mut self.curitem, item.id);
877 visit::walk_item(self, item);
878 self.curitem = orig_curitem;
881 fn visit_expr(&mut self, expr: &hir::Expr) {
883 hir::ExprField(ref base, ident) => {
884 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
885 self.check_field(expr.span,
887 def.struct_variant(),
888 NamedField(ident.node.name));
891 hir::ExprTupField(ref base, idx) => {
892 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
893 self.check_field(expr.span,
895 def.struct_variant(),
896 UnnamedField(idx.node));
899 hir::ExprMethodCall(ident, _, _) => {
900 let method_call = ty::MethodCall::expr(expr.id);
901 let method = self.tcx.tables.borrow().method_map[&method_call];
902 debug!("(privacy checking) checking impl method");
903 self.check_method(expr.span, method.def_id, ident.node.name);
905 hir::ExprStruct(..) => {
906 let adt = self.tcx.expr_ty(expr).ty_adt_def().unwrap();
907 let variant = adt.variant_of_def(self.tcx.resolve_expr(expr));
908 // RFC 736: ensure all unmentioned fields are visible.
909 // Rather than computing the set of unmentioned fields
910 // (i.e. `all_fields - fields`), just check them all.
911 for field in &variant.fields {
912 self.check_field(expr.span, adt, variant, NamedField(field.name));
915 hir::ExprPath(..) => {
917 if let def::DefStruct(_) = self.tcx.resolve_expr(expr) {
918 let expr_ty = self.tcx.expr_ty(expr);
919 let def = match expr_ty.sty {
920 ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
921 output: ty::FnConverging(ty), ..
924 }.ty_adt_def().unwrap();
925 let any_priv = def.struct_variant().fields.iter().any(|f| {
926 f.vis != hir::Public && (
928 !self.private_accessible(f.did.node))
932 self.tcx.sess.span_err(expr.span,
933 "cannot invoke tuple struct constructor \
934 with private fields");
941 visit::walk_expr(self, expr);
944 fn visit_pat(&mut self, pattern: &hir::Pat) {
945 // Foreign functions do not have their patterns mapped in the def_map,
946 // and there's nothing really relevant there anyway, so don't bother
947 // checking privacy. If you can name the type then you can pass it to an
948 // external C function anyway.
949 if self.in_foreign { return }
952 hir::PatStruct(_, ref fields, _) => {
953 let adt = self.tcx.pat_ty(pattern).ty_adt_def().unwrap();
954 let def = self.tcx.def_map.borrow().get(&pattern.id).unwrap().full_def();
955 let variant = adt.variant_of_def(def);
956 for field in fields {
957 self.check_field(pattern.span, adt, variant,
958 NamedField(field.node.ident.name));
962 // Patterns which bind no fields are allowable (the path is check
964 hir::PatEnum(_, Some(ref fields)) => {
965 match self.tcx.pat_ty(pattern).sty {
966 ty::TyStruct(def, _) => {
967 for (i, field) in fields.iter().enumerate() {
968 if let hir::PatWild(..) = field.node {
971 self.check_field(field.span,
973 def.struct_variant(),
978 // enum fields have no privacy at this time
987 visit::walk_pat(self, pattern);
990 fn visit_foreign_item(&mut self, fi: &hir::ForeignItem) {
991 self.in_foreign = true;
992 visit::walk_foreign_item(self, fi);
993 self.in_foreign = false;
996 fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
997 self.check_path(path.span, id, path.segments.last().unwrap().identifier.name);
998 visit::walk_path(self, path);
1002 ////////////////////////////////////////////////////////////////////////////////
1003 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1004 ////////////////////////////////////////////////////////////////////////////////
1006 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1007 tcx: &'a ty::ctxt<'tcx>,
1011 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1012 fn visit_item(&mut self, item: &hir::Item) {
1014 self.check_all_inherited(item);
1016 self.check_sane_privacy(item);
1019 let in_fn = self.in_fn;
1020 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1021 hir::ItemMod(..) => false, // modules turn privacy back on
1022 _ => in_fn, // otherwise we inherit
1024 visit::walk_item(self, item);
1025 self.in_fn = orig_in_fn;
1028 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v hir::FnDecl,
1029 b: &'v hir::Block, s: Span, _: ast::NodeId) {
1030 // This catches both functions and methods
1031 let orig_in_fn = replace(&mut self.in_fn, true);
1032 visit::walk_fn(self, fk, fd, b, s);
1033 self.in_fn = orig_in_fn;
1037 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1038 /// Validates all of the visibility qualifiers placed on the item given. This
1039 /// ensures that there are no extraneous qualifiers that don't actually do
1040 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1041 /// later on down the road...
1042 fn check_sane_privacy(&self, item: &hir::Item) {
1044 let check_inherited = |sp: Span, vis: hir::Visibility, note: &str| {
1045 if vis != hir::Inherited {
1046 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1047 if !note.is_empty() {
1048 tcx.sess.span_note(sp, note);
1053 // implementations of traits don't need visibility qualifiers because
1054 // that's controlled by having the trait in scope.
1055 hir::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1056 check_inherited(item.span, item.vis,
1057 "visibility qualifiers have no effect on trait \
1059 for impl_item in impl_items {
1060 check_inherited(impl_item.span, impl_item.vis, "");
1064 hir::ItemImpl(..) => {
1065 check_inherited(item.span, item.vis,
1066 "place qualifiers on individual methods instead");
1068 hir::ItemForeignMod(..) => {
1069 check_inherited(item.span, item.vis,
1070 "place qualifiers on individual functions \
1074 hir::ItemEnum(ref def, _) => {
1075 for v in &def.variants {
1078 if item.vis == hir::Public {
1079 tcx.sess.span_err(v.span, "unnecessary `pub` \
1083 hir::Inherited => {}
1088 hir::ItemTrait(..) | hir::ItemDefaultImpl(..) |
1089 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemStruct(..) |
1090 hir::ItemFn(..) | hir::ItemMod(..) | hir::ItemTy(..) |
1091 hir::ItemExternCrate(_) | hir::ItemUse(_) => {}
1095 /// When inside of something like a function or a method, visibility has no
1096 /// control over anything so this forbids any mention of any visibility
1097 fn check_all_inherited(&self, item: &hir::Item) {
1099 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: hir::Visibility) {
1100 if vis != hir::Inherited {
1101 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1104 let check_struct = |def: &hir::StructDef| {
1105 for f in &def.fields {
1107 hir::NamedField(_, p) => check_inherited(tcx, f.span, p),
1108 hir::UnnamedField(..) => {}
1112 check_inherited(tcx, item.span, item.vis);
1114 hir::ItemImpl(_, _, _, _, _, ref impl_items) => {
1115 for impl_item in impl_items {
1116 match impl_item.node {
1117 hir::MethodImplItem(..) => {
1118 check_inherited(tcx, impl_item.span, impl_item.vis);
1124 hir::ItemForeignMod(ref fm) => {
1125 for i in &fm.items {
1126 check_inherited(tcx, i.span, i.vis);
1129 hir::ItemEnum(ref def, _) => {
1130 for v in &def.variants {
1131 check_inherited(tcx, v.span, v.node.vis);
1135 hir::ItemStruct(ref def, _) => check_struct(&**def),
1137 hir::ItemExternCrate(_) | hir::ItemUse(_) |
1138 hir::ItemTrait(..) | hir::ItemDefaultImpl(..) |
1139 hir::ItemStatic(..) | hir::ItemConst(..) |
1140 hir::ItemFn(..) | hir::ItemMod(..) | hir::ItemTy(..) => {}
1145 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1146 tcx: &'a ty::ctxt<'tcx>,
1147 exported_items: &'a ExportedItems,
1148 public_items: &'a PublicItems,
1152 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1153 inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1154 /// whether the type refers to private types.
1155 contains_private: bool,
1156 /// whether we've recurred at all (i.e. if we're pointing at the
1157 /// first type on which visit_ty was called).
1158 at_outer_type: bool,
1159 // whether that first type is a public path.
1160 outer_type_is_public_path: bool,
1163 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1164 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1165 let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) {
1166 // `int` etc. (None doesn't seem to occur.)
1167 None | Some(def::DefPrimTy(..)) => return false,
1168 Some(def) => def.def_id(),
1170 // A path can only be private if:
1171 // it's in this crate...
1172 if !did.is_local() {
1176 // .. and it corresponds to a private type in the AST (this returns
1177 // None for type parameters)
1178 match self.tcx.map.find(did.node) {
1179 Some(ast_map::NodeItem(ref item)) => item.vis != hir::Public,
1180 Some(_) | None => false,
1184 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1185 // FIXME: this would preferably be using `exported_items`, but all
1186 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1187 self.public_items.contains(&trait_id)
1190 fn check_ty_param_bound(&self,
1191 ty_param_bound: &hir::TyParamBound) {
1192 if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1193 if !self.tcx.sess.features.borrow().visible_private_types &&
1194 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1195 let span = trait_ref.trait_ref.path.span;
1196 self.tcx.sess.span_err(span, "private trait in exported type \
1202 fn item_is_public(&self, id: &ast::NodeId, vis: hir::Visibility) -> bool {
1203 self.exported_items.contains(id) || vis == hir::Public
1207 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1208 fn visit_ty(&mut self, ty: &hir::Ty) {
1209 if let hir::TyPath(..) = ty.node {
1210 if self.inner.path_is_private_type(ty.id) {
1211 self.contains_private = true;
1212 // found what we're looking for so let's stop
1215 } else if self.at_outer_type {
1216 self.outer_type_is_public_path = true;
1219 self.at_outer_type = false;
1220 visit::walk_ty(self, ty)
1223 // don't want to recurse into [, .. expr]
1224 fn visit_expr(&mut self, _: &hir::Expr) {}
1227 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1228 fn visit_item(&mut self, item: &hir::Item) {
1230 // contents of a private mod can be reexported, so we need
1231 // to check internals.
1232 hir::ItemMod(_) => {}
1234 // An `extern {}` doesn't introduce a new privacy
1235 // namespace (the contents have their own privacies).
1236 hir::ItemForeignMod(_) => {}
1238 hir::ItemTrait(_, _, ref bounds, _) => {
1239 if !self.trait_is_public(item.id) {
1243 for bound in bounds.iter() {
1244 self.check_ty_param_bound(bound)
1248 // impls need some special handling to try to offer useful
1249 // error messages without (too many) false positives
1250 // (i.e. we could just return here to not check them at
1251 // all, or some worse estimation of whether an impl is
1252 // publicly visible).
1253 hir::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1254 // `impl [... for] Private` is never visible.
1255 let self_contains_private;
1256 // impl [... for] Public<...>, but not `impl [... for]
1257 // Vec<Public>` or `(Public,)` etc.
1258 let self_is_public_path;
1260 // check the properties of the Self type:
1262 let mut visitor = CheckTypeForPrivatenessVisitor {
1264 contains_private: false,
1265 at_outer_type: true,
1266 outer_type_is_public_path: false,
1268 visitor.visit_ty(&**self_);
1269 self_contains_private = visitor.contains_private;
1270 self_is_public_path = visitor.outer_type_is_public_path;
1273 // miscellaneous info about the impl
1275 // `true` iff this is `impl Private for ...`.
1276 let not_private_trait =
1277 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1279 let did = self.tcx.trait_ref_to_def_id(tr);
1281 !did.is_local() || self.trait_is_public(did.node)
1284 // `true` iff this is a trait impl or at least one method is public.
1286 // `impl Public { $( fn ...() {} )* }` is not visible.
1288 // This is required over just using the methods' privacy
1289 // directly because we might have `impl<T: Foo<Private>> ...`,
1290 // and we shouldn't warn about the generics if all the methods
1291 // are private (because `T` won't be visible externally).
1292 let trait_or_some_public_method =
1293 trait_ref.is_some() ||
1296 match impl_item.node {
1297 hir::ConstImplItem(..) |
1298 hir::MethodImplItem(..) => {
1299 self.exported_items.contains(&impl_item.id)
1301 hir::TypeImplItem(_) => 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 hir::ConstImplItem(..) |
1321 hir::MethodImplItem(..)
1322 if self.item_is_public(&impl_item.id, impl_item.vis) =>
1324 visit::walk_impl_item(self, impl_item)
1326 hir::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 hir::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 hir::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 hir::MethodImplItem(ref sig, _) => {
1370 if sig.explicit_self.node == hir::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 hir::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: &hir::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 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1415 for bound in bound_pred.bounds.iter() {
1416 self.check_ty_param_bound(bound)
1419 &hir::WherePredicate::RegionPredicate(_) => {}
1420 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1421 self.visit_ty(&*eq_pred.ty);
1427 fn visit_foreign_item(&mut self, item: &hir::ForeignItem) {
1428 if self.exported_items.contains(&item.id) {
1429 visit::walk_foreign_item(self, item)
1433 fn visit_ty(&mut self, t: &hir::Ty) {
1434 debug!("VisiblePrivateTypesVisitor checking ty {:?}", t);
1435 if let hir::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: &hir::Variant, g: &hir::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: &hir::StructField) {
1454 hir::NamedField(_, vis) if vis == hir::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, _: &hir::Block) {}
1467 fn visit_expr(&mut self, _: &hir::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);