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 //! A pass that checks to make sure private fields and methods aren't used
12 //! outside their scopes. This pass will also generate a set of exported items
13 //! which are available for use externally when compiled as a library.
15 use std::mem::replace;
17 use metadata::csearch;
21 use middle::typeck::{MethodCall, MethodMap, MethodOrigin, MethodParam, MethodTypeParam};
22 use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure, MethodObject, MethodTraitObject};
23 use util::nodemap::{NodeMap, NodeSet};
27 use syntax::ast_util::{is_local, local_def, PostExpansionMethod};
28 use syntax::codemap::Span;
29 use syntax::parse::token;
30 use syntax::owned_slice::OwnedSlice;
32 use syntax::visit::Visitor;
34 type Context<'a> = (&'a MethodMap, &'a resolve::ExportMap2);
36 /// A set of AST nodes exported by the crate.
37 pub type ExportedItems = NodeSet;
39 /// A set of AST nodes that are fully public in the crate. This map is used for
40 /// documentation purposes (reexporting a private struct inlines the doc,
41 /// reexporting a public struct doesn't inline the doc).
42 pub type PublicItems = NodeSet;
44 /// Result of a checking operation - None => no errors were found. Some => an
45 /// error and contains the span and message for reporting that error and
46 /// optionally the same for a note about the error.
47 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
49 ////////////////////////////////////////////////////////////////////////////////
50 /// The parent visitor, used to determine what's the parent of what (node-wise)
51 ////////////////////////////////////////////////////////////////////////////////
53 struct ParentVisitor {
54 parents: NodeMap<ast::NodeId>,
55 curparent: ast::NodeId,
58 impl<'v> Visitor<'v> for ParentVisitor {
59 fn visit_item(&mut self, item: &ast::Item) {
60 self.parents.insert(item.id, self.curparent);
62 let prev = self.curparent;
64 ast::ItemMod(..) => { self.curparent = item.id; }
65 // Enum variants are parented to the enum definition itself because
66 // they inherit privacy
67 ast::ItemEnum(ref def, _) => {
68 for variant in def.variants.iter() {
69 // The parent is considered the enclosing enum because the
70 // enum will dictate the privacy visibility of this variant
72 self.parents.insert(variant.node.id, item.id);
76 // Trait methods are always considered "public", but if the trait is
77 // private then we need some private item in the chain from the
78 // method to the root. In this case, if the trait is private, then
79 // parent all the methods to the trait to indicate that they're
81 ast::ItemTrait(_, _, _, ref methods) if item.vis != ast::Public => {
82 for m in methods.iter() {
84 ast::ProvidedMethod(ref m) => {
85 self.parents.insert(m.id, item.id);
87 ast::RequiredMethod(ref m) => {
88 self.parents.insert(m.id, item.id);
90 ast::TypeTraitItem(_) => {}
97 visit::walk_item(self, item);
98 self.curparent = prev;
101 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
102 self.parents.insert(a.id, self.curparent);
103 visit::walk_foreign_item(self, a);
106 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
107 c: &'v ast::Block, d: Span, id: ast::NodeId) {
108 // We already took care of some trait methods above, otherwise things
109 // like impl methods and pub trait methods are parented to the
110 // containing module, not the containing trait.
111 if !self.parents.contains_key(&id) {
112 self.parents.insert(id, self.curparent);
114 visit::walk_fn(self, a, b, c, d);
117 fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
118 _: &'v ast::Generics, n: ast::NodeId) {
119 // Struct constructors are parented to their struct definitions because
120 // they essentially are the struct definitions.
122 Some(id) => { self.parents.insert(id, n); }
126 // While we have the id of the struct definition, go ahead and parent
128 for field in s.fields.iter() {
129 self.parents.insert(field.node.id, self.curparent);
131 visit::walk_struct_def(self, s)
135 ////////////////////////////////////////////////////////////////////////////////
136 /// The embargo visitor, used to determine the exports of the ast
137 ////////////////////////////////////////////////////////////////////////////////
139 struct EmbargoVisitor<'a, 'tcx: 'a> {
140 tcx: &'a ty::ctxt<'tcx>,
141 exp_map2: &'a resolve::ExportMap2,
143 // This flag is an indicator of whether the previous item in the
144 // hierarchical chain was exported or not. This is the indicator of whether
145 // children should be exported as well. Note that this can flip from false
146 // to true if a reexported module is entered (or an action similar).
149 // This is a list of all exported items in the AST. An exported item is any
150 // function/method/item which is usable by external crates. This essentially
151 // means that the result is "public all the way down", but the "path down"
152 // may jump across private boundaries through reexport statements.
153 exported_items: ExportedItems,
155 // This sets contains all the destination nodes which are publicly
156 // re-exported. This is *not* a set of all reexported nodes, only a set of
157 // all nodes which are reexported *and* reachable from external crates. This
158 // means that the destination of the reexport is exported, and hence the
159 // destination must also be exported.
162 // These two fields are closely related to one another in that they are only
163 // used for generation of the 'PublicItems' set, not for privacy checking at
165 public_items: PublicItems,
169 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
170 // There are checks inside of privacy which depend on knowing whether a
171 // trait should be exported or not. The two current consumers of this are:
173 // 1. Should default methods of a trait be exported?
174 // 2. Should the methods of an implementation of a trait be exported?
176 // The answer to both of these questions partly rely on whether the trait
177 // itself is exported or not. If the trait is somehow exported, then the
178 // answers to both questions must be yes. Right now this question involves
179 // more analysis than is currently done in rustc, so we conservatively
180 // answer "yes" so that all traits need to be exported.
181 fn exported_trait(&self, _id: ast::NodeId) -> bool {
186 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
187 fn visit_item(&mut self, item: &ast::Item) {
188 let orig_all_pub = self.prev_public;
189 self.prev_public = orig_all_pub && item.vis == ast::Public;
190 if self.prev_public {
191 self.public_items.insert(item.id);
194 let orig_all_exported = self.prev_exported;
196 // impls/extern blocks do not break the "public chain" because they
197 // cannot have visibility qualifiers on them anyway
198 ast::ItemImpl(..) | ast::ItemForeignMod(..) => {}
200 // Traits are a little special in that even if they themselves are
201 // not public they may still be exported.
202 ast::ItemTrait(..) => {
203 self.prev_exported = self.exported_trait(item.id);
206 // Private by default, hence we only retain the "public chain" if
207 // `pub` is explicitly listed.
210 (orig_all_exported && item.vis == ast::Public) ||
211 self.reexports.contains(&item.id);
215 let public_first = self.prev_exported &&
216 self.exported_items.insert(item.id);
219 // Enum variants inherit from their parent, so if the enum is
220 // public all variants are public unless they're explicitly priv
221 ast::ItemEnum(ref def, _) if public_first => {
222 for variant in def.variants.iter() {
223 self.exported_items.insert(variant.node.id);
227 // Implementations are a little tricky to determine what's exported
228 // out of them. Here's a few cases which are currently defined:
230 // * Impls for private types do not need to export their methods
231 // (either public or private methods)
233 // * Impls for public types only have public methods exported
235 // * Public trait impls for public types must have all methods
238 // * Private trait impls for public types can be ignored
240 // * Public trait impls for private types have their methods
241 // exported. I'm not entirely certain that this is the correct
242 // thing to do, but I have seen use cases of where this will cause
243 // undefined symbols at linkage time if this case is not handled.
245 // * Private trait impls for private types can be completely ignored
246 ast::ItemImpl(_, _, ref ty, ref impl_items) => {
247 let public_ty = match ty.node {
248 ast::TyPath(_, _, id) => {
249 match self.tcx.def_map.borrow().get_copy(&id) {
250 def::DefPrimTy(..) => true,
252 let did = def.def_id();
254 self.exported_items.contains(&did.node)
260 let tr = ty::impl_trait_ref(self.tcx, local_def(item.id));
261 let public_trait = tr.clone().map_or(false, |tr| {
262 !is_local(tr.def_id) ||
263 self.exported_items.contains(&tr.def_id.node)
266 if public_ty || public_trait {
267 for impl_item in impl_items.iter() {
269 ast::MethodImplItem(ref method) => {
271 match method.pe_explicit_self().node {
272 ast::SelfStatic => public_ty,
274 } && method.pe_vis() == ast::Public;
275 if meth_public || tr.is_some() {
276 self.exported_items.insert(method.id);
279 ast::TypeImplItem(_) => {}
285 // Default methods on traits are all public so long as the trait
287 ast::ItemTrait(_, _, _, ref methods) if public_first => {
288 for method in methods.iter() {
290 ast::ProvidedMethod(ref m) => {
291 debug!("provided {}", m.id);
292 self.exported_items.insert(m.id);
294 ast::RequiredMethod(ref m) => {
295 debug!("required {}", m.id);
296 self.exported_items.insert(m.id);
298 ast::TypeTraitItem(ref t) => {
299 debug!("typedef {}", t.id);
300 self.exported_items.insert(t.id);
306 // Struct constructors are public if the struct is all public.
307 ast::ItemStruct(ref def, _) if public_first => {
309 Some(id) => { self.exported_items.insert(id); }
314 ast::ItemTy(ref ty, _) if public_first => {
316 ast::TyPath(_, _, id) => {
317 match self.tcx.def_map.borrow().get_copy(&id) {
318 def::DefPrimTy(..) | def::DefTyParam(..) => {},
320 let did = def.def_id();
322 self.exported_items.insert(did.node);
334 visit::walk_item(self, item);
336 self.prev_exported = orig_all_exported;
337 self.prev_public = orig_all_pub;
340 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
341 if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) {
342 self.exported_items.insert(a.id);
346 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) {
347 // This code is here instead of in visit_item so that the
348 // crate module gets processed as well.
349 if self.prev_exported {
350 assert!(self.exp_map2.contains_key(&id), "wut {:?}", id);
351 for export in self.exp_map2.get(&id).iter() {
352 if is_local(export.def_id) {
353 self.reexports.insert(export.def_id.node);
357 visit::walk_mod(self, m)
361 ////////////////////////////////////////////////////////////////////////////////
362 /// The privacy visitor, where privacy checks take place (violations reported)
363 ////////////////////////////////////////////////////////////////////////////////
365 struct PrivacyVisitor<'a, 'tcx: 'a> {
366 tcx: &'a ty::ctxt<'tcx>,
367 curitem: ast::NodeId,
369 parents: NodeMap<ast::NodeId>,
370 external_exports: resolve::ExternalExports,
371 last_private_map: resolve::LastPrivateMap,
377 DisallowedBy(ast::NodeId),
381 UnnamedField(uint), // index
382 // FIXME #6993: change type (and name) from Ident to Name
383 NamedField(ast::Ident),
386 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
387 // used when debugging
388 fn nodestr(&self, id: ast::NodeId) -> String {
389 self.tcx.map.node_to_string(id).to_string()
392 // Determines whether the given definition is public from the point of view
393 // of the current item.
394 fn def_privacy(&self, did: ast::DefId) -> PrivacyResult {
396 if self.external_exports.contains(&did) {
397 debug!("privacy - {:?} was externally exported", did);
400 debug!("privacy - is {:?} a public method", did);
402 return match self.tcx.impl_or_trait_items.borrow().find(&did) {
403 Some(&ty::MethodTraitItem(ref meth)) => {
404 debug!("privacy - well at least it's a method: {:?}",
406 match meth.container {
407 ty::TraitContainer(id) => {
408 debug!("privacy - recursing on trait {:?}", id);
411 ty::ImplContainer(id) => {
412 match ty::impl_trait_ref(self.tcx, id) {
414 debug!("privacy - impl of trait {:?}", id);
415 self.def_privacy(t.def_id)
418 debug!("privacy - found a method {:?}",
420 if meth.vis == ast::Public {
430 Some(&ty::TypeTraitItem(ref typedef)) => {
431 match typedef.container {
432 ty::TraitContainer(id) => {
433 debug!("privacy - recursing on trait {:?}", id);
436 ty::ImplContainer(id) => {
437 match ty::impl_trait_ref(self.tcx, id) {
439 debug!("privacy - impl of trait {:?}", id);
440 self.def_privacy(t.def_id)
443 debug!("privacy - found a typedef {:?}",
445 if typedef.vis == ast::Public {
456 debug!("privacy - nope, not even a method");
462 debug!("privacy - local {} not public all the way down",
463 self.tcx.map.node_to_string(did.node));
464 // return quickly for things in the same module
465 if self.parents.find(&did.node) == self.parents.find(&self.curitem) {
466 debug!("privacy - same parent, we're done here");
470 // We now know that there is at least one private member between the
471 // destination and the root.
472 let mut closest_private_id = did.node;
474 debug!("privacy - examining {}", self.nodestr(closest_private_id));
475 let vis = match self.tcx.map.find(closest_private_id) {
476 // If this item is a method, then we know for sure that it's an
477 // actual method and not a static method. The reason for this is
478 // that these cases are only hit in the ExprMethodCall
479 // expression, and ExprCall will have its path checked later
480 // (the path of the trait/impl) if it's a static method.
482 // With this information, then we can completely ignore all
483 // trait methods. The privacy violation would be if the trait
484 // couldn't get imported, not if the method couldn't be used
485 // (all trait methods are public).
487 // However, if this is an impl method, then we dictate this
488 // decision solely based on the privacy of the method
490 // FIXME(#10573) is this the right behavior? Why not consider
491 // where the method was defined?
492 Some(ast_map::NodeImplItem(ii)) => {
494 ast::MethodImplItem(ref m) => {
495 let imp = self.tcx.map
496 .get_parent_did(closest_private_id);
497 match ty::impl_trait_ref(self.tcx, imp) {
498 Some(..) => return Allowable,
499 _ if m.pe_vis() == ast::Public => {
505 ast::TypeImplItem(_) => return Allowable,
508 Some(ast_map::NodeTraitItem(_)) => {
512 // This is not a method call, extract the visibility as one
513 // would normally look at it
514 Some(ast_map::NodeItem(it)) => it.vis,
515 Some(ast_map::NodeForeignItem(_)) => {
516 self.tcx.map.get_foreign_vis(closest_private_id)
518 Some(ast_map::NodeVariant(..)) => {
519 ast::Public // need to move up a level (to the enum)
523 if vis != ast::Public { break }
524 // if we've reached the root, then everything was allowable and this
526 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
527 closest_private_id = *self.parents.get(&closest_private_id);
529 // If we reached the top, then we were public all the way down and
530 // we can allow this access.
531 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
533 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
534 if self.private_accessible(closest_private_id) {
537 DisallowedBy(closest_private_id)
541 /// For a local private node in the AST, this function will determine
542 /// whether the node is accessible by the current module that iteration is
544 fn private_accessible(&self, id: ast::NodeId) -> bool {
545 let parent = *self.parents.get(&id);
546 debug!("privacy - accessible parent {}", self.nodestr(parent));
548 // After finding `did`'s closest private member, we roll ourselves back
549 // to see if this private member's parent is anywhere in our ancestry.
550 // By the privacy rules, we can access all of our ancestor's private
551 // members, so that's why we test the parent, and not the did itself.
552 let mut cur = self.curitem;
554 debug!("privacy - questioning {}, {:?}", self.nodestr(cur), cur);
556 // If the relevant parent is in our history, then we're allowed
557 // to look inside any of our ancestor's immediate private items,
558 // so this access is valid.
559 x if x == parent => return true,
561 // If we've reached the root, then we couldn't access this item
562 // in the first place
563 ast::DUMMY_NODE_ID => return false,
569 cur = *self.parents.get(&cur);
573 fn report_error(&self, result: CheckResult) -> bool {
576 Some((span, msg, note)) => {
577 self.tcx.sess.span_err(span, msg.as_slice());
579 Some((span, msg)) => {
580 self.tcx.sess.span_note(span, msg.as_slice())
589 /// Guarantee that a particular definition is public. Returns a CheckResult
590 /// which contains any errors found. These can be reported using `report_error`.
591 /// If the result is `None`, no errors were found.
592 fn ensure_public(&self, span: Span, to_check: ast::DefId,
593 source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
594 let id = match self.def_privacy(to_check) {
595 ExternallyDenied => {
596 return Some((span, format!("{} is private", msg), None))
598 Allowable => return None,
599 DisallowedBy(id) => id,
602 // If we're disallowed by a particular id, then we attempt to give a
603 // nice error message to say why it was disallowed. It was either
604 // because the item itself is private or because its parent is private
605 // and its parent isn't in our ancestry.
606 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
607 return Some((span, format!("{} is private", msg), None));
609 (span, format!("{} is inaccessible", msg))
611 let item = match self.tcx.map.find(id) {
612 Some(ast_map::NodeItem(item)) => {
614 // If an impl disallowed this item, then this is resolve's
615 // way of saying that a struct/enum's static method was
616 // invoked, and the struct/enum itself is private. Crawl
617 // back up the chains to find the relevant struct/enum that
619 ast::ItemImpl(_, _, ref ty, _) => {
620 let id = match ty.node {
621 ast::TyPath(_, _, id) => id,
622 _ => return Some((err_span, err_msg, None)),
624 let def = self.tcx.def_map.borrow().get_copy(&id);
625 let did = def.def_id();
626 assert!(is_local(did));
627 match self.tcx.map.get(did.node) {
628 ast_map::NodeItem(item) => item,
629 _ => self.tcx.sess.span_bug(item.span,
630 "path is not an item")
636 Some(..) | None => return Some((err_span, err_msg, None)),
638 let desc = match item.node {
639 ast::ItemMod(..) => "module",
640 ast::ItemTrait(..) => "trait",
641 ast::ItemStruct(..) => "struct",
642 ast::ItemEnum(..) => "enum",
643 _ => return Some((err_span, err_msg, None))
645 let msg = format!("{} `{}` is private", desc,
646 token::get_ident(item.ident));
647 Some((err_span, err_msg, Some((span, msg))))
650 // Checks that a field is in scope.
651 fn check_field(&mut self,
655 let fields = ty::lookup_struct_fields(self.tcx, id);
656 let field = match name {
657 NamedField(ident) => {
658 debug!("privacy - check named field {} in struct {}", ident.name, id);
659 fields.iter().find(|f| f.name == ident.name).unwrap()
661 UnnamedField(idx) => fields.get(idx)
663 if field.vis == ast::Public ||
664 (is_local(field.id) && self.private_accessible(field.id.node)) {
668 let struct_type = ty::lookup_item_type(self.tcx, id).ty;
669 let struct_desc = match ty::get(struct_type).sty {
670 ty::ty_struct(_, _) => format!("struct `{}`", ty::item_path_str(self.tcx, id)),
671 ty::ty_bare_fn(ty::BareFnTy { sig: ty::FnSig { output, .. }, .. }) => {
672 // Struct `id` is really a struct variant of an enum,
673 // and we're really looking at the variant's constructor
674 // function. So get the return type for a detailed error
676 let enum_id = match ty::get(output).sty {
677 ty::ty_enum(id, _) => id,
678 _ => self.tcx.sess.span_bug(span, "enum variant doesn't \
681 format!("variant `{}` of enum `{}`",
682 ty::with_path(self.tcx, id, |mut p| p.last().unwrap()),
683 ty::item_path_str(self.tcx, enum_id))
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_ident(name), struct_desc),
690 UnnamedField(idx) => format!("field #{} of {} is private",
691 idx + 1, struct_desc),
693 self.tcx.sess.span_err(span, msg.as_slice());
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 `{}`",
715 string).as_slice()));
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().get_copy(&path_id);
722 let ck = |tyname: &str| {
723 let ck_public = |def: ast::DefId| {
724 let name = token::get_ident(path.segments
728 let origdid = orig_def.def_id();
729 self.ensure_public(span,
737 match *self.last_private_map.get(&path_id) {
738 resolve::LastMod(resolve::AllPublic) => {},
739 resolve::LastMod(resolve::DependsOn(def)) => {
740 self.report_error(ck_public(def));
742 resolve::LastImport{value_priv: value_priv,
743 value_used: check_value,
744 type_priv: type_priv,
745 type_used: check_type} => {
746 // This dance with found_error is because we don't want to report
747 // a privacy error twice for the same directive.
748 let found_error = match (type_priv, check_type) {
749 (Some(resolve::DependsOn(def)), resolve::Used) => {
750 !self.report_error(ck_public(def))
755 match (value_priv, check_value) {
756 (Some(resolve::DependsOn(def)), resolve::Used) => {
757 self.report_error(ck_public(def));
762 // If an import is not used in either namespace, we still
763 // want to check that it could be legal. Therefore we check
764 // in both namespaces and only report an error if both would
765 // be illegal. We only report one error, even if it is
766 // illegal to import from both namespaces.
767 match (value_priv, check_value, type_priv, check_type) {
768 (Some(p), resolve::Unused, None, _) |
769 (None, _, Some(p), resolve::Unused) => {
771 resolve::AllPublic => None,
772 resolve::DependsOn(def) => ck_public(def),
775 self.report_error(p);
778 (Some(v), resolve::Unused, Some(t), resolve::Unused) => {
780 resolve::AllPublic => None,
781 resolve::DependsOn(def) => ck_public(def),
784 resolve::AllPublic => None,
785 resolve::DependsOn(def) => ck_public(def),
788 (Some(_), Some(t)) => {
789 self.report_error(Some(t));
799 // FIXME(#12334) Imports can refer to definitions in both the type and
800 // value namespaces. The privacy information is aware of this, but the
801 // def map is not. Therefore the names we work out below will not always
802 // be accurate and we can get slightly wonky error messages (but type
803 // checking is always correct).
804 match self.tcx.def_map.borrow().get_copy(&path_id) {
805 def::DefStaticMethod(..) => ck("static method"),
806 def::DefFn(..) => ck("function"),
807 def::DefStatic(..) => ck("static"),
808 def::DefVariant(..) => ck("variant"),
809 def::DefTy(_, false) => ck("type"),
810 def::DefTy(_, true) => ck("enum"),
811 def::DefTrait(..) => ck("trait"),
812 def::DefStruct(..) => ck("struct"),
813 def::DefMethod(_, Some(..)) => ck("trait method"),
814 def::DefMethod(..) => ck("method"),
815 def::DefMod(..) => ck("module"),
820 // Checks that a method is in scope.
821 fn check_method(&mut self, span: Span, origin: &MethodOrigin,
824 MethodStatic(method_id) => {
825 self.check_static_method(span, method_id, ident)
827 MethodStaticUnboxedClosure(_) => {}
828 // Trait methods are always all public. The only controlling factor
829 // is whether the trait itself is accessible or not.
830 MethodTypeParam(MethodParam { trait_ref: ref trait_ref, .. }) |
831 MethodTraitObject(MethodObject { trait_ref: ref trait_ref, .. }) => {
832 self.report_error(self.ensure_public(span, trait_ref.def_id,
833 None, "source trait"));
839 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
840 fn visit_item(&mut self, item: &ast::Item) {
841 let orig_curitem = replace(&mut self.curitem, item.id);
842 visit::walk_item(self, item);
843 self.curitem = orig_curitem;
846 fn visit_expr(&mut self, expr: &ast::Expr) {
848 ast::ExprField(ref base, ident, _) => {
849 match ty::get(ty::expr_ty_adjusted(self.tcx, &**base)).sty {
850 ty::ty_struct(id, _) => {
851 self.check_field(expr.span, id, NamedField(ident.node));
856 ast::ExprTupField(ref base, idx, _) => {
857 match ty::get(ty::expr_ty_adjusted(self.tcx, &**base)).sty {
858 ty::ty_struct(id, _) => {
859 self.check_field(expr.span, id, UnnamedField(idx.node));
864 ast::ExprMethodCall(ident, _, _) => {
865 let method_call = MethodCall::expr(expr.id);
866 match self.tcx.method_map.borrow().find(&method_call) {
868 self.tcx.sess.span_bug(expr.span,
869 "method call not in \
873 debug!("(privacy checking) checking impl method");
874 self.check_method(expr.span, &method.origin, ident.node);
878 ast::ExprStruct(_, ref fields, _) => {
879 match ty::get(ty::expr_ty(self.tcx, expr)).sty {
880 ty::ty_struct(id, _) => {
881 for field in (*fields).iter() {
882 self.check_field(expr.span, id,
883 NamedField(field.ident.node));
886 ty::ty_enum(_, _) => {
887 match self.tcx.def_map.borrow().get_copy(&expr.id) {
888 def::DefVariant(_, variant_id, _) => {
889 for field in fields.iter() {
890 self.check_field(expr.span, variant_id,
891 NamedField(field.ident.node));
894 _ => self.tcx.sess.span_bug(expr.span,
901 _ => self.tcx.sess.span_bug(expr.span, "struct expr \
906 ast::ExprPath(..) => {
907 let guard = |did: ast::DefId| {
908 let fields = ty::lookup_struct_fields(self.tcx, did);
909 let any_priv = fields.iter().any(|f| {
910 f.vis != ast::Public && (
912 !self.private_accessible(f.id.node))
915 self.tcx.sess.span_err(expr.span,
916 "cannot invoke tuple struct constructor \
917 with private fields");
920 match self.tcx.def_map.borrow().find(&expr.id) {
921 Some(&def::DefStruct(did)) => {
922 guard(if is_local(did) {
923 local_def(self.tcx.map.get_parent(did.node))
925 // "tuple structs" with zero fields (such as
926 // `pub struct Foo;`) don't have a ctor_id, hence
927 // the unwrap_or to the same struct id.
929 csearch::get_tuple_struct_definition_if_ctor(
930 &self.tcx.sess.cstore, did);
931 maybe_did.unwrap_or(did)
934 // Tuple struct constructors across crates are identified as
935 // DefFn types, so we explicitly handle that case here.
936 Some(&def::DefFn(did, _)) if !is_local(did) => {
937 match csearch::get_tuple_struct_definition_if_ctor(
938 &self.tcx.sess.cstore, did) {
939 Some(did) => guard(did),
949 visit::walk_expr(self, expr);
952 fn visit_view_item(&mut self, a: &ast::ViewItem) {
954 ast::ViewItemExternCrate(..) => {}
955 ast::ViewItemUse(ref vpath) => {
957 ast::ViewPathSimple(..) | ast::ViewPathGlob(..) => {}
958 ast::ViewPathList(ref prefix, ref list, _) => {
959 for pid in list.iter() {
961 ast::PathListIdent { id, name } => {
962 debug!("privacy - ident item {}", id);
963 let seg = ast::PathSegment {
965 lifetimes: Vec::new(),
966 types: OwnedSlice::empty(),
968 let segs = vec![seg];
969 let path = ast::Path {
974 self.check_path(pid.span, id, &path);
976 ast::PathListMod { id } => {
977 debug!("privacy - mod item {}", id);
978 self.check_path(pid.span, id, prefix);
986 visit::walk_view_item(self, a);
989 fn visit_pat(&mut self, pattern: &ast::Pat) {
990 // Foreign functions do not have their patterns mapped in the def_map,
991 // and there's nothing really relevant there anyway, so don't bother
992 // checking privacy. If you can name the type then you can pass it to an
993 // external C function anyway.
994 if self.in_foreign { return }
997 ast::PatStruct(_, ref fields, _) => {
998 match ty::get(ty::pat_ty(self.tcx, pattern)).sty {
999 ty::ty_struct(id, _) => {
1000 for field in fields.iter() {
1001 self.check_field(pattern.span, id,
1002 NamedField(field.ident));
1005 ty::ty_enum(_, _) => {
1006 match self.tcx.def_map.borrow().find(&pattern.id) {
1007 Some(&def::DefVariant(_, variant_id, _)) => {
1008 for field in fields.iter() {
1009 self.check_field(pattern.span, variant_id,
1010 NamedField(field.ident));
1013 _ => self.tcx.sess.span_bug(pattern.span,
1020 _ => self.tcx.sess.span_bug(pattern.span,
1021 "struct pattern didn't have \
1026 // Patterns which bind no fields are allowable (the path is check
1028 ast::PatEnum(_, Some(ref fields)) => {
1029 match ty::get(ty::pat_ty(self.tcx, pattern)).sty {
1030 ty::ty_struct(id, _) => {
1031 for (i, field) in fields.iter().enumerate() {
1033 ast::PatWild(..) => continue,
1036 self.check_field(field.span, id, UnnamedField(i));
1039 ty::ty_enum(..) => {
1040 // enum fields have no privacy at this time
1049 visit::walk_pat(self, pattern);
1052 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
1053 self.in_foreign = true;
1054 visit::walk_foreign_item(self, fi);
1055 self.in_foreign = false;
1058 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
1059 self.check_path(path.span, id, path);
1060 visit::walk_path(self, path);
1064 ////////////////////////////////////////////////////////////////////////////////
1065 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1066 ////////////////////////////////////////////////////////////////////////////////
1068 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1069 tcx: &'a ty::ctxt<'tcx>,
1073 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1074 fn visit_item(&mut self, item: &ast::Item) {
1076 self.check_all_inherited(item);
1078 self.check_sane_privacy(item);
1081 let in_fn = self.in_fn;
1082 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1083 ast::ItemMod(..) => false, // modules turn privacy back on
1084 _ => in_fn, // otherwise we inherit
1086 visit::walk_item(self, item);
1087 self.in_fn = orig_in_fn;
1090 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1091 b: &'v ast::Block, s: Span, _: ast::NodeId) {
1092 // This catches both functions and methods
1093 let orig_in_fn = replace(&mut self.in_fn, true);
1094 visit::walk_fn(self, fk, fd, b, s);
1095 self.in_fn = orig_in_fn;
1098 fn visit_view_item(&mut self, i: &ast::ViewItem) {
1100 ast::Inherited => {}
1103 self.tcx.sess.span_err(i.span, "unnecessary `pub`, imports \
1104 in functions are never \
1108 ast::ViewItemExternCrate(..) => {
1109 self.tcx.sess.span_err(i.span, "`pub` visibility \
1117 visit::walk_view_item(self, i);
1121 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1122 /// Validates all of the visibility qualifiers placed on the item given. This
1123 /// ensures that there are no extraneous qualifiers that don't actually do
1124 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1125 /// later on down the road...
1126 fn check_sane_privacy(&self, item: &ast::Item) {
1128 let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
1129 if vis != ast::Inherited {
1130 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1132 tcx.sess.span_note(sp, note);
1137 // implementations of traits don't need visibility qualifiers because
1138 // that's controlled by having the trait in scope.
1139 ast::ItemImpl(_, Some(..), _, ref impl_items) => {
1140 check_inherited(item.span, item.vis,
1141 "visibility qualifiers have no effect on trait \
1143 for impl_item in impl_items.iter() {
1145 ast::MethodImplItem(ref m) => {
1146 check_inherited(m.span, m.pe_vis(), "");
1148 ast::TypeImplItem(_) => {}
1153 ast::ItemImpl(..) => {
1154 check_inherited(item.span, item.vis,
1155 "place qualifiers on individual methods instead");
1157 ast::ItemForeignMod(..) => {
1158 check_inherited(item.span, item.vis,
1159 "place qualifiers on individual functions \
1163 ast::ItemEnum(ref def, _) => {
1164 for v in def.variants.iter() {
1167 if item.vis == ast::Public {
1168 tcx.sess.span_err(v.span, "unnecessary `pub` \
1172 ast::Inherited => {}
1177 ast::ItemTrait(_, _, _, ref methods) => {
1178 for m in methods.iter() {
1180 ast::ProvidedMethod(ref m) => {
1181 check_inherited(m.span, m.pe_vis(),
1182 "unnecessary visibility");
1184 ast::RequiredMethod(ref m) => {
1185 check_inherited(m.span, m.vis,
1186 "unnecessary visibility");
1188 ast::TypeTraitItem(_) => {}
1193 ast::ItemStatic(..) | ast::ItemStruct(..) |
1194 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1195 ast::ItemMac(..) => {}
1199 /// When inside of something like a function or a method, visibility has no
1200 /// control over anything so this forbids any mention of any visibility
1201 fn check_all_inherited(&self, item: &ast::Item) {
1203 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
1204 if vis != ast::Inherited {
1205 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1208 let check_struct = |def: &ast::StructDef| {
1209 for f in def.fields.iter() {
1211 ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
1212 ast::UnnamedField(..) => {}
1216 check_inherited(tcx, item.span, item.vis);
1218 ast::ItemImpl(_, _, _, ref impl_items) => {
1219 for impl_item in impl_items.iter() {
1221 ast::MethodImplItem(ref m) => {
1222 check_inherited(tcx, m.span, m.pe_vis());
1224 ast::TypeImplItem(_) => {}
1228 ast::ItemForeignMod(ref fm) => {
1229 for i in fm.items.iter() {
1230 check_inherited(tcx, i.span, i.vis);
1233 ast::ItemEnum(ref def, _) => {
1234 for v in def.variants.iter() {
1235 check_inherited(tcx, v.span, v.node.vis);
1238 ast::StructVariantKind(ref s) => check_struct(&**s),
1239 ast::TupleVariantKind(..) => {}
1244 ast::ItemStruct(ref def, _) => check_struct(&**def),
1246 ast::ItemTrait(_, _, _, ref methods) => {
1247 for m in methods.iter() {
1249 ast::RequiredMethod(..) => {}
1250 ast::ProvidedMethod(ref m) => check_inherited(tcx, m.span,
1252 ast::TypeTraitItem(_) => {}
1257 ast::ItemStatic(..) |
1258 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1259 ast::ItemMac(..) => {}
1264 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1265 tcx: &'a ty::ctxt<'tcx>,
1266 exported_items: &'a ExportedItems,
1267 public_items: &'a PublicItems,
1270 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1271 inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1272 /// whether the type refers to private types.
1273 contains_private: bool,
1274 /// whether we've recurred at all (i.e. if we're pointing at the
1275 /// first type on which visit_ty was called).
1276 at_outer_type: bool,
1277 // whether that first type is a public path.
1278 outer_type_is_public_path: bool,
1281 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1282 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1283 let did = match self.tcx.def_map.borrow().find_copy(&path_id) {
1284 // `int` etc. (None doesn't seem to occur.)
1285 None | Some(def::DefPrimTy(..)) => return false,
1286 Some(def) => def.def_id()
1288 // A path can only be private if:
1289 // it's in this crate...
1293 // .. and it corresponds to a private type in the AST (this returns
1294 // None for type parameters)
1295 match self.tcx.map.find(did.node) {
1296 Some(ast_map::NodeItem(ref item)) => item.vis != ast::Public,
1297 Some(_) | None => false,
1301 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1302 // FIXME: this would preferably be using `exported_items`, but all
1303 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1304 self.public_items.contains(&trait_id)
1307 fn check_ty_param_bound(&self,
1309 ty_param_bound: &ast::TyParamBound) {
1310 match *ty_param_bound {
1311 ast::TraitTyParamBound(ref trait_ref) => {
1312 if !self.tcx.sess.features.borrow().visible_private_types &&
1313 self.path_is_private_type(trait_ref.ref_id) {
1314 self.tcx.sess.span_err(span,
1315 "private type in exported type \
1324 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1325 fn visit_ty(&mut self, ty: &ast::Ty) {
1327 ast::TyPath(_, _, path_id) => {
1328 if self.inner.path_is_private_type(path_id) {
1329 self.contains_private = true;
1330 // found what we're looking for so let's stop
1333 } else if self.at_outer_type {
1334 self.outer_type_is_public_path = true;
1339 self.at_outer_type = false;
1340 visit::walk_ty(self, ty)
1343 // don't want to recurse into [, .. expr]
1344 fn visit_expr(&mut self, _: &ast::Expr) {}
1347 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1348 fn visit_item(&mut self, item: &ast::Item) {
1350 // contents of a private mod can be reexported, so we need
1351 // to check internals.
1352 ast::ItemMod(_) => {}
1354 // An `extern {}` doesn't introduce a new privacy
1355 // namespace (the contents have their own privacies).
1356 ast::ItemForeignMod(_) => {}
1358 ast::ItemTrait(_, _, ref bounds, _) => {
1359 if !self.trait_is_public(item.id) {
1363 for bound in bounds.iter() {
1364 self.check_ty_param_bound(item.span, bound)
1368 // impls need some special handling to try to offer useful
1369 // error messages without (too many) false positives
1370 // (i.e. we could just return here to not check them at
1371 // all, or some worse estimation of whether an impl is
1372 // publicly visible.
1373 ast::ItemImpl(ref g, ref trait_ref, ref self_, ref impl_items) => {
1374 // `impl [... for] Private` is never visible.
1375 let self_contains_private;
1376 // impl [... for] Public<...>, but not `impl [... for]
1377 // ~[Public]` or `(Public,)` etc.
1378 let self_is_public_path;
1380 // check the properties of the Self type:
1382 let mut visitor = CheckTypeForPrivatenessVisitor {
1384 contains_private: false,
1385 at_outer_type: true,
1386 outer_type_is_public_path: false,
1388 visitor.visit_ty(&**self_);
1389 self_contains_private = visitor.contains_private;
1390 self_is_public_path = visitor.outer_type_is_public_path;
1393 // miscellaneous info about the impl
1395 // `true` iff this is `impl Private for ...`.
1396 let not_private_trait =
1397 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1399 let did = ty::trait_ref_to_def_id(self.tcx, tr);
1401 !is_local(did) || self.trait_is_public(did.node)
1404 // `true` iff this is a trait impl or at least one method is public.
1406 // `impl Public { $( fn ...() {} )* }` is not visible.
1408 // This is required over just using the methods' privacy
1409 // directly because we might have `impl<T: Foo<Private>> ...`,
1410 // and we shouldn't warn about the generics if all the methods
1411 // are private (because `T` won't be visible externally).
1412 let trait_or_some_public_method =
1413 trait_ref.is_some() ||
1417 ast::MethodImplItem(ref m) => {
1418 self.exported_items.contains(&m.id)
1420 ast::TypeImplItem(_) => false,
1424 if !self_contains_private &&
1425 not_private_trait &&
1426 trait_or_some_public_method {
1428 visit::walk_generics(self, g);
1432 for impl_item in impl_items.iter() {
1434 ast::MethodImplItem(ref method) => {
1435 visit::walk_method_helper(self, &**method)
1437 ast::TypeImplItem(_) => {}
1442 // Any private types in a trait impl fall into two
1444 // 1. mentioned in the trait definition
1445 // 2. mentioned in the type params/generics
1447 // Those in 1. can only occur if the trait is in
1448 // this crate and will've been warned about on the
1449 // trait definition (there's no need to warn twice
1450 // so we don't check the methods).
1452 // Those in 2. are warned via walk_generics and this
1454 visit::walk_trait_ref_helper(self, tr)
1457 } else if trait_ref.is_none() && self_is_public_path {
1458 // impl Public<Private> { ... }. Any public static
1459 // methods will be visible as `Public::foo`.
1460 let mut found_pub_static = false;
1461 for impl_item in impl_items.iter() {
1463 ast::MethodImplItem(ref method) => {
1464 if method.pe_explicit_self().node ==
1467 .contains(&method.id) {
1468 found_pub_static = true;
1469 visit::walk_method_helper(self, &**method);
1472 ast::TypeImplItem(_) => {}
1475 if found_pub_static {
1476 visit::walk_generics(self, g)
1482 // `type ... = ...;` can contain private types, because
1483 // we're introducing a new name.
1484 ast::ItemTy(..) => return,
1486 // not at all public, so we don't care
1487 _ if !self.exported_items.contains(&item.id) => return,
1492 // we've carefully constructed it so that if we're here, then
1493 // any `visit_ty`'s will be called on things that are in
1494 // public signatures, i.e. things that we're interested in for
1496 visit::walk_item(self, item);
1499 fn visit_generics(&mut self, generics: &ast::Generics) {
1500 for ty_param in generics.ty_params.iter() {
1501 for bound in ty_param.bounds.iter() {
1502 self.check_ty_param_bound(ty_param.span, bound)
1505 for predicate in generics.where_clause.predicates.iter() {
1506 for bound in predicate.bounds.iter() {
1507 self.check_ty_param_bound(predicate.span, bound)
1512 fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
1513 if self.exported_items.contains(&item.id) {
1514 visit::walk_foreign_item(self, item)
1518 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1519 b: &'v ast::Block, s: Span, id: ast::NodeId) {
1520 // needs special handling for methods.
1521 if self.exported_items.contains(&id) {
1522 visit::walk_fn(self, fk, fd, b, s);
1526 fn visit_ty(&mut self, t: &ast::Ty) {
1528 ast::TyPath(ref p, _, path_id) => {
1529 if !self.tcx.sess.features.borrow().visible_private_types &&
1530 self.path_is_private_type(path_id) {
1531 self.tcx.sess.span_err(p.span,
1532 "private type in exported type \
1538 visit::walk_ty(self, t)
1541 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
1542 if self.exported_items.contains(&v.node.id) {
1543 visit::walk_variant(self, v, g);
1547 fn visit_struct_field(&mut self, s: &ast::StructField) {
1549 ast::NamedField(_, ast::Public) => {
1550 visit::walk_struct_field(self, s);
1557 // we don't need to introspect into these at all: an
1558 // expression/block context can't possibly contain exported
1559 // things, and neither do view_items. (Making them no-ops stops us
1560 // from traversing the whole AST without having to be super
1561 // careful about our `walk_...` calls above.)
1562 fn visit_view_item(&mut self, _: &ast::ViewItem) {}
1563 fn visit_block(&mut self, _: &ast::Block) {}
1564 fn visit_expr(&mut self, _: &ast::Expr) {}
1567 pub fn check_crate(tcx: &ty::ctxt,
1568 exp_map2: &resolve::ExportMap2,
1569 external_exports: resolve::ExternalExports,
1570 last_private_map: resolve::LastPrivateMap)
1571 -> (ExportedItems, PublicItems) {
1572 let krate = tcx.map.krate();
1574 // Figure out who everyone's parent is
1575 let mut visitor = ParentVisitor {
1576 parents: NodeMap::new(),
1577 curparent: ast::DUMMY_NODE_ID,
1579 visit::walk_crate(&mut visitor, krate);
1581 // Use the parent map to check the privacy of everything
1582 let mut visitor = PrivacyVisitor {
1583 curitem: ast::DUMMY_NODE_ID,
1586 parents: visitor.parents,
1587 external_exports: external_exports,
1588 last_private_map: last_private_map,
1590 visit::walk_crate(&mut visitor, krate);
1592 // Sanity check to make sure that all privacy usage and controls are
1594 let mut visitor = SanePrivacyVisitor {
1598 visit::walk_crate(&mut visitor, krate);
1600 tcx.sess.abort_if_errors();
1602 // Build up a set of all exported items in the AST. This is a set of all
1603 // items which are reachable from external crates based on visibility.
1604 let mut visitor = EmbargoVisitor {
1606 exported_items: NodeSet::new(),
1607 public_items: NodeSet::new(),
1608 reexports: NodeSet::new(),
1610 prev_exported: true,
1614 let before = visitor.exported_items.len();
1615 visit::walk_crate(&mut visitor, krate);
1616 if before == visitor.exported_items.len() {
1621 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1624 let mut visitor = VisiblePrivateTypesVisitor {
1626 exported_items: &exported_items,
1627 public_items: &public_items
1629 visit::walk_crate(&mut visitor, krate);
1631 return (exported_items, public_items);