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 #![crate_name = "rustc_privacy"]
12 #![unstable(feature = "rustc_private")]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
18 html_root_url = "http://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;
36 use rustc::metadata::csearch;
37 use rustc::middle::def;
38 use rustc::middle::privacy::ImportUse::*;
39 use rustc::middle::privacy::LastPrivate::*;
40 use rustc::middle::privacy::PrivateDep::*;
41 use rustc::middle::privacy::{ExportedItems, PublicItems, LastPrivateMap};
42 use rustc::middle::privacy::{ExternalExports};
43 use rustc::middle::ty::{MethodTypeParam, MethodStatic};
44 use rustc::middle::ty::{MethodCall, MethodMap, MethodOrigin, MethodParam};
45 use rustc::middle::ty::{MethodStaticClosure, MethodObject};
46 use rustc::middle::ty::{MethodTraitObject};
47 use rustc::middle::ty::{self, Ty};
48 use rustc::util::nodemap::{NodeMap, NodeSet};
50 use syntax::{ast, ast_map};
51 use syntax::ast_util::{is_local, local_def, PostExpansionMethod};
52 use syntax::codemap::Span;
53 use syntax::parse::token;
54 use syntax::visit::{self, Visitor};
56 type Context<'a, 'tcx> = (&'a MethodMap<'tcx>, &'a def::ExportMap);
58 /// Result of a checking operation - None => no errors were found. Some => an
59 /// error and contains the span and message for reporting that error and
60 /// optionally the same for a note about the error.
61 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
63 ////////////////////////////////////////////////////////////////////////////////
64 /// The parent visitor, used to determine what's the parent of what (node-wise)
65 ////////////////////////////////////////////////////////////////////////////////
67 struct ParentVisitor {
68 parents: NodeMap<ast::NodeId>,
69 curparent: ast::NodeId,
72 impl<'v> Visitor<'v> for ParentVisitor {
73 fn visit_item(&mut self, item: &ast::Item) {
74 self.parents.insert(item.id, self.curparent);
76 let prev = self.curparent;
78 ast::ItemMod(..) => { self.curparent = item.id; }
79 // Enum variants are parented to the enum definition itself because
80 // they inherit privacy
81 ast::ItemEnum(ref def, _) => {
82 for variant in &def.variants {
83 // The parent is considered the enclosing enum because the
84 // enum will dictate the privacy visibility of this variant
86 self.parents.insert(variant.node.id, item.id);
90 // Trait methods are always considered "public", but if the trait is
91 // private then we need some private item in the chain from the
92 // method to the root. In this case, if the trait is private, then
93 // parent all the methods to the trait to indicate that they're
95 ast::ItemTrait(_, _, _, ref methods) if item.vis != ast::Public => {
98 ast::ProvidedMethod(ref m) => {
99 self.parents.insert(m.id, item.id);
101 ast::RequiredMethod(ref m) => {
102 self.parents.insert(m.id, item.id);
104 ast::TypeTraitItem(_) => {}
111 visit::walk_item(self, item);
112 self.curparent = prev;
115 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
116 self.parents.insert(a.id, self.curparent);
117 visit::walk_foreign_item(self, a);
120 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
121 c: &'v ast::Block, d: Span, id: ast::NodeId) {
122 // We already took care of some trait methods above, otherwise things
123 // like impl methods and pub trait methods are parented to the
124 // containing module, not the containing trait.
125 if !self.parents.contains_key(&id) {
126 self.parents.insert(id, self.curparent);
128 visit::walk_fn(self, a, b, c, d);
131 fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
132 _: &'v ast::Generics, n: ast::NodeId) {
133 // Struct constructors are parented to their struct definitions because
134 // they essentially are the struct definitions.
136 Some(id) => { self.parents.insert(id, n); }
140 // While we have the id of the struct definition, go ahead and parent
142 for field in &s.fields {
143 self.parents.insert(field.node.id, self.curparent);
145 visit::walk_struct_def(self, s)
149 ////////////////////////////////////////////////////////////////////////////////
150 /// The embargo visitor, used to determine the exports of the ast
151 ////////////////////////////////////////////////////////////////////////////////
153 struct EmbargoVisitor<'a, 'tcx: 'a> {
154 tcx: &'a ty::ctxt<'tcx>,
155 export_map: &'a def::ExportMap,
157 // This flag is an indicator of whether the previous item in the
158 // hierarchical chain was exported or not. This is the indicator of whether
159 // children should be exported as well. Note that this can flip from false
160 // to true if a reexported module is entered (or an action similar).
163 // This is a list of all exported items in the AST. An exported item is any
164 // function/method/item which is usable by external crates. This essentially
165 // means that the result is "public all the way down", but the "path down"
166 // may jump across private boundaries through reexport statements.
167 exported_items: ExportedItems,
169 // This sets contains all the destination nodes which are publicly
170 // re-exported. This is *not* a set of all reexported nodes, only a set of
171 // all nodes which are reexported *and* reachable from external crates. This
172 // means that the destination of the reexport is exported, and hence the
173 // destination must also be exported.
176 // These two fields are closely related to one another in that they are only
177 // used for generation of the 'PublicItems' set, not for privacy checking at
179 public_items: PublicItems,
183 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
184 // There are checks inside of privacy which depend on knowing whether a
185 // trait should be exported or not. The two current consumers of this are:
187 // 1. Should default methods of a trait be exported?
188 // 2. Should the methods of an implementation of a trait be exported?
190 // The answer to both of these questions partly rely on whether the trait
191 // itself is exported or not. If the trait is somehow exported, then the
192 // answers to both questions must be yes. Right now this question involves
193 // more analysis than is currently done in rustc, so we conservatively
194 // answer "yes" so that all traits need to be exported.
195 fn exported_trait(&self, _id: ast::NodeId) -> bool {
200 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
201 fn visit_item(&mut self, item: &ast::Item) {
202 let orig_all_pub = self.prev_public;
203 self.prev_public = orig_all_pub && item.vis == ast::Public;
204 if self.prev_public {
205 self.public_items.insert(item.id);
208 let orig_all_exported = self.prev_exported;
210 // impls/extern blocks do not break the "public chain" because they
211 // cannot have visibility qualifiers on them anyway
212 ast::ItemImpl(..) | ast::ItemForeignMod(..) => {}
214 // Traits are a little special in that even if they themselves are
215 // not public they may still be exported.
216 ast::ItemTrait(..) => {
217 self.prev_exported = self.exported_trait(item.id);
220 // Private by default, hence we only retain the "public chain" if
221 // `pub` is explicitly listed.
224 (orig_all_exported && item.vis == ast::Public) ||
225 self.reexports.contains(&item.id);
229 let public_first = self.prev_exported &&
230 self.exported_items.insert(item.id);
233 // Enum variants inherit from their parent, so if the enum is
234 // public all variants are public unless they're explicitly priv
235 ast::ItemEnum(ref def, _) if public_first => {
236 for variant in &def.variants {
237 self.exported_items.insert(variant.node.id);
241 // Implementations are a little tricky to determine what's exported
242 // out of them. Here's a few cases which are currently defined:
244 // * Impls for private types do not need to export their methods
245 // (either public or private methods)
247 // * Impls for public types only have public methods exported
249 // * Public trait impls for public types must have all methods
252 // * Private trait impls for public types can be ignored
254 // * Public trait impls for private types have their methods
255 // exported. I'm not entirely certain that this is the correct
256 // thing to do, but I have seen use cases of where this will cause
257 // undefined symbols at linkage time if this case is not handled.
259 // * Private trait impls for private types can be completely ignored
260 ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
261 let public_ty = match ty.node {
262 ast::TyPath(_, id) => {
263 match self.tcx.def_map.borrow()[id].clone() {
264 def::DefPrimTy(..) => true,
266 let did = def.def_id();
268 self.exported_items.contains(&did.node)
274 let tr = ty::impl_trait_ref(self.tcx, local_def(item.id));
275 let public_trait = tr.clone().map_or(false, |tr| {
276 !is_local(tr.def_id) ||
277 self.exported_items.contains(&tr.def_id.node)
280 if public_ty || public_trait {
281 for impl_item in impl_items {
283 ast::MethodImplItem(ref method) => {
285 match method.pe_explicit_self().node {
286 ast::SelfStatic => public_ty,
288 } && method.pe_vis() == ast::Public;
289 if meth_public || tr.is_some() {
290 self.exported_items.insert(method.id);
293 ast::TypeImplItem(_) => {}
299 // Default methods on traits are all public so long as the trait
301 ast::ItemTrait(_, _, _, ref methods) if public_first => {
302 for method in methods {
304 ast::ProvidedMethod(ref m) => {
305 debug!("provided {}", m.id);
306 self.exported_items.insert(m.id);
308 ast::RequiredMethod(ref m) => {
309 debug!("required {}", m.id);
310 self.exported_items.insert(m.id);
312 ast::TypeTraitItem(ref t) => {
313 debug!("typedef {}", t.ty_param.id);
314 self.exported_items.insert(t.ty_param.id);
320 // Struct constructors are public if the struct is all public.
321 ast::ItemStruct(ref def, _) if public_first => {
323 Some(id) => { self.exported_items.insert(id); }
328 ast::ItemTy(ref ty, _) if public_first => {
329 if let ast::TyPath(_, id) = ty.node {
330 match self.tcx.def_map.borrow()[id].clone() {
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[id] {
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,
382 last_private_map: LastPrivateMap,
388 DisallowedBy(ast::NodeId),
392 UnnamedField(uint), // 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: ast::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::MethodTraitItem(ref meth)) => {
415 debug!("privacy - well at least it's a method: {:?}",
417 match meth.container {
418 ty::TraitContainer(id) => {
419 debug!("privacy - recursing on trait {:?}", id);
422 ty::ImplContainer(id) => {
423 match ty::impl_trait_ref(self.tcx, id) {
425 debug!("privacy - impl of trait {:?}", id);
426 self.def_privacy(t.def_id)
429 debug!("privacy - found a method {:?}",
431 if meth.vis == ast::Public {
441 Some(&ty::TypeTraitItem(ref typedef)) => {
442 match typedef.container {
443 ty::TraitContainer(id) => {
444 debug!("privacy - recursing on trait {:?}", id);
447 ty::ImplContainer(id) => {
448 match ty::impl_trait_ref(self.tcx, id) {
450 debug!("privacy - impl of trait {:?}", id);
451 self.def_privacy(t.def_id)
454 debug!("privacy - found a typedef {:?}",
456 if typedef.vis == ast::Public {
467 debug!("privacy - nope, not even a method");
473 debug!("privacy - local {} not public all the way down",
474 self.tcx.map.node_to_string(did.node));
475 // return quickly for things in the same module
476 if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
477 debug!("privacy - same parent, we're done here");
481 // We now know that there is at least one private member between the
482 // destination and the root.
483 let mut closest_private_id = did.node;
485 debug!("privacy - examining {}", self.nodestr(closest_private_id));
486 let vis = match self.tcx.map.find(closest_private_id) {
487 // If this item is a method, then we know for sure that it's an
488 // actual method and not a static method. The reason for this is
489 // that these cases are only hit in the ExprMethodCall
490 // expression, and ExprCall will have its path checked later
491 // (the path of the trait/impl) if it's a static method.
493 // With this information, then we can completely ignore all
494 // trait methods. The privacy violation would be if the trait
495 // couldn't get imported, not if the method couldn't be used
496 // (all trait methods are public).
498 // However, if this is an impl method, then we dictate this
499 // decision solely based on the privacy of the method
501 // FIXME(#10573) is this the right behavior? Why not consider
502 // where the method was defined?
503 Some(ast_map::NodeImplItem(ii)) => {
505 ast::MethodImplItem(ref m) => {
506 let imp = self.tcx.map
507 .get_parent_did(closest_private_id);
508 match ty::impl_trait_ref(self.tcx, imp) {
509 Some(..) => return Allowable,
510 _ if m.pe_vis() == ast::Public => {
516 ast::TypeImplItem(_) => return Allowable,
519 Some(ast_map::NodeTraitItem(_)) => {
523 // This is not a method call, extract the visibility as one
524 // would normally look at it
525 Some(ast_map::NodeItem(it)) => it.vis,
526 Some(ast_map::NodeForeignItem(_)) => {
527 self.tcx.map.get_foreign_vis(closest_private_id)
529 Some(ast_map::NodeVariant(..)) => {
530 ast::Public // need to move up a level (to the enum)
534 if vis != ast::Public { break }
535 // if we've reached the root, then everything was allowable and this
537 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
538 closest_private_id = self.parents[closest_private_id];
540 // If we reached the top, then we were public all the way down and
541 // we can allow this access.
542 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
544 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
545 if self.private_accessible(closest_private_id) {
548 DisallowedBy(closest_private_id)
552 /// For a local private node in the AST, this function will determine
553 /// whether the node is accessible by the current module that iteration is
555 fn private_accessible(&self, id: ast::NodeId) -> bool {
556 let parent = self.parents[id];
557 debug!("privacy - accessible parent {}", self.nodestr(parent));
559 // After finding `did`'s closest private member, we roll ourselves back
560 // to see if this private member's parent is anywhere in our ancestry.
561 // By the privacy rules, we can access all of our ancestor's private
562 // members, so that's why we test the parent, and not the did itself.
563 let mut cur = self.curitem;
565 debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
567 // If the relevant parent is in our history, then we're allowed
568 // to look inside any of our ancestor's immediate private items,
569 // so this access is valid.
570 x if x == parent => return true,
572 // If we've reached the root, then we couldn't access this item
573 // in the first place
574 ast::DUMMY_NODE_ID => return false,
580 cur = self.parents[cur];
584 fn report_error(&self, result: CheckResult) -> bool {
587 Some((span, msg, note)) => {
588 self.tcx.sess.span_err(span, &msg[]);
590 Some((span, msg)) => {
591 self.tcx.sess.span_note(span, &msg[])
600 /// Guarantee that a particular definition is public. Returns a CheckResult
601 /// which contains any errors found. These can be reported using `report_error`.
602 /// If the result is `None`, no errors were found.
603 fn ensure_public(&self, span: Span, to_check: ast::DefId,
604 source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
605 let id = match self.def_privacy(to_check) {
606 ExternallyDenied => {
607 return Some((span, format!("{} is private", msg), None))
609 Allowable => return None,
610 DisallowedBy(id) => id,
613 // If we're disallowed by a particular id, then we attempt to give a
614 // nice error message to say why it was disallowed. It was either
615 // because the item itself is private or because its parent is private
616 // and its parent isn't in our ancestry.
617 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
618 return Some((span, format!("{} is private", msg), None));
620 (span, format!("{} is inaccessible", msg))
622 let item = match self.tcx.map.find(id) {
623 Some(ast_map::NodeItem(item)) => {
625 // If an impl disallowed this item, then this is resolve's
626 // way of saying that a struct/enum's static method was
627 // invoked, and the struct/enum itself is private. Crawl
628 // back up the chains to find the relevant struct/enum that
630 ast::ItemImpl(_, _, _, _, ref ty, _) => {
631 let id = match ty.node {
632 ast::TyPath(_, id) => id,
633 _ => return Some((err_span, err_msg, None)),
635 let def = self.tcx.def_map.borrow()[id].clone();
636 let did = def.def_id();
637 assert!(is_local(did));
638 match self.tcx.map.get(did.node) {
639 ast_map::NodeItem(item) => item,
640 _ => self.tcx.sess.span_bug(item.span,
641 "path is not an item")
647 Some(..) | None => return Some((err_span, err_msg, None)),
649 let desc = match item.node {
650 ast::ItemMod(..) => "module",
651 ast::ItemTrait(..) => "trait",
652 ast::ItemStruct(..) => "struct",
653 ast::ItemEnum(..) => "enum",
654 _ => return Some((err_span, err_msg, None))
656 let msg = format!("{} `{}` is private", desc,
657 token::get_ident(item.ident));
658 Some((err_span, err_msg, Some((span, msg))))
661 // Checks that a field is in scope.
662 fn check_field(&mut self,
666 let fields = ty::lookup_struct_fields(self.tcx, id);
667 let field = match name {
668 NamedField(f_name) => {
669 debug!("privacy - check named field {} in struct {:?}", f_name, id);
670 fields.iter().find(|f| f.name == f_name).unwrap()
672 UnnamedField(idx) => &fields[idx]
674 if field.vis == ast::Public ||
675 (is_local(field.id) && self.private_accessible(field.id.node)) {
679 let struct_type = ty::lookup_item_type(self.tcx, id).ty;
680 let struct_desc = match struct_type.sty {
681 ty::ty_struct(_, _) =>
682 format!("struct `{}`", ty::item_path_str(self.tcx, id)),
683 // struct variant fields have inherited visibility
684 ty::ty_enum(..) => return,
685 _ => self.tcx.sess.span_bug(span, "can't find struct for field")
687 let msg = match name {
688 NamedField(name) => format!("field `{}` of {} is private",
689 token::get_name(name), struct_desc),
690 UnnamedField(idx) => format!("field #{} of {} is private",
691 idx + 1, struct_desc),
693 self.tcx.sess.span_err(span, &msg[]);
696 // Given the ID of a method, checks to ensure it's in scope.
697 fn check_static_method(&mut self,
699 method_id: ast::DefId,
701 // If the method is a default method, we need to use the def_id of
702 // the default implementation.
703 let method_id = match ty::impl_or_trait_item(self.tcx, method_id) {
704 ty::MethodTraitItem(method_type) => {
705 method_type.provided_source.unwrap_or(method_id)
707 ty::TypeTraitItem(_) => method_id,
710 let string = token::get_ident(name);
711 self.report_error(self.ensure_public(span,
714 &format!("method `{}`",
718 // Checks that a path is in scope.
719 fn check_path(&mut self, span: Span, path_id: ast::NodeId, path: &ast::Path) {
720 debug!("privacy - path {}", self.nodestr(path_id));
721 let orig_def = self.tcx.def_map.borrow()[path_id].clone();
722 let ck = |tyname: &str| {
723 let ck_public = |def: ast::DefId| {
724 debug!("privacy - ck_public {:?}", def);
725 let name = token::get_ident(path.segments.last().unwrap().identifier);
726 let origdid = orig_def.def_id();
727 self.ensure_public(span,
730 &format!("{} `{}`", tyname, name)[])
733 match self.last_private_map[path_id] {
734 LastMod(AllPublic) => {},
735 LastMod(DependsOn(def)) => {
736 self.report_error(ck_public(def));
738 LastImport { value_priv,
739 value_used: check_value,
741 type_used: check_type } => {
742 // This dance with found_error is because we don't want to
743 // report a privacy error twice for the same directive.
744 let found_error = match (type_priv, check_type) {
745 (Some(DependsOn(def)), Used) => {
746 !self.report_error(ck_public(def))
751 match (value_priv, check_value) {
752 (Some(DependsOn(def)), Used) => {
753 self.report_error(ck_public(def));
758 // If an import is not used in either namespace, we still
759 // want to check that it could be legal. Therefore we check
760 // in both namespaces and only report an error if both would
761 // be illegal. We only report one error, even if it is
762 // illegal to import from both namespaces.
763 match (value_priv, check_value, type_priv, check_type) {
764 (Some(p), Unused, None, _) |
765 (None, _, Some(p), Unused) => {
768 DependsOn(def) => ck_public(def),
771 self.report_error(p);
774 (Some(v), Unused, Some(t), Unused) => {
777 DependsOn(def) => ck_public(def),
781 DependsOn(def) => ck_public(def),
783 if let (Some(_), Some(t)) = (v, t) {
784 self.report_error(Some(t));
792 // FIXME(#12334) Imports can refer to definitions in both the type and
793 // value namespaces. The privacy information is aware of this, but the
794 // def map is not. Therefore the names we work out below will not always
795 // be accurate and we can get slightly wonky error messages (but type
796 // checking is always correct).
797 match self.tcx.def_map.borrow()[path_id].clone() {
798 def::DefStaticMethod(..) => ck("static method"),
799 def::DefFn(..) => ck("function"),
800 def::DefStatic(..) => ck("static"),
801 def::DefConst(..) => ck("const"),
802 def::DefVariant(..) => ck("variant"),
803 def::DefTy(_, false) => ck("type"),
804 def::DefTy(_, true) => ck("enum"),
805 def::DefTrait(..) => ck("trait"),
806 def::DefStruct(..) => ck("struct"),
807 def::DefMethod(_, Some(..), _) => ck("trait method"),
808 def::DefMethod(..) => ck("method"),
809 def::DefMod(..) => ck("module"),
814 // Checks that a method is in scope.
815 fn check_method(&mut self, span: Span, origin: &MethodOrigin,
818 MethodStatic(method_id) => {
819 self.check_static_method(span, method_id, ident)
821 MethodStaticClosure(_) => {}
822 // Trait methods are always all public. The only controlling factor
823 // is whether the trait itself is accessible or not.
824 MethodTypeParam(MethodParam { ref trait_ref, .. }) |
825 MethodTraitObject(MethodObject { ref trait_ref, .. }) => {
826 self.report_error(self.ensure_public(span, trait_ref.def_id,
827 None, "source trait"));
833 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
834 fn visit_item(&mut self, item: &ast::Item) {
836 ast::ItemUse(ref vpath) => {
838 ast::ViewPathSimple(..) | ast::ViewPathGlob(..) => {}
839 ast::ViewPathList(ref prefix, ref list) => {
842 ast::PathListIdent { id, name } => {
843 debug!("privacy - ident item {}", id);
844 let seg = ast::PathSegment {
846 parameters: ast::PathParameters::none(),
848 let segs = vec![seg];
849 let path = ast::Path {
854 self.check_path(pid.span, id, &path);
856 ast::PathListMod { id } => {
857 debug!("privacy - mod item {}", id);
858 self.check_path(pid.span, id, prefix);
867 let orig_curitem = replace(&mut self.curitem, item.id);
868 visit::walk_item(self, item);
869 self.curitem = orig_curitem;
872 fn visit_expr(&mut self, expr: &ast::Expr) {
874 ast::ExprField(ref base, ident) => {
875 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
876 self.check_field(expr.span, id, NamedField(ident.node.name));
879 ast::ExprTupField(ref base, idx) => {
880 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
881 self.check_field(expr.span, id, UnnamedField(idx.node));
884 ast::ExprMethodCall(ident, _, _) => {
885 let method_call = MethodCall::expr(expr.id);
886 match self.tcx.method_map.borrow().get(&method_call) {
888 self.tcx.sess.span_bug(expr.span,
889 "method call not in \
893 debug!("(privacy checking) checking impl method");
894 self.check_method(expr.span, &method.origin, ident.node);
898 ast::ExprStruct(_, ref fields, _) => {
899 match ty::expr_ty(self.tcx, expr).sty {
900 ty::ty_struct(ctor_id, _) => {
901 // RFC 736: ensure all unmentioned fields are visible.
902 // Rather than computing the set of unmentioned fields
903 // (i.e. `all_fields - fields`), just check them all.
904 let all_fields = ty::lookup_struct_fields(self.tcx, ctor_id);
905 for field in all_fields {
906 self.check_field(expr.span, ctor_id,
907 NamedField(field.name));
910 ty::ty_enum(_, _) => {
911 match self.tcx.def_map.borrow()[expr.id].clone() {
912 def::DefVariant(_, variant_id, _) => {
913 for field in fields {
914 self.check_field(expr.span, variant_id,
915 NamedField(field.ident.node.name));
918 _ => self.tcx.sess.span_bug(expr.span,
925 _ => self.tcx.sess.span_bug(expr.span, "struct expr \
930 ast::ExprPath(_) | ast::ExprQPath(_) => {
931 let guard = |did: ast::DefId| {
932 let fields = ty::lookup_struct_fields(self.tcx, did);
933 let any_priv = fields.iter().any(|f| {
934 f.vis != ast::Public && (
936 !self.private_accessible(f.id.node))
939 self.tcx.sess.span_err(expr.span,
940 "cannot invoke tuple struct constructor \
941 with private fields");
944 match self.tcx.def_map.borrow().get(&expr.id) {
945 Some(&def::DefStruct(did)) => {
946 guard(if is_local(did) {
947 local_def(self.tcx.map.get_parent(did.node))
949 // "tuple structs" with zero fields (such as
950 // `pub struct Foo;`) don't have a ctor_id, hence
951 // the unwrap_or to the same struct id.
953 csearch::get_tuple_struct_definition_if_ctor(
954 &self.tcx.sess.cstore, did);
955 maybe_did.unwrap_or(did)
964 visit::walk_expr(self, expr);
967 fn visit_pat(&mut self, pattern: &ast::Pat) {
968 // Foreign functions do not have their patterns mapped in the def_map,
969 // and there's nothing really relevant there anyway, so don't bother
970 // checking privacy. If you can name the type then you can pass it to an
971 // external C function anyway.
972 if self.in_foreign { return }
975 ast::PatStruct(_, ref fields, _) => {
976 match ty::pat_ty(self.tcx, pattern).sty {
977 ty::ty_struct(id, _) => {
978 for field in fields {
979 self.check_field(pattern.span, id,
980 NamedField(field.node.ident.name));
983 ty::ty_enum(_, _) => {
984 match self.tcx.def_map.borrow().get(&pattern.id) {
985 Some(&def::DefVariant(_, variant_id, _)) => {
986 for field in fields {
987 self.check_field(pattern.span, variant_id,
988 NamedField(field.node.ident.name));
991 _ => self.tcx.sess.span_bug(pattern.span,
998 _ => self.tcx.sess.span_bug(pattern.span,
999 "struct pattern didn't have \
1004 // Patterns which bind no fields are allowable (the path is check
1006 ast::PatEnum(_, Some(ref fields)) => {
1007 match ty::pat_ty(self.tcx, pattern).sty {
1008 ty::ty_struct(id, _) => {
1009 for (i, field) in fields.iter().enumerate() {
1010 if let ast::PatWild(..) = field.node {
1013 self.check_field(field.span, id, UnnamedField(i));
1016 ty::ty_enum(..) => {
1017 // enum fields have no privacy at this time
1026 visit::walk_pat(self, pattern);
1029 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
1030 self.in_foreign = true;
1031 visit::walk_foreign_item(self, fi);
1032 self.in_foreign = false;
1035 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
1036 self.check_path(path.span, id, path);
1037 visit::walk_path(self, path);
1041 ////////////////////////////////////////////////////////////////////////////////
1042 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1043 ////////////////////////////////////////////////////////////////////////////////
1045 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1046 tcx: &'a ty::ctxt<'tcx>,
1050 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1051 fn visit_item(&mut self, item: &ast::Item) {
1053 self.check_all_inherited(item);
1055 self.check_sane_privacy(item);
1058 let in_fn = self.in_fn;
1059 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1060 ast::ItemMod(..) => false, // modules turn privacy back on
1061 _ => in_fn, // otherwise we inherit
1063 visit::walk_item(self, item);
1064 self.in_fn = orig_in_fn;
1067 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1068 b: &'v ast::Block, s: Span, _: ast::NodeId) {
1069 // This catches both functions and methods
1070 let orig_in_fn = replace(&mut self.in_fn, true);
1071 visit::walk_fn(self, fk, fd, b, s);
1072 self.in_fn = orig_in_fn;
1076 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1077 /// Validates all of the visibility qualifiers placed on the item given. This
1078 /// ensures that there are no extraneous qualifiers that don't actually do
1079 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1080 /// later on down the road...
1081 fn check_sane_privacy(&self, item: &ast::Item) {
1083 let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
1084 if vis != ast::Inherited {
1085 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1087 tcx.sess.span_note(sp, note);
1092 // implementations of traits don't need visibility qualifiers because
1093 // that's controlled by having the trait in scope.
1094 ast::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1095 check_inherited(item.span, item.vis,
1096 "visibility qualifiers have no effect on trait \
1098 for impl_item in impl_items {
1100 ast::MethodImplItem(ref m) => {
1101 check_inherited(m.span, m.pe_vis(), "");
1103 ast::TypeImplItem(_) => {}
1108 ast::ItemImpl(..) => {
1109 check_inherited(item.span, item.vis,
1110 "place qualifiers on individual methods instead");
1112 ast::ItemForeignMod(..) => {
1113 check_inherited(item.span, item.vis,
1114 "place qualifiers on individual functions \
1118 ast::ItemEnum(ref def, _) => {
1119 for v in &def.variants {
1122 if item.vis == ast::Public {
1123 tcx.sess.span_err(v.span, "unnecessary `pub` \
1127 ast::Inherited => {}
1132 ast::ItemTrait(_, _, _, ref methods) => {
1135 ast::ProvidedMethod(ref m) => {
1136 check_inherited(m.span, m.pe_vis(),
1137 "unnecessary visibility");
1139 ast::RequiredMethod(ref m) => {
1140 check_inherited(m.span, m.vis,
1141 "unnecessary visibility");
1143 ast::TypeTraitItem(_) => {}
1148 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemStruct(..) |
1149 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1150 ast::ItemExternCrate(_) | ast::ItemUse(_) | ast::ItemMac(..) => {}
1154 /// When inside of something like a function or a method, visibility has no
1155 /// control over anything so this forbids any mention of any visibility
1156 fn check_all_inherited(&self, item: &ast::Item) {
1158 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
1159 if vis != ast::Inherited {
1160 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1163 let check_struct = |def: &ast::StructDef| {
1164 for f in &def.fields {
1166 ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
1167 ast::UnnamedField(..) => {}
1171 check_inherited(tcx, item.span, item.vis);
1173 ast::ItemImpl(_, _, _, _, _, ref impl_items) => {
1174 for impl_item in impl_items {
1176 ast::MethodImplItem(ref m) => {
1177 check_inherited(tcx, m.span, m.pe_vis());
1179 ast::TypeImplItem(_) => {}
1183 ast::ItemForeignMod(ref fm) => {
1184 for i in &fm.items {
1185 check_inherited(tcx, i.span, i.vis);
1188 ast::ItemEnum(ref def, _) => {
1189 for v in &def.variants {
1190 check_inherited(tcx, v.span, v.node.vis);
1194 ast::ItemStruct(ref def, _) => check_struct(&**def),
1196 ast::ItemTrait(_, _, _, ref methods) => {
1199 ast::RequiredMethod(..) => {}
1200 ast::ProvidedMethod(ref m) => check_inherited(tcx, m.span,
1202 ast::TypeTraitItem(_) => {}
1207 ast::ItemExternCrate(_) | ast::ItemUse(_) |
1208 ast::ItemStatic(..) | ast::ItemConst(..) |
1209 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1210 ast::ItemMac(..) => {}
1215 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1216 tcx: &'a ty::ctxt<'tcx>,
1217 exported_items: &'a ExportedItems,
1218 public_items: &'a PublicItems,
1222 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1223 inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1224 /// whether the type refers to private types.
1225 contains_private: bool,
1226 /// whether we've recurred at all (i.e. if we're pointing at the
1227 /// first type on which visit_ty was called).
1228 at_outer_type: bool,
1229 // whether that first type is a public path.
1230 outer_type_is_public_path: bool,
1233 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1234 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1235 let did = match self.tcx.def_map.borrow().get(&path_id).cloned() {
1236 // `int` etc. (None doesn't seem to occur.)
1237 None | Some(def::DefPrimTy(..)) => return false,
1238 Some(def) => def.def_id()
1240 // A path can only be private if:
1241 // it's in this crate...
1245 // .. and it corresponds to a private type in the AST (this returns
1246 // None for type parameters)
1247 match self.tcx.map.find(did.node) {
1248 Some(ast_map::NodeItem(ref item)) => item.vis != ast::Public,
1249 Some(_) | None => false,
1253 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1254 // FIXME: this would preferably be using `exported_items`, but all
1255 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1256 self.public_items.contains(&trait_id)
1259 fn check_ty_param_bound(&self,
1260 ty_param_bound: &ast::TyParamBound) {
1261 if let ast::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1262 if !self.tcx.sess.features.borrow().visible_private_types &&
1263 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1264 let span = trait_ref.trait_ref.path.span;
1265 self.tcx.sess.span_err(span,
1266 "private trait in exported type \
1273 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1274 fn visit_ty(&mut self, ty: &ast::Ty) {
1275 if let ast::TyPath(_, path_id) = ty.node {
1276 if self.inner.path_is_private_type(path_id) {
1277 self.contains_private = true;
1278 // found what we're looking for so let's stop
1281 } else if self.at_outer_type {
1282 self.outer_type_is_public_path = true;
1285 self.at_outer_type = false;
1286 visit::walk_ty(self, ty)
1289 // don't want to recurse into [, .. expr]
1290 fn visit_expr(&mut self, _: &ast::Expr) {}
1293 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1294 fn visit_item(&mut self, item: &ast::Item) {
1296 // contents of a private mod can be reexported, so we need
1297 // to check internals.
1298 ast::ItemMod(_) => {}
1300 // An `extern {}` doesn't introduce a new privacy
1301 // namespace (the contents have their own privacies).
1302 ast::ItemForeignMod(_) => {}
1304 ast::ItemTrait(_, _, ref bounds, _) => {
1305 if !self.trait_is_public(item.id) {
1309 for bound in &**bounds {
1310 self.check_ty_param_bound(bound)
1314 // impls need some special handling to try to offer useful
1315 // error messages without (too many) false positives
1316 // (i.e. we could just return here to not check them at
1317 // all, or some worse estimation of whether an impl is
1318 // publicly visible.
1319 ast::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1320 // `impl [... for] Private` is never visible.
1321 let self_contains_private;
1322 // impl [... for] Public<...>, but not `impl [... for]
1323 // ~[Public]` or `(Public,)` etc.
1324 let self_is_public_path;
1326 // check the properties of the Self type:
1328 let mut visitor = CheckTypeForPrivatenessVisitor {
1330 contains_private: false,
1331 at_outer_type: true,
1332 outer_type_is_public_path: false,
1334 visitor.visit_ty(&**self_);
1335 self_contains_private = visitor.contains_private;
1336 self_is_public_path = visitor.outer_type_is_public_path;
1339 // miscellaneous info about the impl
1341 // `true` iff this is `impl Private for ...`.
1342 let not_private_trait =
1343 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1345 let did = ty::trait_ref_to_def_id(self.tcx, tr);
1347 !is_local(did) || self.trait_is_public(did.node)
1350 // `true` iff this is a trait impl or at least one method is public.
1352 // `impl Public { $( fn ...() {} )* }` is not visible.
1354 // This is required over just using the methods' privacy
1355 // directly because we might have `impl<T: Foo<Private>> ...`,
1356 // and we shouldn't warn about the generics if all the methods
1357 // are private (because `T` won't be visible externally).
1358 let trait_or_some_public_method =
1359 trait_ref.is_some() ||
1363 ast::MethodImplItem(ref m) => {
1364 self.exported_items.contains(&m.id)
1366 ast::TypeImplItem(_) => false,
1370 if !self_contains_private &&
1371 not_private_trait &&
1372 trait_or_some_public_method {
1374 visit::walk_generics(self, g);
1378 for impl_item in impl_items {
1380 ast::MethodImplItem(ref method) => {
1381 visit::walk_method_helper(self, &**method)
1383 ast::TypeImplItem(_) => {}
1388 // Any private types in a trait impl fall into two
1390 // 1. mentioned in the trait definition
1391 // 2. mentioned in the type params/generics
1393 // Those in 1. can only occur if the trait is in
1394 // this crate and will've been warned about on the
1395 // trait definition (there's no need to warn twice
1396 // so we don't check the methods).
1398 // Those in 2. are warned via walk_generics and this
1400 self.visit_trait_ref(tr)
1403 } else if trait_ref.is_none() && self_is_public_path {
1404 // impl Public<Private> { ... }. Any public static
1405 // methods will be visible as `Public::foo`.
1406 let mut found_pub_static = false;
1407 for impl_item in impl_items {
1409 ast::MethodImplItem(ref method) => {
1410 if method.pe_explicit_self().node ==
1413 .contains(&method.id) {
1414 found_pub_static = true;
1415 visit::walk_method_helper(self, &**method);
1418 ast::TypeImplItem(_) => {}
1421 if found_pub_static {
1422 visit::walk_generics(self, g)
1428 // `type ... = ...;` can contain private types, because
1429 // we're introducing a new name.
1430 ast::ItemTy(..) => return,
1432 // not at all public, so we don't care
1433 _ if !self.exported_items.contains(&item.id) => return,
1438 // we've carefully constructed it so that if we're here, then
1439 // any `visit_ty`'s will be called on things that are in
1440 // public signatures, i.e. things that we're interested in for
1442 visit::walk_item(self, item);
1445 fn visit_generics(&mut self, generics: &ast::Generics) {
1446 for ty_param in &*generics.ty_params {
1447 for bound in &*ty_param.bounds {
1448 self.check_ty_param_bound(bound)
1451 for predicate in &generics.where_clause.predicates {
1453 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
1454 for bound in &*bound_pred.bounds {
1455 self.check_ty_param_bound(bound)
1458 &ast::WherePredicate::RegionPredicate(_) => {}
1459 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
1460 self.visit_ty(&*eq_pred.ty);
1466 fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
1467 if self.exported_items.contains(&item.id) {
1468 visit::walk_foreign_item(self, item)
1472 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1473 b: &'v ast::Block, s: Span, id: ast::NodeId) {
1474 // needs special handling for methods.
1475 if self.exported_items.contains(&id) {
1476 visit::walk_fn(self, fk, fd, b, s);
1480 fn visit_ty(&mut self, t: &ast::Ty) {
1481 if let ast::TyPath(ref p, path_id) = t.node {
1482 if !self.tcx.sess.features.borrow().visible_private_types &&
1483 self.path_is_private_type(path_id) {
1484 self.tcx.sess.span_err(p.span,
1485 "private type in exported type signature");
1488 visit::walk_ty(self, t)
1491 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
1492 if self.exported_items.contains(&v.node.id) {
1493 self.in_variant = true;
1494 visit::walk_variant(self, v, g);
1495 self.in_variant = false;
1499 fn visit_struct_field(&mut self, s: &ast::StructField) {
1501 ast::NamedField(_, vis) if vis == ast::Public || self.in_variant => {
1502 visit::walk_struct_field(self, s);
1509 // we don't need to introspect into these at all: an
1510 // expression/block context can't possibly contain exported things.
1511 // (Making them no-ops stops us from traversing the whole AST without
1512 // having to be super careful about our `walk_...` calls above.)
1513 fn visit_block(&mut self, _: &ast::Block) {}
1514 fn visit_expr(&mut self, _: &ast::Expr) {}
1517 pub fn check_crate(tcx: &ty::ctxt,
1518 export_map: &def::ExportMap,
1519 external_exports: ExternalExports,
1520 last_private_map: LastPrivateMap)
1521 -> (ExportedItems, PublicItems) {
1522 let krate = tcx.map.krate();
1524 // Figure out who everyone's parent is
1525 let mut visitor = ParentVisitor {
1527 curparent: ast::DUMMY_NODE_ID,
1529 visit::walk_crate(&mut visitor, krate);
1531 // Use the parent map to check the privacy of everything
1532 let mut visitor = PrivacyVisitor {
1533 curitem: ast::DUMMY_NODE_ID,
1536 parents: visitor.parents,
1537 external_exports: external_exports,
1538 last_private_map: last_private_map,
1540 visit::walk_crate(&mut visitor, krate);
1542 // Sanity check to make sure that all privacy usage and controls are
1544 let mut visitor = SanePrivacyVisitor {
1548 visit::walk_crate(&mut visitor, krate);
1550 tcx.sess.abort_if_errors();
1552 // Build up a set of all exported items in the AST. This is a set of all
1553 // items which are reachable from external crates based on visibility.
1554 let mut visitor = EmbargoVisitor {
1556 exported_items: NodeSet(),
1557 public_items: NodeSet(),
1558 reexports: NodeSet(),
1559 export_map: export_map,
1560 prev_exported: true,
1564 let before = visitor.exported_items.len();
1565 visit::walk_crate(&mut visitor, krate);
1566 if before == visitor.exported_items.len() {
1571 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1574 let mut visitor = VisiblePrivateTypesVisitor {
1576 exported_items: &exported_items,
1577 public_items: &public_items,
1580 visit::walk_crate(&mut visitor, krate);
1582 return (exported_items, public_items);