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/",
21 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
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;
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::{self, Ty};
44 use rustc::util::nodemap::{NodeMap, NodeSet};
47 use syntax::ast_util::{is_local, local_def};
48 use syntax::codemap::Span;
49 use syntax::visit::{self, Visitor};
51 type Context<'a, 'tcx> = (&'a ty::MethodMap<'tcx>, &'a def::ExportMap);
53 /// Result of a checking operation - None => no errors were found. Some => an
54 /// error and contains the span and message for reporting that error and
55 /// optionally the same for a note about the error.
56 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
58 ////////////////////////////////////////////////////////////////////////////////
59 /// The parent visitor, used to determine what's the parent of what (node-wise)
60 ////////////////////////////////////////////////////////////////////////////////
62 struct ParentVisitor {
63 parents: NodeMap<ast::NodeId>,
64 curparent: ast::NodeId,
67 impl<'v> Visitor<'v> for ParentVisitor {
68 fn visit_item(&mut self, item: &ast::Item) {
69 self.parents.insert(item.id, self.curparent);
71 let prev = self.curparent;
73 ast::ItemMod(..) => { self.curparent = item.id; }
74 // Enum variants are parented to the enum definition itself because
75 // they inherit privacy
76 ast::ItemEnum(ref def, _) => {
77 for variant in &def.variants {
78 // The parent is considered the enclosing enum because the
79 // enum will dictate the privacy visibility of this variant
81 self.parents.insert(variant.node.id, item.id);
85 // Trait methods are always considered "public", but if the trait is
86 // private then we need some private item in the chain from the
87 // method to the root. In this case, if the trait is private, then
88 // parent all the methods to the trait to indicate that they're
90 ast::ItemTrait(_, _, _, ref trait_items) if item.vis != ast::Public => {
91 for trait_item in trait_items {
92 self.parents.insert(trait_item.id, item.id);
98 visit::walk_item(self, item);
99 self.curparent = prev;
102 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
103 self.parents.insert(a.id, self.curparent);
104 visit::walk_foreign_item(self, a);
107 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
108 c: &'v ast::Block, d: Span, id: ast::NodeId) {
109 // We already took care of some trait methods above, otherwise things
110 // like impl methods and pub trait methods are parented to the
111 // containing module, not the containing trait.
112 if !self.parents.contains_key(&id) {
113 self.parents.insert(id, self.curparent);
115 visit::walk_fn(self, a, b, c, d);
118 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
119 // visit_fn handles methods, but associated consts have to be handled
121 if !self.parents.contains_key(&ii.id) {
122 self.parents.insert(ii.id, self.curparent);
124 visit::walk_impl_item(self, ii);
127 fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
128 _: &'v ast::Generics, n: ast::NodeId) {
129 // Struct constructors are parented to their struct definitions because
130 // they essentially are the struct definitions.
132 Some(id) => { self.parents.insert(id, n); }
136 // While we have the id of the struct definition, go ahead and parent
138 for field in &s.fields {
139 self.parents.insert(field.node.id, self.curparent);
141 visit::walk_struct_def(self, s)
145 ////////////////////////////////////////////////////////////////////////////////
146 /// The embargo visitor, used to determine the exports of the ast
147 ////////////////////////////////////////////////////////////////////////////////
149 struct EmbargoVisitor<'a, 'tcx: 'a> {
150 tcx: &'a ty::ctxt<'tcx>,
151 export_map: &'a def::ExportMap,
153 // This flag is an indicator of whether the previous item in the
154 // hierarchical chain was exported or not. This is the indicator of whether
155 // children should be exported as well. Note that this can flip from false
156 // to true if a reexported module is entered (or an action similar).
159 // This is a list of all exported items in the AST. An exported item is any
160 // function/method/item which is usable by external crates. This essentially
161 // means that the result is "public all the way down", but the "path down"
162 // may jump across private boundaries through reexport statements.
163 exported_items: ExportedItems,
165 // This sets contains all the destination nodes which are publicly
166 // re-exported. This is *not* a set of all reexported nodes, only a set of
167 // all nodes which are reexported *and* reachable from external crates. This
168 // means that the destination of the reexport is exported, and hence the
169 // destination must also be exported.
172 // These two fields are closely related to one another in that they are only
173 // used for generation of the 'PublicItems' set, not for privacy checking at
175 public_items: PublicItems,
179 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
180 // There are checks inside of privacy which depend on knowing whether a
181 // trait should be exported or not. The two current consumers of this are:
183 // 1. Should default methods of a trait be exported?
184 // 2. Should the methods of an implementation of a trait be exported?
186 // The answer to both of these questions partly rely on whether the trait
187 // itself is exported or not. If the trait is somehow exported, then the
188 // answers to both questions must be yes. Right now this question involves
189 // more analysis than is currently done in rustc, so we conservatively
190 // answer "yes" so that all traits need to be exported.
191 fn exported_trait(&self, _id: ast::NodeId) -> bool {
196 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
197 fn visit_item(&mut self, item: &ast::Item) {
198 let orig_all_pub = self.prev_public;
199 self.prev_public = orig_all_pub && item.vis == ast::Public;
200 if self.prev_public {
201 self.public_items.insert(item.id);
204 let orig_all_exported = self.prev_exported;
206 // impls/extern blocks do not break the "public chain" because they
207 // cannot have visibility qualifiers on them anyway
208 ast::ItemImpl(..) | ast::ItemDefaultImpl(..) | ast::ItemForeignMod(..) => {}
210 // Traits are a little special in that even if they themselves are
211 // not public they may still be exported.
212 ast::ItemTrait(..) => {
213 self.prev_exported = self.exported_trait(item.id);
216 // Private by default, hence we only retain the "public chain" if
217 // `pub` is explicitly listed.
220 (orig_all_exported && item.vis == ast::Public) ||
221 self.reexports.contains(&item.id);
225 let public_first = self.prev_exported &&
226 self.exported_items.insert(item.id);
229 // Enum variants inherit from their parent, so if the enum is
230 // public all variants are public unless they're explicitly priv
231 ast::ItemEnum(ref def, _) if public_first => {
232 for variant in &def.variants {
233 self.exported_items.insert(variant.node.id);
234 self.public_items.insert(variant.node.id);
238 // Implementations are a little tricky to determine what's exported
239 // out of them. Here's a few cases which are currently defined:
241 // * Impls for private types do not need to export their methods
242 // (either public or private methods)
244 // * Impls for public types only have public methods exported
246 // * Public trait impls for public types must have all methods
249 // * Private trait impls for public types can be ignored
251 // * Public trait impls for private types have their methods
252 // exported. I'm not entirely certain that this is the correct
253 // thing to do, but I have seen use cases of where this will cause
254 // undefined symbols at linkage time if this case is not handled.
256 // * Private trait impls for private types can be completely ignored
257 ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
258 let public_ty = match ty.node {
260 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
261 def::DefPrimTy(..) => true,
263 let did = def.def_id();
265 self.exported_items.contains(&did.node)
271 let tr = self.tcx.impl_trait_ref(local_def(item.id));
272 let public_trait = tr.clone().map_or(false, |tr| {
273 !is_local(tr.def_id) ||
274 self.exported_items.contains(&tr.def_id.node)
277 if public_ty || public_trait {
278 for impl_item in impl_items {
279 match impl_item.node {
280 ast::ConstImplItem(..) => {
281 if (public_ty && impl_item.vis == ast::Public)
283 self.exported_items.insert(impl_item.id);
286 ast::MethodImplItem(ref sig, _) => {
287 let meth_public = match sig.explicit_self.node {
288 ast::SelfStatic => public_ty,
290 } && impl_item.vis == ast::Public;
291 if meth_public || tr.is_some() {
292 self.exported_items.insert(impl_item.id);
295 ast::TypeImplItem(_) |
296 ast::MacImplItem(_) => {}
302 // Default methods on traits are all public so long as the trait
304 ast::ItemTrait(_, _, _, ref trait_items) if public_first => {
305 for trait_item in trait_items {
306 debug!("trait item {}", trait_item.id);
307 self.exported_items.insert(trait_item.id);
311 // Struct constructors are public if the struct is all public.
312 ast::ItemStruct(ref def, _) if public_first => {
314 Some(id) => { self.exported_items.insert(id); }
317 // fields can be public or private, so lets check
318 for field in &def.fields {
319 let vis = match field.node.kind {
320 ast::NamedField(_, vis) | ast::UnnamedField(vis) => vis
322 if vis == ast::Public {
323 self.public_items.insert(field.node.id);
328 ast::ItemTy(ref ty, _) if public_first => {
329 if let ast::TyPath(..) = ty.node {
330 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
331 def::DefPrimTy(..) | def::DefTyParam(..) => {},
333 let did = def.def_id();
335 self.exported_items.insert(did.node);
345 visit::walk_item(self, item);
347 self.prev_exported = orig_all_exported;
348 self.prev_public = orig_all_pub;
351 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
352 if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) {
353 self.exported_items.insert(a.id);
357 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) {
358 // This code is here instead of in visit_item so that the
359 // crate module gets processed as well.
360 if self.prev_exported {
361 assert!(self.export_map.contains_key(&id), "wut {}", id);
362 for export in self.export_map.get(&id).unwrap() {
363 if is_local(export.def_id) {
364 self.reexports.insert(export.def_id.node);
368 visit::walk_mod(self, m)
372 ////////////////////////////////////////////////////////////////////////////////
373 /// The privacy visitor, where privacy checks take place (violations reported)
374 ////////////////////////////////////////////////////////////////////////////////
376 struct PrivacyVisitor<'a, 'tcx: 'a> {
377 tcx: &'a ty::ctxt<'tcx>,
378 curitem: ast::NodeId,
380 parents: NodeMap<ast::NodeId>,
381 external_exports: ExternalExports,
387 DisallowedBy(ast::NodeId),
391 UnnamedField(usize), // index
392 // (Name, not Ident, because struct fields are not macro-hygienic)
393 NamedField(ast::Name),
396 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
397 // used when debugging
398 fn nodestr(&self, id: ast::NodeId) -> String {
399 self.tcx.map.node_to_string(id).to_string()
402 // Determines whether the given definition is public from the point of view
403 // of the current item.
404 fn def_privacy(&self, did: ast::DefId) -> PrivacyResult {
406 if self.external_exports.contains(&did) {
407 debug!("privacy - {:?} was externally exported", did);
410 debug!("privacy - is {:?} a public method", did);
412 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
413 Some(&ty::ConstTraitItem(ref ac)) => {
414 debug!("privacy - it's a const: {:?}", *ac);
416 ty::TraitContainer(id) => {
417 debug!("privacy - recursing on trait {:?}", id);
420 ty::ImplContainer(id) => {
421 match self.tcx.impl_trait_ref(id) {
423 debug!("privacy - impl of trait {:?}", id);
424 self.def_privacy(t.def_id)
427 debug!("privacy - found inherent \
428 associated constant {:?}",
430 if ac.vis == ast::Public {
440 Some(&ty::MethodTraitItem(ref meth)) => {
441 debug!("privacy - well at least it's a method: {:?}",
443 match meth.container {
444 ty::TraitContainer(id) => {
445 debug!("privacy - recursing on trait {:?}", id);
448 ty::ImplContainer(id) => {
449 match self.tcx.impl_trait_ref(id) {
451 debug!("privacy - impl of trait {:?}", id);
452 self.def_privacy(t.def_id)
455 debug!("privacy - found a method {:?}",
457 if meth.vis == ast::Public {
467 Some(&ty::TypeTraitItem(ref typedef)) => {
468 match typedef.container {
469 ty::TraitContainer(id) => {
470 debug!("privacy - recursing on trait {:?}", id);
473 ty::ImplContainer(id) => {
474 match self.tcx.impl_trait_ref(id) {
476 debug!("privacy - impl of trait {:?}", id);
477 self.def_privacy(t.def_id)
480 debug!("privacy - found a typedef {:?}",
482 if typedef.vis == ast::Public {
493 debug!("privacy - nope, not even a method");
499 debug!("privacy - local {} not public all the way down",
500 self.tcx.map.node_to_string(did.node));
501 // return quickly for things in the same module
502 if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
503 debug!("privacy - same parent, we're done here");
507 // We now know that there is at least one private member between the
508 // destination and the root.
509 let mut closest_private_id = did.node;
511 debug!("privacy - examining {}", self.nodestr(closest_private_id));
512 let vis = match self.tcx.map.find(closest_private_id) {
513 // If this item is a method, then we know for sure that it's an
514 // actual method and not a static method. The reason for this is
515 // that these cases are only hit in the ExprMethodCall
516 // expression, and ExprCall will have its path checked later
517 // (the path of the trait/impl) if it's a static method.
519 // With this information, then we can completely ignore all
520 // trait methods. The privacy violation would be if the trait
521 // couldn't get imported, not if the method couldn't be used
522 // (all trait methods are public).
524 // However, if this is an impl method, then we dictate this
525 // decision solely based on the privacy of the method
527 // FIXME(#10573) is this the right behavior? Why not consider
528 // where the method was defined?
529 Some(ast_map::NodeImplItem(ii)) => {
531 ast::ConstImplItem(..) |
532 ast::MethodImplItem(..) => {
533 let imp = self.tcx.map
534 .get_parent_did(closest_private_id);
535 match self.tcx.impl_trait_ref(imp) {
536 Some(..) => return Allowable,
537 _ if ii.vis == ast::Public => {
543 ast::TypeImplItem(_) |
544 ast::MacImplItem(_) => 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 ast::Public // need to move up a level (to the enum)
562 if vis != ast::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: ast::DefId,
632 source_did: Option<ast::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 ast::ItemImpl(_, _, _, _, ref ty, _) => {
660 ast::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!(is_local(did));
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 ast::ItemMod(..) => "module",
679 ast::ItemTrait(..) => "trait",
680 ast::ItemStruct(..) => "struct",
681 ast::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 == ast::Public ||
702 (is_local(field.did) && 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,
724 method_id: ast::DefId,
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: ast::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: ast::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: &ast::Item) {
859 if let ast::ItemUse(ref vpath) = item.node {
860 if let ast::ViewPathList(ref prefix, ref list) = vpath.node {
863 ast::PathListIdent { id, name, .. } => {
864 debug!("privacy - ident item {}", id);
865 self.check_path(pid.span, id, name.name);
867 ast::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: &ast::Expr) {
883 ast::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 ast::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 ast::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 ast::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 ast::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 != ast::Public && (
928 !self.private_accessible(f.did.node))
931 self.tcx.sess.span_err(expr.span,
932 "cannot invoke tuple struct constructor \
933 with private fields");
940 visit::walk_expr(self, expr);
943 fn visit_pat(&mut self, pattern: &ast::Pat) {
944 // Foreign functions do not have their patterns mapped in the def_map,
945 // and there's nothing really relevant there anyway, so don't bother
946 // checking privacy. If you can name the type then you can pass it to an
947 // external C function anyway.
948 if self.in_foreign { return }
951 ast::PatStruct(_, ref fields, _) => {
952 let adt = self.tcx.pat_ty(pattern).ty_adt_def().unwrap();
953 let def = self.tcx.def_map.borrow().get(&pattern.id).unwrap().full_def();
954 let variant = adt.variant_of_def(def);
955 for field in fields {
956 self.check_field(pattern.span, adt, variant,
957 NamedField(field.node.ident.name));
961 // Patterns which bind no fields are allowable (the path is check
963 ast::PatEnum(_, Some(ref fields)) => {
964 match self.tcx.pat_ty(pattern).sty {
965 ty::TyStruct(def, _) => {
966 for (i, field) in fields.iter().enumerate() {
967 if let ast::PatWild(..) = field.node {
970 self.check_field(field.span,
972 def.struct_variant(),
977 // enum fields have no privacy at this time
986 visit::walk_pat(self, pattern);
989 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
990 self.in_foreign = true;
991 visit::walk_foreign_item(self, fi);
992 self.in_foreign = false;
995 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
996 self.check_path(path.span, id, path.segments.last().unwrap().identifier.name);
997 visit::walk_path(self, path);
1001 ////////////////////////////////////////////////////////////////////////////////
1002 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1003 ////////////////////////////////////////////////////////////////////////////////
1005 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1006 tcx: &'a ty::ctxt<'tcx>,
1010 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1011 fn visit_item(&mut self, item: &ast::Item) {
1013 self.check_all_inherited(item);
1015 self.check_sane_privacy(item);
1018 let in_fn = self.in_fn;
1019 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1020 ast::ItemMod(..) => false, // modules turn privacy back on
1021 _ => in_fn, // otherwise we inherit
1023 visit::walk_item(self, item);
1024 self.in_fn = orig_in_fn;
1027 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1028 b: &'v ast::Block, s: Span, _: ast::NodeId) {
1029 // This catches both functions and methods
1030 let orig_in_fn = replace(&mut self.in_fn, true);
1031 visit::walk_fn(self, fk, fd, b, s);
1032 self.in_fn = orig_in_fn;
1036 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1037 /// Validates all of the visibility qualifiers placed on the item given. This
1038 /// ensures that there are no extraneous qualifiers that don't actually do
1039 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1040 /// later on down the road...
1041 fn check_sane_privacy(&self, item: &ast::Item) {
1043 let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
1044 if vis != ast::Inherited {
1045 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1046 if !note.is_empty() {
1047 tcx.sess.span_note(sp, note);
1052 // implementations of traits don't need visibility qualifiers because
1053 // that's controlled by having the trait in scope.
1054 ast::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1055 check_inherited(item.span, item.vis,
1056 "visibility qualifiers have no effect on trait \
1058 for impl_item in impl_items {
1059 check_inherited(impl_item.span, impl_item.vis, "");
1063 ast::ItemImpl(..) => {
1064 check_inherited(item.span, item.vis,
1065 "place qualifiers on individual methods instead");
1067 ast::ItemForeignMod(..) => {
1068 check_inherited(item.span, item.vis,
1069 "place qualifiers on individual functions \
1073 ast::ItemEnum(ref def, _) => {
1074 for v in &def.variants {
1077 if item.vis == ast::Public {
1078 tcx.sess.span_err(v.span, "unnecessary `pub` \
1082 ast::Inherited => {}
1087 ast::ItemTrait(..) | ast::ItemDefaultImpl(..) |
1088 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemStruct(..) |
1089 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1090 ast::ItemExternCrate(_) | ast::ItemUse(_) | ast::ItemMac(..) => {}
1094 /// When inside of something like a function or a method, visibility has no
1095 /// control over anything so this forbids any mention of any visibility
1096 fn check_all_inherited(&self, item: &ast::Item) {
1098 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
1099 if vis != ast::Inherited {
1100 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1103 let check_struct = |def: &ast::StructDef| {
1104 for f in &def.fields {
1106 ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
1107 ast::UnnamedField(..) => {}
1111 check_inherited(tcx, item.span, item.vis);
1113 ast::ItemImpl(_, _, _, _, _, ref impl_items) => {
1114 for impl_item in impl_items {
1115 match impl_item.node {
1116 ast::MethodImplItem(..) => {
1117 check_inherited(tcx, impl_item.span, impl_item.vis);
1123 ast::ItemForeignMod(ref fm) => {
1124 for i in &fm.items {
1125 check_inherited(tcx, i.span, i.vis);
1128 ast::ItemEnum(ref def, _) => {
1129 for v in &def.variants {
1130 check_inherited(tcx, v.span, v.node.vis);
1134 ast::ItemStruct(ref def, _) => check_struct(&**def),
1136 ast::ItemExternCrate(_) | ast::ItemUse(_) |
1137 ast::ItemTrait(..) | ast::ItemDefaultImpl(..) |
1138 ast::ItemStatic(..) | ast::ItemConst(..) |
1139 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1140 ast::ItemMac(..) => {}
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...
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 != ast::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: &ast::TyParamBound) {
1192 if let ast::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: ast::Visibility) -> bool {
1203 self.exported_items.contains(id) || vis == ast::Public
1207 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1208 fn visit_ty(&mut self, ty: &ast::Ty) {
1209 if let ast::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, _: &ast::Expr) {}
1227 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1228 fn visit_item(&mut self, item: &ast::Item) {
1230 // contents of a private mod can be reexported, so we need
1231 // to check internals.
1232 ast::ItemMod(_) => {}
1234 // An `extern {}` doesn't introduce a new privacy
1235 // namespace (the contents have their own privacies).
1236 ast::ItemForeignMod(_) => {}
1238 ast::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 ast::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 !is_local(did) || 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 ast::ConstImplItem(..) |
1298 ast::MethodImplItem(..) => {
1299 self.exported_items.contains(&impl_item.id)
1301 ast::TypeImplItem(_) |
1302 ast::MacImplItem(_) => false,
1306 if !self_contains_private &&
1307 not_private_trait &&
1308 trait_or_some_public_method {
1310 visit::walk_generics(self, g);
1314 for impl_item in impl_items {
1315 // This is where we choose whether to walk down
1316 // further into the impl to check its items. We
1317 // should only walk into public items so that we
1318 // don't erroneously report errors for private
1319 // types in private items.
1320 match impl_item.node {
1321 ast::ConstImplItem(..) |
1322 ast::MethodImplItem(..)
1323 if self.item_is_public(&impl_item.id, impl_item.vis) =>
1325 visit::walk_impl_item(self, impl_item)
1327 ast::TypeImplItem(..) => {
1328 visit::walk_impl_item(self, impl_item)
1335 // Any private types in a trait impl fall into three
1337 // 1. mentioned in the trait definition
1338 // 2. mentioned in the type params/generics
1339 // 3. mentioned in the associated types of the impl
1341 // Those in 1. can only occur if the trait is in
1342 // this crate and will've been warned about on the
1343 // trait definition (there's no need to warn twice
1344 // so we don't check the methods).
1346 // Those in 2. are warned via walk_generics and this
1348 visit::walk_path(self, &tr.path);
1350 // Those in 3. are warned with this call.
1351 for impl_item in impl_items {
1352 if let ast::TypeImplItem(ref ty) = impl_item.node {
1358 } else if trait_ref.is_none() && self_is_public_path {
1359 // impl Public<Private> { ... }. Any public static
1360 // methods will be visible as `Public::foo`.
1361 let mut found_pub_static = false;
1362 for impl_item in impl_items {
1363 match impl_item.node {
1364 ast::ConstImplItem(..) => {
1365 if self.item_is_public(&impl_item.id, impl_item.vis) {
1366 found_pub_static = true;
1367 visit::walk_impl_item(self, impl_item);
1370 ast::MethodImplItem(ref sig, _) => {
1371 if sig.explicit_self.node == ast::SelfStatic &&
1372 self.item_is_public(&impl_item.id, impl_item.vis) {
1373 found_pub_static = true;
1374 visit::walk_impl_item(self, impl_item);
1380 if found_pub_static {
1381 visit::walk_generics(self, g)
1387 // `type ... = ...;` can contain private types, because
1388 // we're introducing a new name.
1389 ast::ItemTy(..) => return,
1391 // not at all public, so we don't care
1392 _ if !self.item_is_public(&item.id, item.vis) => {
1399 // We've carefully constructed it so that if we're here, then
1400 // any `visit_ty`'s will be called on things that are in
1401 // public signatures, i.e. things that we're interested in for
1403 debug!("VisiblePrivateTypesVisitor entering item {:?}", item);
1404 visit::walk_item(self, item);
1407 fn visit_generics(&mut self, generics: &ast::Generics) {
1408 for ty_param in generics.ty_params.iter() {
1409 for bound in ty_param.bounds.iter() {
1410 self.check_ty_param_bound(bound)
1413 for predicate in &generics.where_clause.predicates {
1415 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
1416 for bound in bound_pred.bounds.iter() {
1417 self.check_ty_param_bound(bound)
1420 &ast::WherePredicate::RegionPredicate(_) => {}
1421 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
1422 self.visit_ty(&*eq_pred.ty);
1428 fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
1429 if self.exported_items.contains(&item.id) {
1430 visit::walk_foreign_item(self, item)
1434 fn visit_ty(&mut self, t: &ast::Ty) {
1435 debug!("VisiblePrivateTypesVisitor checking ty {:?}", t);
1436 if let ast::TyPath(_, ref p) = t.node {
1437 if !self.tcx.sess.features.borrow().visible_private_types &&
1438 self.path_is_private_type(t.id) {
1439 self.tcx.sess.span_err(p.span, "private type in exported type signature");
1442 visit::walk_ty(self, t)
1445 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
1446 if self.exported_items.contains(&v.node.id) {
1447 self.in_variant = true;
1448 visit::walk_variant(self, v, g);
1449 self.in_variant = false;
1453 fn visit_struct_field(&mut self, s: &ast::StructField) {
1455 ast::NamedField(_, vis) if vis == ast::Public || self.in_variant => {
1456 visit::walk_struct_field(self, s);
1463 // we don't need to introspect into these at all: an
1464 // expression/block context can't possibly contain exported things.
1465 // (Making them no-ops stops us from traversing the whole AST without
1466 // having to be super careful about our `walk_...` calls above.)
1467 fn visit_block(&mut self, _: &ast::Block) {}
1468 fn visit_expr(&mut self, _: &ast::Expr) {}
1471 pub fn check_crate(tcx: &ty::ctxt,
1472 export_map: &def::ExportMap,
1473 external_exports: ExternalExports)
1474 -> (ExportedItems, PublicItems) {
1475 let krate = tcx.map.krate();
1477 // Figure out who everyone's parent is
1478 let mut visitor = ParentVisitor {
1480 curparent: ast::DUMMY_NODE_ID,
1482 visit::walk_crate(&mut visitor, krate);
1484 // Use the parent map to check the privacy of everything
1485 let mut visitor = PrivacyVisitor {
1486 curitem: ast::DUMMY_NODE_ID,
1489 parents: visitor.parents,
1490 external_exports: external_exports,
1492 visit::walk_crate(&mut visitor, krate);
1494 // Sanity check to make sure that all privacy usage and controls are
1496 let mut visitor = SanePrivacyVisitor {
1500 visit::walk_crate(&mut visitor, krate);
1502 tcx.sess.abort_if_errors();
1504 // Build up a set of all exported items in the AST. This is a set of all
1505 // items which are reachable from external crates based on visibility.
1506 let mut visitor = EmbargoVisitor {
1508 exported_items: NodeSet(),
1509 public_items: NodeSet(),
1510 reexports: NodeSet(),
1511 export_map: export_map,
1512 prev_exported: true,
1516 let before = visitor.exported_items.len();
1517 visit::walk_crate(&mut visitor, krate);
1518 if before == visitor.exported_items.len() {
1523 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1526 let mut visitor = VisiblePrivateTypesVisitor {
1528 exported_items: &exported_items,
1529 public_items: &public_items,
1532 visit::walk_crate(&mut visitor, krate);
1534 return (exported_items, public_items);