1 // Copyright 2012-2013 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;
16 use collections::{HashSet, HashMap};
18 use metadata::csearch;
22 use middle::typeck::{MethodMap, MethodOrigin, MethodParam};
23 use middle::typeck::{MethodStatic, MethodObject};
27 use syntax::ast_util::{is_local, def_id_of_def, local_def};
29 use syntax::codemap::Span;
30 use syntax::parse::token;
33 use syntax::visit::Visitor;
35 type Context<'a> = (&'a MethodMap, &'a resolve::ExportMap2);
37 /// A set of AST nodes exported by the crate.
38 pub type ExportedItems = HashSet<ast::NodeId>;
40 /// A set of AST nodes that are fully public in the crate. This map is used for
41 /// documentation purposes (reexporting a private struct inlines the doc,
42 /// reexporting a public struct doesn't inline the doc).
43 pub type PublicItems = HashSet<ast::NodeId>;
45 /// Result of a checking operation - None => no errors were found. Some => an
46 /// error and contains the span and message for reporting that error and
47 /// optionally the same for a note about the error.
48 type CheckResult = Option<(Span, ~str, Option<(Span, ~str)>)>;
50 ////////////////////////////////////////////////////////////////////////////////
51 /// The parent visitor, used to determine what's the parent of what (node-wise)
52 ////////////////////////////////////////////////////////////////////////////////
54 struct ParentVisitor {
55 parents: HashMap<ast::NodeId, ast::NodeId>,
56 curparent: ast::NodeId,
59 impl Visitor<()> for ParentVisitor {
60 fn visit_item(&mut self, item: &ast::Item, _: ()) {
61 self.parents.insert(item.id, self.curparent);
63 let prev = self.curparent;
65 ast::ItemMod(..) => { self.curparent = item.id; }
66 // Enum variants are parented to the enum definition itself beacuse
67 // they inherit privacy
68 ast::ItemEnum(ref def, _) => {
69 for variant in def.variants.iter() {
70 // If variants are private, then their logical "parent" is
71 // the enclosing module because everyone in the enclosing
72 // module can still use the private variant
73 if variant.node.vis == ast::Private {
74 self.parents.insert(variant.node.id, self.curparent);
76 // Otherwise, if the variant is public, then the parent is
77 // considered the enclosing enum because the enum will
78 // dictate the privacy visibility of this variant instead.
80 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 methods) if item.vis != ast::Public => {
91 for m in methods.iter() {
93 ast::Provided(ref m) => self.parents.insert(m.id, item.id),
94 ast::Required(ref m) => self.parents.insert(m.id, item.id),
101 visit::walk_item(self, item, ());
102 self.curparent = prev;
105 fn visit_foreign_item(&mut self, a: &ast::ForeignItem, _: ()) {
106 self.parents.insert(a.id, self.curparent);
107 visit::walk_foreign_item(self, a, ());
110 fn visit_fn(&mut self, a: &visit::FnKind, b: &ast::FnDecl,
111 c: &ast::Block, d: Span, id: ast::NodeId, _: ()) {
112 // We already took care of some trait methods above, otherwise things
113 // like impl methods and pub trait methods are parented to the
114 // containing module, not the containing trait.
115 if !self.parents.contains_key(&id) {
116 self.parents.insert(id, self.curparent);
118 visit::walk_fn(self, a, b, c, d, id, ());
121 fn visit_struct_def(&mut self, s: &ast::StructDef, i: ast::Ident,
122 g: &ast::Generics, n: ast::NodeId, _: ()) {
123 // Struct constructors are parented to their struct definitions because
124 // they essentially are the struct definitions.
126 Some(id) => { self.parents.insert(id, n); }
130 // While we have the id of the struct definition, go ahead and parent
132 for field in s.fields.iter() {
133 self.parents.insert(field.node.id, self.curparent);
135 visit::walk_struct_def(self, s, i, g, n, ())
139 ////////////////////////////////////////////////////////////////////////////////
140 /// The embargo visitor, used to determine the exports of the ast
141 ////////////////////////////////////////////////////////////////////////////////
143 struct EmbargoVisitor<'a> {
145 exp_map2: &'a resolve::ExportMap2,
147 // This flag is an indicator of whether the previous item in the
148 // hierarchical chain was exported or not. This is the indicator of whether
149 // children should be exported as well. Note that this can flip from false
150 // to true if a reexported module is entered (or an action similar).
153 // This is a list of all exported items in the AST. An exported item is any
154 // function/method/item which is usable by external crates. This essentially
155 // means that the result is "public all the way down", but the "path down"
156 // may jump across private boundaries through reexport statements.
157 exported_items: ExportedItems,
159 // This sets contains all the destination nodes which are publicly
160 // re-exported. This is *not* a set of all reexported nodes, only a set of
161 // all nodes which are reexported *and* reachable from external crates. This
162 // means that the destination of the reexport is exported, and hence the
163 // destination must also be exported.
164 reexports: HashSet<ast::NodeId>,
166 // These two fields are closely related to one another in that they are only
167 // used for generation of the 'PublicItems' set, not for privacy checking at
169 public_items: PublicItems,
173 impl<'a> EmbargoVisitor<'a> {
174 // There are checks inside of privacy which depend on knowing whether a
175 // trait should be exported or not. The two current consumers of this are:
177 // 1. Should default methods of a trait be exported?
178 // 2. Should the methods of an implementation of a trait be exported?
180 // The answer to both of these questions partly rely on whether the trait
181 // itself is exported or not. If the trait is somehow exported, then the
182 // answers to both questions must be yes. Right now this question involves
183 // more analysis than is currently done in rustc, so we conservatively
184 // answer "yes" so that all traits need to be exported.
185 fn exported_trait(&self, _id: ast::NodeId) -> bool {
190 impl<'a> Visitor<()> for EmbargoVisitor<'a> {
191 fn visit_item(&mut self, item: &ast::Item, _: ()) {
192 let orig_all_pub = self.prev_public;
193 self.prev_public = orig_all_pub && item.vis == ast::Public;
194 if self.prev_public {
195 self.public_items.insert(item.id);
198 let orig_all_exported = self.prev_exported;
200 // impls/extern blocks do not break the "public chain" because they
201 // cannot have visibility qualifiers on them anyway
202 ast::ItemImpl(..) | ast::ItemForeignMod(..) => {}
204 // Traits are a little special in that even if they themselves are
205 // not public they may still be exported.
206 ast::ItemTrait(..) => {
207 self.prev_exported = self.exported_trait(item.id);
210 // Private by default, hence we only retain the "public chain" if
211 // `pub` is explicitly listed.
214 (orig_all_exported && item.vis == ast::Public) ||
215 self.reexports.contains(&item.id);
219 let public_first = self.prev_exported &&
220 self.exported_items.insert(item.id);
223 // Enum variants inherit from their parent, so if the enum is
224 // public all variants are public unless they're explicitly priv
225 ast::ItemEnum(ref def, _) if public_first => {
226 for variant in def.variants.iter() {
227 if variant.node.vis != ast::Private {
228 self.exported_items.insert(variant.node.id);
233 // Implementations are a little tricky to determine what's exported
234 // out of them. Here's a few cases which are currently defined:
236 // * Impls for private types do not need to export their methods
237 // (either public or private methods)
239 // * Impls for public types only have public methods exported
241 // * Public trait impls for public types must have all methods
244 // * Private trait impls for public types can be ignored
246 // * Public trait impls for private types have their methods
247 // exported. I'm not entirely certain that this is the correct
248 // thing to do, but I have seen use cases of where this will cause
249 // undefined symbols at linkage time if this case is not handled.
251 // * Private trait impls for private types can be completely ignored
252 ast::ItemImpl(_, _, ref ty, ref methods) => {
253 let public_ty = match ty.node {
254 ast::TyPath(_, _, id) => {
255 let def_map = self.tcx.def_map.borrow();
256 match def_map.get().get_copy(&id) {
257 ast::DefPrimTy(..) => true,
259 let did = def_id_of_def(def);
261 self.exported_items.contains(&did.node)
267 let tr = ty::impl_trait_ref(self.tcx, local_def(item.id));
268 let public_trait = tr.map_or(false, |tr| {
269 !is_local(tr.def_id) ||
270 self.exported_items.contains(&tr.def_id.node)
273 if public_ty || public_trait {
274 for method in methods.iter() {
275 let meth_public = match method.explicit_self.node {
276 ast::SelfStatic => public_ty,
278 } && method.vis == ast::Public;
279 if meth_public || tr.is_some() {
280 self.exported_items.insert(method.id);
286 // Default methods on traits are all public so long as the trait
288 ast::ItemTrait(_, _, ref methods) if public_first => {
289 for method in methods.iter() {
291 ast::Provided(ref m) => {
292 debug!("provided {}", m.id);
293 self.exported_items.insert(m.id);
295 ast::Required(ref m) => {
296 debug!("required {}", m.id);
297 self.exported_items.insert(m.id);
303 // Struct constructors are public if the struct is all public.
304 ast::ItemStruct(ref def, _) if public_first => {
306 Some(id) => { self.exported_items.insert(id); }
314 visit::walk_item(self, item, ());
316 self.prev_exported = orig_all_exported;
317 self.prev_public = orig_all_pub;
320 fn visit_foreign_item(&mut self, a: &ast::ForeignItem, _: ()) {
321 if self.prev_exported && a.vis == ast::Public {
322 self.exported_items.insert(a.id);
326 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId, _: ()) {
327 // This code is here instead of in visit_item so that the
328 // crate module gets processed as well.
329 if self.prev_exported {
330 let exp_map2 = self.exp_map2.borrow();
331 assert!(exp_map2.get().contains_key(&id), "wut {:?}", id);
332 for export in exp_map2.get().get(&id).iter() {
333 if is_local(export.def_id) {
334 self.reexports.insert(export.def_id.node);
338 visit::walk_mod(self, m, ())
342 ////////////////////////////////////////////////////////////////////////////////
343 /// The privacy visitor, where privacy checks take place (violations reported)
344 ////////////////////////////////////////////////////////////////////////////////
346 struct PrivacyVisitor<'a> {
348 curitem: ast::NodeId,
351 method_map: &'a MethodMap,
352 parents: HashMap<ast::NodeId, ast::NodeId>,
353 external_exports: resolve::ExternalExports,
354 last_private_map: resolve::LastPrivateMap,
360 DisallowedBy(ast::NodeId),
363 impl<'a> PrivacyVisitor<'a> {
364 // used when debugging
365 fn nodestr(&self, id: ast::NodeId) -> ~str {
366 self.tcx.map.node_to_str(id)
369 // Determines whether the given definition is public from the point of view
370 // of the current item.
371 fn def_privacy(&self, did: ast::DefId) -> PrivacyResult {
373 if self.external_exports.contains(&did) {
374 debug!("privacy - {:?} was externally exported", did);
377 debug!("privacy - is {:?} a public method", did);
379 let methods = self.tcx.methods.borrow();
380 return match methods.get().find(&did) {
382 debug!("privacy - well at least it's a method: {:?}", meth);
383 match meth.container {
384 ty::TraitContainer(id) => {
385 debug!("privacy - recursing on trait {:?}", id);
388 ty::ImplContainer(id) => {
389 match ty::impl_trait_ref(self.tcx, id) {
391 debug!("privacy - impl of trait {:?}", id);
392 self.def_privacy(t.def_id)
395 debug!("privacy - found a method {:?}",
397 if meth.vis == ast::Public {
408 debug!("privacy - nope, not even a method");
414 debug!("privacy - local {:?} not public all the way down", did);
415 // return quickly for things in the same module
416 if self.parents.find(&did.node) == self.parents.find(&self.curitem) {
417 debug!("privacy - same parent, we're done here");
421 // We now know that there is at least one private member between the
422 // destination and the root.
423 let mut closest_private_id = did.node;
425 debug!("privacy - examining {}", self.nodestr(closest_private_id));
426 let vis = match self.tcx.map.find(closest_private_id) {
427 // If this item is a method, then we know for sure that it's an
428 // actual method and not a static method. The reason for this is
429 // that these cases are only hit in the ExprMethodCall
430 // expression, and ExprCall will have its path checked later
431 // (the path of the trait/impl) if it's a static method.
433 // With this information, then we can completely ignore all
434 // trait methods. The privacy violation would be if the trait
435 // couldn't get imported, not if the method couldn't be used
436 // (all trait methods are public).
438 // However, if this is an impl method, then we dictate this
439 // decision solely based on the privacy of the method
441 // FIXME(#10573) is this the right behavior? Why not consider
442 // where the method was defined?
443 Some(ast_map::NodeMethod(ref m)) => {
444 let imp = self.tcx.map.get_parent_did(closest_private_id);
445 match ty::impl_trait_ref(self.tcx, imp) {
446 Some(..) => return Allowable,
447 _ if m.vis == ast::Public => return Allowable,
451 Some(ast_map::NodeTraitMethod(_)) => {
455 // This is not a method call, extract the visibility as one
456 // would normally look at it
457 Some(ast_map::NodeItem(it)) => it.vis,
458 Some(ast_map::NodeForeignItem(_)) => {
459 self.tcx.map.get_foreign_vis(closest_private_id)
461 Some(ast_map::NodeVariant(ref v)) => {
462 // sadly enum variants still inherit visibility, so only
463 // break out of this is explicitly private
464 if v.node.vis == ast::Private { break }
465 ast::Public // need to move up a level (to the enum)
469 if vis != ast::Public { break }
470 // if we've reached the root, then everything was allowable and this
472 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
473 closest_private_id = *self.parents.get(&closest_private_id);
475 // If we reached the top, then we were public all the way down and
476 // we can allow this access.
477 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
479 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
480 if self.private_accessible(closest_private_id) {
483 DisallowedBy(closest_private_id)
487 /// For a local private node in the AST, this function will determine
488 /// whether the node is accessible by the current module that iteration is
490 fn private_accessible(&self, id: ast::NodeId) -> bool {
491 let parent = *self.parents.get(&id);
492 debug!("privacy - accessible parent {}", self.nodestr(parent));
494 // After finding `did`'s closest private member, we roll ourselves back
495 // to see if this private member's parent is anywhere in our ancestry.
496 // By the privacy rules, we can access all of our ancestor's private
497 // members, so that's why we test the parent, and not the did itself.
498 let mut cur = self.curitem;
500 debug!("privacy - questioning {}", self.nodestr(cur));
502 // If the relevant parent is in our history, then we're allowed
503 // to look inside any of our ancestor's immediate private items,
504 // so this access is valid.
505 x if x == parent => return true,
507 // If we've reached the root, then we couldn't access this item
508 // in the first place
509 ast::DUMMY_NODE_ID => return false,
515 cur = *self.parents.get(&cur);
519 fn report_error(&self, result: CheckResult) -> bool {
522 Some((span, msg, note)) => {
523 self.tcx.sess.span_err(span, msg);
525 Some((span, msg)) => self.tcx.sess.span_note(span, msg),
533 /// Guarantee that a particular definition is public. Returns a CheckResult
534 /// which contains any errors found. These can be reported using `report_error`.
535 /// If the result is `None`, no errors were found.
536 fn ensure_public(&self, span: Span, to_check: ast::DefId,
537 source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
538 match self.def_privacy(to_check) {
539 ExternallyDenied => Some((span, format!("{} is private", msg), None)),
540 DisallowedBy(id) => {
541 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
542 return Some((span, format!("{} is private", msg), None));
544 (span, format!("{} is inaccessible", msg))
546 match self.tcx.map.find(id) {
547 Some(ast_map::NodeItem(item)) => {
548 let desc = match item.node {
549 ast::ItemMod(..) => "module",
550 ast::ItemTrait(..) => "trait",
551 _ => return Some((err_span, err_msg, None)),
553 let msg = format!("{} `{}` is private",
555 token::get_ident(item.ident));
556 Some((err_span, err_msg, Some((span, msg))))
558 _ => Some((err_span, err_msg, None)),
565 // Checks that a field is in scope.
566 // FIXME #6993: change type (and name) from Ident to Name
567 fn check_field(&mut self, span: Span, id: ast::DefId, ident: ast::Ident,
568 enum_id: Option<ast::DefId>) {
569 let fields = ty::lookup_struct_fields(self.tcx, id);
570 let struct_vis = if is_local(id) {
571 match self.tcx.map.get(id.node) {
572 ast_map::NodeItem(ref it) => it.vis,
573 ast_map::NodeVariant(ref v) => {
574 if v.node.vis == ast::Inherited {
575 let parent = self.tcx.map.get_parent(id.node);
576 self.tcx.map.expect_item(parent).vis
582 self.tcx.sess.span_bug(span,
583 format!("not an item or variant def"));
587 let cstore = self.tcx.sess.cstore;
590 let v = csearch::get_enum_variants(self.tcx, enum_id);
591 match v.iter().find(|v| v.id == id) {
593 if variant.vis == ast::Inherited {
594 csearch::get_item_visibility(cstore, enum_id)
600 self.tcx.sess.span_bug(span, "no xcrate variant");
604 None => csearch::get_item_visibility(cstore, id)
608 for field in fields.iter() {
609 if field.name != ident.name { continue; }
610 // public structs have public fields by default, and private structs
611 // have private fields by default.
612 if struct_vis == ast::Public && field.vis != ast::Private { break }
613 if struct_vis != ast::Public && field.vis == ast::Public { break }
614 if !is_local(field.id) ||
615 !self.private_accessible(field.id.node) {
616 self.tcx.sess.span_err(span,
617 format!("field `{}` is private",
618 token::get_ident(ident)))
624 // Given the ID of a method, checks to ensure it's in scope.
625 fn check_static_method(&mut self, span: Span, method_id: ast::DefId,
627 // If the method is a default method, we need to use the def_id of
628 // the default implementation.
629 let method_id = ty::method(self.tcx, method_id).provided_source
630 .unwrap_or(method_id);
632 let string = token::get_ident(name);
633 self.report_error(self.ensure_public(span,
636 format!("method `{}`", string)));
639 // Checks that a path is in scope.
640 fn check_path(&mut self, span: Span, path_id: ast::NodeId, path: &ast::Path) {
641 debug!("privacy - path {}", self.nodestr(path_id));
642 let def_map = self.tcx.def_map.borrow();
643 let orig_def = def_map.get().get_copy(&path_id);
644 let ck = |tyname: &str| {
645 let ck_public = |def: ast::DefId| {
646 let name = token::get_ident(path.segments
650 let origdid = def_id_of_def(orig_def);
651 self.ensure_public(span,
659 match *self.last_private_map.get(&path_id) {
660 resolve::LastMod(resolve::AllPublic) => {},
661 resolve::LastMod(resolve::DependsOn(def)) => {
662 self.report_error(ck_public(def));
664 resolve::LastImport{value_priv: value_priv,
665 value_used: check_value,
666 type_priv: type_priv,
667 type_used: check_type} => {
668 // This dance with found_error is because we don't want to report
669 // a privacy error twice for the same directive.
670 let found_error = match (type_priv, check_type) {
671 (Some(resolve::DependsOn(def)), resolve::Used) => {
672 !self.report_error(ck_public(def))
677 match (value_priv, check_value) {
678 (Some(resolve::DependsOn(def)), resolve::Used) => {
679 self.report_error(ck_public(def));
684 // If an import is not used in either namespace, we still want to check
685 // that it could be legal. Therefore we check in both namespaces and only
686 // report an error if both would be illegal. We only report one error,
687 // even if it is illegal to import from both namespaces.
688 match (value_priv, check_value, type_priv, check_type) {
689 (Some(p), resolve::Unused, None, _) |
690 (None, _, Some(p), resolve::Unused) => {
692 resolve::AllPublic => None,
693 resolve::DependsOn(def) => ck_public(def),
696 self.report_error(p);
699 (Some(v), resolve::Unused, Some(t), resolve::Unused) => {
701 resolve::AllPublic => None,
702 resolve::DependsOn(def) => ck_public(def),
705 resolve::AllPublic => None,
706 resolve::DependsOn(def) => ck_public(def),
709 (Some(_), Some(t)) => {
710 self.report_error(Some(t));
720 // FIXME(#12334) Imports can refer to definitions in both the type and
721 // value namespaces. The privacy information is aware of this, but the
722 // def map is not. Therefore the names we work out below will not always
723 // be accurate and we can get slightly wonky error messages (but type
724 // checking is always correct).
725 let def_map = self.tcx.def_map.borrow();
726 match def_map.get().get_copy(&path_id) {
727 ast::DefStaticMethod(..) => ck("static method"),
728 ast::DefFn(..) => ck("function"),
729 ast::DefStatic(..) => ck("static"),
730 ast::DefVariant(..) => ck("variant"),
731 ast::DefTy(..) => ck("type"),
732 ast::DefTrait(..) => ck("trait"),
733 ast::DefStruct(..) => ck("struct"),
734 ast::DefMethod(_, Some(..)) => ck("trait method"),
735 ast::DefMethod(..) => ck("method"),
736 ast::DefMod(..) => ck("module"),
741 // Checks that a method is in scope.
742 fn check_method(&mut self, span: Span, origin: MethodOrigin,
745 MethodStatic(method_id) => {
746 self.check_static_method(span, method_id, ident)
748 // Trait methods are always all public. The only controlling factor
749 // is whether the trait itself is accessible or not.
750 MethodParam(MethodParam { trait_id: trait_id, .. }) |
751 MethodObject(MethodObject { trait_id: trait_id, .. }) => {
752 self.report_error(self.ensure_public(span, trait_id, None, "source trait"));
758 impl<'a> Visitor<()> for PrivacyVisitor<'a> {
759 fn visit_item(&mut self, item: &ast::Item, _: ()) {
760 // Do not check privacy inside items with the resolve_unexported
761 // attribute. This is used for the test runner.
762 if attr::contains_name(item.attrs, "!resolve_unexported") {
766 let orig_curitem = replace(&mut self.curitem, item.id);
767 visit::walk_item(self, item, ());
768 self.curitem = orig_curitem;
771 fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
773 ast::ExprField(base, ident, _) => {
774 // Method calls are now a special syntactic form,
775 // so `a.b` should always be a field.
776 let method_map = self.method_map.borrow();
777 assert!(!method_map.get().contains_key(&expr.id));
779 // With type_autoderef, make sure we don't
780 // allow pointers to violate privacy
781 let t = ty::type_autoderef(ty::expr_ty(self.tcx, base));
782 match ty::get(t).sty {
783 ty::ty_struct(id, _) => {
784 self.check_field(expr.span, id, ident, None);
789 ast::ExprMethodCall(ident, _, ref args) => {
791 let t = ty::type_autoderef(ty::expr_ty(self.tcx, args[0]));
792 match ty::get(t).sty {
793 ty::ty_enum(_, _) | ty::ty_struct(_, _) => {
794 match self.method_map.borrow().get().find(&expr.id) {
796 self.tcx.sess.span_bug(expr.span,
797 "method call not in \
801 debug!("(privacy checking) checking impl method");
802 self.check_method(expr.span, method.origin, ident);
809 ast::ExprStruct(_, ref fields, _) => {
810 match ty::get(ty::expr_ty(self.tcx, expr)).sty {
811 ty::ty_struct(id, _) => {
812 for field in (*fields).iter() {
813 self.check_field(expr.span, id, field.ident.node,
817 ty::ty_enum(_, _) => {
818 let def_map = self.tcx.def_map.borrow();
819 match def_map.get().get_copy(&expr.id) {
820 ast::DefVariant(enum_id, variant_id, _) => {
821 for field in fields.iter() {
822 self.check_field(expr.span, variant_id,
827 _ => self.tcx.sess.span_bug(expr.span,
834 _ => self.tcx.sess.span_bug(expr.span, "struct expr \
842 visit::walk_expr(self, expr, ());
845 fn visit_view_item(&mut self, a: &ast::ViewItem, _: ()) {
847 ast::ViewItemExternMod(..) => {}
848 ast::ViewItemUse(ref uses) => {
849 for vpath in uses.iter() {
851 ast::ViewPathSimple(..) | ast::ViewPathGlob(..) => {}
852 ast::ViewPathList(_, ref list, _) => {
853 for pid in list.iter() {
854 debug!("privacy - list {}", pid.node.id);
855 let seg = ast::PathSegment {
856 identifier: pid.node.name,
857 lifetimes: opt_vec::Empty,
858 types: opt_vec::Empty,
861 let path = ast::Path {
866 self.check_path(pid.span, pid.node.id, &path);
873 visit::walk_view_item(self, a, ());
876 fn visit_pat(&mut self, pattern: &ast::Pat, _: ()) {
877 // Foreign functions do not have their patterns mapped in the def_map,
878 // and there's nothing really relevant there anyway, so don't bother
879 // checking privacy. If you can name the type then you can pass it to an
880 // external C function anyway.
881 if self.in_foreign { return }
884 ast::PatStruct(_, ref fields, _) => {
885 match ty::get(ty::pat_ty(self.tcx, pattern)).sty {
886 ty::ty_struct(id, _) => {
887 for field in fields.iter() {
888 self.check_field(pattern.span, id, field.ident,
892 ty::ty_enum(_, _) => {
893 let def_map = self.tcx.def_map.borrow();
894 match def_map.get().find(&pattern.id) {
895 Some(&ast::DefVariant(enum_id, variant_id, _)) => {
896 for field in fields.iter() {
897 self.check_field(pattern.span, variant_id,
898 field.ident, Some(enum_id));
901 _ => self.tcx.sess.span_bug(pattern.span,
908 _ => self.tcx.sess.span_bug(pattern.span,
909 "struct pattern didn't have \
916 visit::walk_pat(self, pattern, ());
919 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) {
920 self.in_foreign = true;
921 visit::walk_foreign_item(self, fi, ());
922 self.in_foreign = false;
925 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, _: ()) {
926 self.check_path(path.span, id, path);
927 visit::walk_path(self, path, ());
931 ////////////////////////////////////////////////////////////////////////////////
932 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
933 ////////////////////////////////////////////////////////////////////////////////
935 struct SanePrivacyVisitor {
940 impl Visitor<()> for SanePrivacyVisitor {
941 fn visit_item(&mut self, item: &ast::Item, _: ()) {
943 self.check_all_inherited(item);
945 self.check_sane_privacy(item);
948 let orig_in_fn = replace(&mut self.in_fn, match item.node {
949 ast::ItemMod(..) => false, // modules turn privacy back on
950 _ => self.in_fn, // otherwise we inherit
952 visit::walk_item(self, item, ());
953 self.in_fn = orig_in_fn;
956 fn visit_fn(&mut self, fk: &visit::FnKind, fd: &ast::FnDecl,
957 b: &ast::Block, s: Span, n: ast::NodeId, _: ()) {
958 // This catches both functions and methods
959 let orig_in_fn = replace(&mut self.in_fn, true);
960 visit::walk_fn(self, fk, fd, b, s, n, ());
961 self.in_fn = orig_in_fn;
964 fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
968 self.tcx.sess.span_err(i.span, "unnecessary visibility \
973 self.tcx.sess.span_err(i.span, "unnecessary `pub`, imports \
974 in functions are never \
978 ast::ViewItemExternMod(..) => {
979 self.tcx.sess.span_err(i.span, "`pub` visibility \
987 visit::walk_view_item(self, i, ());
991 impl SanePrivacyVisitor {
992 /// Validates all of the visibility qualifers placed on the item given. This
993 /// ensures that there are no extraneous qualifiers that don't actually do
994 /// anything. In theory these qualifiers wouldn't parse, but that may happen
995 /// later on down the road...
996 fn check_sane_privacy(&self, item: &ast::Item) {
998 let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
999 if vis != ast::Inherited {
1000 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1002 tcx.sess.span_note(sp, note);
1006 let check_not_priv = |sp: Span, vis: ast::Visibility, note: &str| {
1007 if vis == ast::Private {
1008 tcx.sess.span_err(sp, "unnecessary `priv` qualifier");
1010 tcx.sess.span_note(sp, note);
1014 let check_struct = |def: &@ast::StructDef,
1015 vis: ast::Visibility,
1016 parent_vis: Option<ast::Visibility>| {
1017 let public_def = match vis {
1018 ast::Public => true,
1019 ast::Inherited | ast::Private => parent_vis == Some(ast::Public),
1021 for f in def.fields.iter() {
1023 ast::NamedField(_, ast::Public) if public_def => {
1024 tcx.sess.span_err(f.span, "unnecessary `pub` \
1027 ast::NamedField(_, ast::Private) if !public_def => {
1028 tcx.sess.span_err(f.span, "unnecessary `priv` \
1031 ast::NamedField(..) | ast::UnnamedField => {}
1036 // implementations of traits don't need visibility qualifiers because
1037 // that's controlled by having the trait in scope.
1038 ast::ItemImpl(_, Some(..), _, ref methods) => {
1039 check_inherited(item.span, item.vis,
1040 "visibility qualifiers have no effect on trait \
1042 for m in methods.iter() {
1043 check_inherited(m.span, m.vis, "");
1047 ast::ItemImpl(_, _, _, ref methods) => {
1048 check_inherited(item.span, item.vis,
1049 "place qualifiers on individual methods instead");
1050 for i in methods.iter() {
1051 check_not_priv(i.span, i.vis, "functions are private by \
1055 ast::ItemForeignMod(ref fm) => {
1056 check_inherited(item.span, item.vis,
1057 "place qualifiers on individual functions \
1059 for i in fm.items.iter() {
1060 check_not_priv(i.span, i.vis, "functions are private by \
1065 ast::ItemEnum(ref def, _) => {
1066 for v in def.variants.iter() {
1069 if item.vis == ast::Public {
1070 tcx.sess.span_err(v.span, "unnecessary `pub` \
1075 if item.vis != ast::Public {
1076 tcx.sess.span_err(v.span, "unnecessary `priv` \
1080 ast::Inherited => {}
1084 ast::StructVariantKind(ref s) => {
1085 check_struct(s, v.node.vis, Some(item.vis));
1087 ast::TupleVariantKind(..) => {}
1092 ast::ItemStruct(ref def, _) => check_struct(def, item.vis, None),
1094 ast::ItemTrait(_, _, ref methods) => {
1095 for m in methods.iter() {
1097 ast::Provided(ref m) => {
1098 check_inherited(m.span, m.vis,
1099 "unnecessary visibility");
1101 ast::Required(..) => {}
1106 ast::ItemStatic(..) |
1107 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1108 ast::ItemMac(..) => {
1109 check_not_priv(item.span, item.vis, "items are private by \
1115 /// When inside of something like a function or a method, visibility has no
1116 /// control over anything so this forbids any mention of any visibility
1117 fn check_all_inherited(&self, item: &ast::Item) {
1119 let check_inherited = |sp: Span, vis: ast::Visibility| {
1120 if vis != ast::Inherited {
1121 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1124 let check_struct = |def: &@ast::StructDef| {
1125 for f in def.fields.iter() {
1127 ast::NamedField(_, p) => check_inherited(f.span, p),
1128 ast::UnnamedField => {}
1132 check_inherited(item.span, item.vis);
1134 ast::ItemImpl(_, _, _, ref methods) => {
1135 for m in methods.iter() {
1136 check_inherited(m.span, m.vis);
1139 ast::ItemForeignMod(ref fm) => {
1140 for i in fm.items.iter() {
1141 check_inherited(i.span, i.vis);
1144 ast::ItemEnum(ref def, _) => {
1145 for v in def.variants.iter() {
1146 check_inherited(v.span, v.node.vis);
1149 ast::StructVariantKind(ref s) => check_struct(s),
1150 ast::TupleVariantKind(..) => {}
1155 ast::ItemStruct(ref def, _) => check_struct(def),
1157 ast::ItemTrait(_, _, ref methods) => {
1158 for m in methods.iter() {
1160 ast::Required(..) => {}
1161 ast::Provided(ref m) => check_inherited(m.span, m.vis),
1166 ast::ItemStatic(..) |
1167 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1168 ast::ItemMac(..) => {}
1173 struct VisiblePrivateTypesVisitor<'a> {
1175 exported_items: &'a ExportedItems,
1176 public_items: &'a PublicItems,
1179 struct CheckTypeForPrivatenessVisitor<'a, 'b> {
1180 inner: &'b VisiblePrivateTypesVisitor<'a>,
1181 /// whether the type refers to private types.
1182 contains_private: bool,
1183 /// whether we've recurred at all (i.e. if we're pointing at the
1184 /// first type on which visit_ty was called).
1185 at_outer_type: bool,
1186 // whether that first type is a public path.
1187 outer_type_is_public_path: bool,
1190 impl<'a> VisiblePrivateTypesVisitor<'a> {
1191 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1192 let did = match self.tcx.def_map.borrow().get().find_copy(&path_id) {
1193 // `int` etc. (None doesn't seem to occur.)
1194 None | Some(ast::DefPrimTy(..)) => return false,
1195 Some(def) => def_id_of_def(def)
1197 // A path can only be private if:
1198 // it's in this crate...
1200 // ... it's not exported (obviously) ...
1201 !self.exported_items.contains(&did.node) &&
1202 // .. and it corresponds to a type in the AST (this returns None for
1204 self.tcx.map.find(did.node).is_some()
1207 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1208 // FIXME: this would preferably be using `exported_items`, but all
1209 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1210 self.public_items.contains(&trait_id)
1214 impl<'a, 'b> Visitor<()> for CheckTypeForPrivatenessVisitor<'a, 'b> {
1215 fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
1217 ast::TyPath(_, _, path_id) => {
1218 if self.inner.path_is_private_type(path_id) {
1219 self.contains_private = true;
1220 // found what we're looking for so let's stop
1223 } else if self.at_outer_type {
1224 self.outer_type_is_public_path = true;
1229 self.at_outer_type = false;
1230 visit::walk_ty(self, ty, ())
1233 // don't want to recurse into [, .. expr]
1234 fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
1237 impl<'a> Visitor<()> for VisiblePrivateTypesVisitor<'a> {
1238 fn visit_item(&mut self, item: &ast::Item, _: ()) {
1240 // contents of a private mod can be reexported, so we need
1241 // to check internals.
1242 ast::ItemMod(_) => {}
1244 // An `extern {}` doesn't introduce a new privacy
1245 // namespace (the contents have their own privacies).
1246 ast::ItemForeignMod(_) => {}
1248 ast::ItemTrait(..) if !self.trait_is_public(item.id) => return,
1250 // impls need some special handling to try to offer useful
1251 // error messages without (too many) false positives
1252 // (i.e. we could just return here to not check them at
1253 // all, or some worse estimation of whether an impl is
1254 // publically visible.
1255 ast::ItemImpl(ref g, ref trait_ref, self_, ref methods) => {
1256 // `impl [... for] Private` is never visible.
1257 let self_contains_private;
1258 // impl [... for] Public<...>, but not `impl [... for]
1259 // ~[Public]` or `(Public,)` etc.
1260 let self_is_public_path;
1262 // check the properties of the Self type:
1264 let mut visitor = CheckTypeForPrivatenessVisitor {
1266 contains_private: false,
1267 at_outer_type: true,
1268 outer_type_is_public_path: false,
1270 visitor.visit_ty(self_, ());
1271 self_contains_private = visitor.contains_private;
1272 self_is_public_path = visitor.outer_type_is_public_path;
1275 // miscellanous info about the impl
1277 // `true` iff this is `impl Private for ...`.
1278 let not_private_trait =
1279 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1281 let did = ty::trait_ref_to_def_id(self.tcx, tr);
1283 !is_local(did) || self.trait_is_public(did.node)
1286 // `true` iff this is a trait impl or at least one method is public.
1288 // `impl Public { $( fn ...() {} )* }` is not visible.
1290 // This is required over just using the methods' privacy
1291 // directly because we might have `impl<T: Foo<Private>> ...`,
1292 // and we shouldn't warn about the generics if all the methods
1293 // are private (because `T` won't be visible externally).
1294 let trait_or_some_public_method =
1295 trait_ref.is_some() ||
1296 methods.iter().any(|m| self.exported_items.contains(&m.id));
1298 if !self_contains_private &&
1299 not_private_trait &&
1300 trait_or_some_public_method {
1302 visit::walk_generics(self, g, ());
1306 for method in methods.iter() {
1307 visit::walk_method_helper(self, *method, ())
1311 // Any private types in a trait impl fall into two
1313 // 1. mentioned in the trait definition
1314 // 2. mentioned in the type params/generics
1316 // Those in 1. can only occur if the trait is in
1317 // this crate and will've been warned about on the
1318 // trait definition (there's no need to warn twice
1319 // so we don't check the methods).
1321 // Those in 2. are warned via walk_generics and this
1323 visit::walk_trait_ref_helper(self, tr, ())
1326 } else if trait_ref.is_none() && self_is_public_path {
1327 // impl Public<Private> { ... }. Any public static
1328 // methods will be visible as `Public::foo`.
1329 let mut found_pub_static = false;
1330 for method in methods.iter() {
1331 if method.explicit_self.node == ast::SelfStatic &&
1332 self.exported_items.contains(&method.id) {
1333 found_pub_static = true;
1334 visit::walk_method_helper(self, *method, ());
1337 if found_pub_static {
1338 visit::walk_generics(self, g, ())
1344 // `type ... = ...;` can contain private types, because
1345 // we're introducing a new name.
1346 ast::ItemTy(..) => return,
1348 // not at all public, so we don't care
1349 _ if !self.exported_items.contains(&item.id) => return,
1354 // we've carefully constructed it so that if we're here, then
1355 // any `visit_ty`'s will be called on things that are in
1356 // public signatures, i.e. things that we're interested in for
1358 visit::walk_item(self, item, ());
1361 fn visit_foreign_item(&mut self, item: &ast::ForeignItem, _: ()) {
1362 if self.exported_items.contains(&item.id) {
1363 visit::walk_foreign_item(self, item, ())
1367 fn visit_fn(&mut self,
1368 fk: &visit::FnKind, fd: &ast::FnDecl, b: &ast::Block, s: Span, id: ast::NodeId,
1370 // needs special handling for methods.
1371 if self.exported_items.contains(&id) {
1372 visit::walk_fn(self, fk, fd, b, s, id, ());
1376 fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
1378 ast::TyPath(ref p, _, path_id) => {
1379 if self.path_is_private_type(path_id) {
1380 self.tcx.sess.add_lint(lint::VisiblePrivateTypes,
1382 ~"private type in exported type signature");
1387 visit::walk_ty(self, t, ())
1390 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
1391 if self.exported_items.contains(&v.node.id) {
1392 visit::walk_variant(self, v, g, ());
1396 fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
1398 // the only way to get here is by being inside a public
1399 // struct/enum variant, so the only way to have a private
1400 // field is with an explicit `priv`.
1401 ast::NamedField(_, ast::Private) => {}
1403 _ => visit::walk_struct_field(self, s, ())
1408 // we don't need to introspect into these at all: an
1409 // expression/block context can't possibly contain exported
1410 // things, and neither do view_items. (Making them no-ops stops us
1411 // from traversing the whole AST without having to be super
1412 // careful about our `walk_...` calls above.)
1413 fn visit_view_item(&mut self, _: &ast::ViewItem, _: ()) {}
1414 fn visit_block(&mut self, _: &ast::Block, _: ()) {}
1415 fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
1418 pub fn check_crate(tcx: ty::ctxt,
1419 method_map: &MethodMap,
1420 exp_map2: &resolve::ExportMap2,
1421 external_exports: resolve::ExternalExports,
1422 last_private_map: resolve::LastPrivateMap,
1423 krate: &ast::Crate) -> (ExportedItems, PublicItems) {
1424 // Figure out who everyone's parent is
1425 let mut visitor = ParentVisitor {
1426 parents: HashMap::new(),
1427 curparent: ast::DUMMY_NODE_ID,
1429 visit::walk_crate(&mut visitor, krate, ());
1431 // Use the parent map to check the privacy of everything
1432 let mut visitor = PrivacyVisitor {
1433 curitem: ast::DUMMY_NODE_ID,
1437 parents: visitor.parents,
1438 method_map: method_map,
1439 external_exports: external_exports,
1440 last_private_map: last_private_map,
1442 visit::walk_crate(&mut visitor, krate, ());
1444 // Sanity check to make sure that all privacy usage and controls are
1446 let mut visitor = SanePrivacyVisitor {
1450 visit::walk_crate(&mut visitor, krate, ());
1452 tcx.sess.abort_if_errors();
1454 // Build up a set of all exported items in the AST. This is a set of all
1455 // items which are reachable from external crates based on visibility.
1456 let mut visitor = EmbargoVisitor {
1458 exported_items: HashSet::new(),
1459 public_items: HashSet::new(),
1460 reexports: HashSet::new(),
1462 prev_exported: true,
1466 let before = visitor.exported_items.len();
1467 visit::walk_crate(&mut visitor, krate, ());
1468 if before == visitor.exported_items.len() {
1473 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1476 let mut visitor = VisiblePrivateTypesVisitor {
1478 exported_items: &exported_items,
1479 public_items: &public_items
1481 visit::walk_crate(&mut visitor, krate, ());
1483 return (exported_items, public_items);