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;
17 use metadata::csearch;
21 use middle::typeck::{MethodCall, MethodMap, MethodOrigin, MethodParam};
22 use middle::typeck::{MethodStatic, MethodObject};
23 use util::nodemap::{NodeMap, NodeSet};
27 use syntax::ast_util::{is_local, def_id_of_def, local_def};
29 use syntax::codemap::Span;
30 use syntax::parse::token;
31 use syntax::owned_slice::OwnedSlice;
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 = NodeSet;
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 = NodeSet;
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: NodeMap<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 // The parent is considered the enclosing enum because the
71 // enum will dictate the privacy visibility of this variant
73 self.parents.insert(variant.node.id, item.id);
77 // Trait methods are always considered "public", but if the trait is
78 // private then we need some private item in the chain from the
79 // method to the root. In this case, if the trait is private, then
80 // parent all the methods to the trait to indicate that they're
82 ast::ItemTrait(_, _, ref methods) if item.vis != ast::Public => {
83 for m in methods.iter() {
85 ast::Provided(ref m) => self.parents.insert(m.id, item.id),
86 ast::Required(ref m) => self.parents.insert(m.id, item.id),
93 visit::walk_item(self, item, ());
94 self.curparent = prev;
97 fn visit_foreign_item(&mut self, a: &ast::ForeignItem, _: ()) {
98 self.parents.insert(a.id, self.curparent);
99 visit::walk_foreign_item(self, a, ());
102 fn visit_fn(&mut self, a: &visit::FnKind, b: &ast::FnDecl,
103 c: &ast::Block, d: Span, id: ast::NodeId, _: ()) {
104 // We already took care of some trait methods above, otherwise things
105 // like impl methods and pub trait methods are parented to the
106 // containing module, not the containing trait.
107 if !self.parents.contains_key(&id) {
108 self.parents.insert(id, self.curparent);
110 visit::walk_fn(self, a, b, c, d, id, ());
113 fn visit_struct_def(&mut self, s: &ast::StructDef, i: ast::Ident,
114 g: &ast::Generics, n: ast::NodeId, _: ()) {
115 // Struct constructors are parented to their struct definitions because
116 // they essentially are the struct definitions.
118 Some(id) => { self.parents.insert(id, n); }
122 // While we have the id of the struct definition, go ahead and parent
124 for field in s.fields.iter() {
125 self.parents.insert(field.node.id, self.curparent);
127 visit::walk_struct_def(self, s, i, g, n, ())
131 ////////////////////////////////////////////////////////////////////////////////
132 /// The embargo visitor, used to determine the exports of the ast
133 ////////////////////////////////////////////////////////////////////////////////
135 struct EmbargoVisitor<'a> {
137 exp_map2: &'a resolve::ExportMap2,
139 // This flag is an indicator of whether the previous item in the
140 // hierarchical chain was exported or not. This is the indicator of whether
141 // children should be exported as well. Note that this can flip from false
142 // to true if a reexported module is entered (or an action similar).
145 // This is a list of all exported items in the AST. An exported item is any
146 // function/method/item which is usable by external crates. This essentially
147 // means that the result is "public all the way down", but the "path down"
148 // may jump across private boundaries through reexport statements.
149 exported_items: ExportedItems,
151 // This sets contains all the destination nodes which are publicly
152 // re-exported. This is *not* a set of all reexported nodes, only a set of
153 // all nodes which are reexported *and* reachable from external crates. This
154 // means that the destination of the reexport is exported, and hence the
155 // destination must also be exported.
158 // These two fields are closely related to one another in that they are only
159 // used for generation of the 'PublicItems' set, not for privacy checking at
161 public_items: PublicItems,
165 impl<'a> EmbargoVisitor<'a> {
166 // There are checks inside of privacy which depend on knowing whether a
167 // trait should be exported or not. The two current consumers of this are:
169 // 1. Should default methods of a trait be exported?
170 // 2. Should the methods of an implementation of a trait be exported?
172 // The answer to both of these questions partly rely on whether the trait
173 // itself is exported or not. If the trait is somehow exported, then the
174 // answers to both questions must be yes. Right now this question involves
175 // more analysis than is currently done in rustc, so we conservatively
176 // answer "yes" so that all traits need to be exported.
177 fn exported_trait(&self, _id: ast::NodeId) -> bool {
182 impl<'a> Visitor<()> for EmbargoVisitor<'a> {
183 fn visit_item(&mut self, item: &ast::Item, _: ()) {
184 let orig_all_pub = self.prev_public;
185 self.prev_public = orig_all_pub && item.vis == ast::Public;
186 if self.prev_public {
187 self.public_items.insert(item.id);
190 let orig_all_exported = self.prev_exported;
192 // impls/extern blocks do not break the "public chain" because they
193 // cannot have visibility qualifiers on them anyway
194 ast::ItemImpl(..) | ast::ItemForeignMod(..) => {}
196 // Traits are a little special in that even if they themselves are
197 // not public they may still be exported.
198 ast::ItemTrait(..) => {
199 self.prev_exported = self.exported_trait(item.id);
202 // Private by default, hence we only retain the "public chain" if
203 // `pub` is explicitly listed.
206 (orig_all_exported && item.vis == ast::Public) ||
207 self.reexports.contains(&item.id);
211 let public_first = self.prev_exported &&
212 self.exported_items.insert(item.id);
215 // Enum variants inherit from their parent, so if the enum is
216 // public all variants are public unless they're explicitly priv
217 ast::ItemEnum(ref def, _) if public_first => {
218 for variant in def.variants.iter() {
219 self.exported_items.insert(variant.node.id);
223 // Implementations are a little tricky to determine what's exported
224 // out of them. Here's a few cases which are currently defined:
226 // * Impls for private types do not need to export their methods
227 // (either public or private methods)
229 // * Impls for public types only have public methods exported
231 // * Public trait impls for public types must have all methods
234 // * Private trait impls for public types can be ignored
236 // * Public trait impls for private types have their methods
237 // exported. I'm not entirely certain that this is the correct
238 // thing to do, but I have seen use cases of where this will cause
239 // undefined symbols at linkage time if this case is not handled.
241 // * Private trait impls for private types can be completely ignored
242 ast::ItemImpl(_, _, ref ty, ref methods) => {
243 let public_ty = match ty.node {
244 ast::TyPath(_, _, id) => {
245 match self.tcx.def_map.borrow().get_copy(&id) {
246 ast::DefPrimTy(..) => true,
248 let did = def_id_of_def(def);
250 self.exported_items.contains(&did.node)
256 let tr = ty::impl_trait_ref(self.tcx, local_def(item.id));
257 let public_trait = tr.map_or(false, |tr| {
258 !is_local(tr.def_id) ||
259 self.exported_items.contains(&tr.def_id.node)
262 if public_ty || public_trait {
263 for method in methods.iter() {
264 let meth_public = match method.explicit_self.node {
265 ast::SelfStatic => public_ty,
267 } && method.vis == ast::Public;
268 if meth_public || tr.is_some() {
269 self.exported_items.insert(method.id);
275 // Default methods on traits are all public so long as the trait
277 ast::ItemTrait(_, _, ref methods) if public_first => {
278 for method in methods.iter() {
280 ast::Provided(ref m) => {
281 debug!("provided {}", m.id);
282 self.exported_items.insert(m.id);
284 ast::Required(ref m) => {
285 debug!("required {}", m.id);
286 self.exported_items.insert(m.id);
292 // Struct constructors are public if the struct is all public.
293 ast::ItemStruct(ref def, _) if public_first => {
295 Some(id) => { self.exported_items.insert(id); }
303 visit::walk_item(self, item, ());
305 self.prev_exported = orig_all_exported;
306 self.prev_public = orig_all_pub;
309 fn visit_foreign_item(&mut self, a: &ast::ForeignItem, _: ()) {
310 if self.prev_exported && a.vis == ast::Public {
311 self.exported_items.insert(a.id);
315 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId, _: ()) {
316 // This code is here instead of in visit_item so that the
317 // crate module gets processed as well.
318 if self.prev_exported {
319 let exp_map2 = self.exp_map2.borrow();
320 assert!(exp_map2.contains_key(&id), "wut {:?}", id);
321 for export in exp_map2.get(&id).iter() {
322 if is_local(export.def_id) {
323 self.reexports.insert(export.def_id.node);
327 visit::walk_mod(self, m, ())
331 ////////////////////////////////////////////////////////////////////////////////
332 /// The privacy visitor, where privacy checks take place (violations reported)
333 ////////////////////////////////////////////////////////////////////////////////
335 struct PrivacyVisitor<'a> {
337 curitem: ast::NodeId,
340 method_map: &'a MethodMap,
341 parents: NodeMap<ast::NodeId>,
342 external_exports: resolve::ExternalExports,
343 last_private_map: resolve::LastPrivateMap,
349 DisallowedBy(ast::NodeId),
353 UnnamedField(uint), // index
354 // FIXME #6993: change type (and name) from Ident to Name
355 NamedField(ast::Ident),
358 impl<'a> PrivacyVisitor<'a> {
359 // used when debugging
360 fn nodestr(&self, id: ast::NodeId) -> ~str {
361 self.tcx.map.node_to_str(id)
364 // Determines whether the given definition is public from the point of view
365 // of the current item.
366 fn def_privacy(&self, did: ast::DefId) -> PrivacyResult {
368 if self.external_exports.contains(&did) {
369 debug!("privacy - {:?} was externally exported", did);
372 debug!("privacy - is {:?} a public method", did);
374 return match self.tcx.methods.borrow().find(&did) {
376 debug!("privacy - well at least it's a method: {:?}", meth);
377 match meth.container {
378 ty::TraitContainer(id) => {
379 debug!("privacy - recursing on trait {:?}", id);
382 ty::ImplContainer(id) => {
383 match ty::impl_trait_ref(self.tcx, id) {
385 debug!("privacy - impl of trait {:?}", id);
386 self.def_privacy(t.def_id)
389 debug!("privacy - found a method {:?}",
391 if meth.vis == ast::Public {
402 debug!("privacy - nope, not even a method");
408 debug!("privacy - local {:?} not public all the way down", did);
409 // return quickly for things in the same module
410 if self.parents.find(&did.node) == self.parents.find(&self.curitem) {
411 debug!("privacy - same parent, we're done here");
415 // We now know that there is at least one private member between the
416 // destination and the root.
417 let mut closest_private_id = did.node;
419 debug!("privacy - examining {}", self.nodestr(closest_private_id));
420 let vis = match self.tcx.map.find(closest_private_id) {
421 // If this item is a method, then we know for sure that it's an
422 // actual method and not a static method. The reason for this is
423 // that these cases are only hit in the ExprMethodCall
424 // expression, and ExprCall will have its path checked later
425 // (the path of the trait/impl) if it's a static method.
427 // With this information, then we can completely ignore all
428 // trait methods. The privacy violation would be if the trait
429 // couldn't get imported, not if the method couldn't be used
430 // (all trait methods are public).
432 // However, if this is an impl method, then we dictate this
433 // decision solely based on the privacy of the method
435 // FIXME(#10573) is this the right behavior? Why not consider
436 // where the method was defined?
437 Some(ast_map::NodeMethod(ref m)) => {
438 let imp = self.tcx.map.get_parent_did(closest_private_id);
439 match ty::impl_trait_ref(self.tcx, imp) {
440 Some(..) => return Allowable,
441 _ if m.vis == ast::Public => return Allowable,
445 Some(ast_map::NodeTraitMethod(_)) => {
449 // This is not a method call, extract the visibility as one
450 // would normally look at it
451 Some(ast_map::NodeItem(it)) => it.vis,
452 Some(ast_map::NodeForeignItem(_)) => {
453 self.tcx.map.get_foreign_vis(closest_private_id)
455 Some(ast_map::NodeVariant(..)) => {
456 ast::Public // need to move up a level (to the enum)
460 if vis != ast::Public { break }
461 // if we've reached the root, then everything was allowable and this
463 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
464 closest_private_id = *self.parents.get(&closest_private_id);
466 // If we reached the top, then we were public all the way down and
467 // we can allow this access.
468 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
470 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
471 if self.private_accessible(closest_private_id) {
474 DisallowedBy(closest_private_id)
478 /// For a local private node in the AST, this function will determine
479 /// whether the node is accessible by the current module that iteration is
481 fn private_accessible(&self, id: ast::NodeId) -> bool {
482 let parent = *self.parents.get(&id);
483 debug!("privacy - accessible parent {}", self.nodestr(parent));
485 // After finding `did`'s closest private member, we roll ourselves back
486 // to see if this private member's parent is anywhere in our ancestry.
487 // By the privacy rules, we can access all of our ancestor's private
488 // members, so that's why we test the parent, and not the did itself.
489 let mut cur = self.curitem;
491 debug!("privacy - questioning {}", self.nodestr(cur));
493 // If the relevant parent is in our history, then we're allowed
494 // to look inside any of our ancestor's immediate private items,
495 // so this access is valid.
496 x if x == parent => return true,
498 // If we've reached the root, then we couldn't access this item
499 // in the first place
500 ast::DUMMY_NODE_ID => return false,
506 cur = *self.parents.get(&cur);
510 fn report_error(&self, result: CheckResult) -> bool {
513 Some((span, msg, note)) => {
514 self.tcx.sess.span_err(span, msg);
516 Some((span, msg)) => self.tcx.sess.span_note(span, msg),
524 /// Guarantee that a particular definition is public. Returns a CheckResult
525 /// which contains any errors found. These can be reported using `report_error`.
526 /// If the result is `None`, no errors were found.
527 fn ensure_public(&self, span: Span, to_check: ast::DefId,
528 source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
529 match self.def_privacy(to_check) {
530 ExternallyDenied => Some((span, format!("{} is private", msg), None)),
531 DisallowedBy(id) => {
532 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
533 return Some((span, format!("{} is private", msg), None));
535 (span, format!("{} is inaccessible", msg))
537 match self.tcx.map.find(id) {
538 Some(ast_map::NodeItem(item)) => {
539 let desc = match item.node {
540 ast::ItemMod(..) => "module",
541 ast::ItemTrait(..) => "trait",
542 _ => return Some((err_span, err_msg, None)),
544 let msg = format!("{} `{}` is private",
546 token::get_ident(item.ident));
547 Some((err_span, err_msg, Some((span, msg))))
549 _ => Some((err_span, err_msg, None)),
556 // Checks that a field is in scope.
557 fn check_field(&mut self, span: Span, id: ast::DefId,
559 let fields = ty::lookup_struct_fields(self.tcx, id);
560 let field = match name {
561 NamedField(ident) => {
562 fields.iter().find(|f| f.name == ident.name).unwrap()
564 UnnamedField(idx) => fields.get(idx)
566 if field.vis == ast::Public ||
567 (is_local(field.id) && self.private_accessible(field.id.node)) {
571 let struct_type = ty::lookup_item_type(self.tcx, id).ty;
572 let struct_desc = match ty::get(struct_type).sty {
573 ty::ty_struct(_, _) => format!("struct `{}`", ty::item_path_str(self.tcx, id)),
574 ty::ty_bare_fn(ty::BareFnTy { sig: ty::FnSig { output, .. }, .. }) => {
575 // Struct `id` is really a struct variant of an enum,
576 // and we're really looking at the variant's constructor
577 // function. So get the return type for a detailed error
579 let enum_id = match ty::get(output).sty {
580 ty::ty_enum(id, _) => id,
581 _ => self.tcx.sess.span_bug(span, "enum variant doesn't \
584 format!("variant `{}` of enum `{}`",
585 ty::with_path(self.tcx, id, |mut p| p.last().unwrap()),
586 ty::item_path_str(self.tcx, enum_id))
588 _ => self.tcx.sess.span_bug(span, "can't find struct for field")
590 let msg = match name {
591 NamedField(name) => format!("field `{}` of {} is private",
592 token::get_ident(name), struct_desc),
593 UnnamedField(idx) => format!("field \\#{} of {} is private",
594 idx + 1, struct_desc),
596 self.tcx.sess.span_err(span, msg);
599 // Given the ID of a method, checks to ensure it's in scope.
600 fn check_static_method(&mut self, span: Span, method_id: ast::DefId,
602 // If the method is a default method, we need to use the def_id of
603 // the default implementation.
604 let method_id = ty::method(self.tcx, method_id).provided_source
605 .unwrap_or(method_id);
607 let string = token::get_ident(name);
608 self.report_error(self.ensure_public(span,
611 format!("method `{}`", string)));
614 // Checks that a path is in scope.
615 fn check_path(&mut self, span: Span, path_id: ast::NodeId, path: &ast::Path) {
616 debug!("privacy - path {}", self.nodestr(path_id));
617 let orig_def = self.tcx.def_map.borrow().get_copy(&path_id);
618 let ck = |tyname: &str| {
619 let ck_public = |def: ast::DefId| {
620 let name = token::get_ident(path.segments
624 let origdid = def_id_of_def(orig_def);
625 self.ensure_public(span,
633 match *self.last_private_map.get(&path_id) {
634 resolve::LastMod(resolve::AllPublic) => {},
635 resolve::LastMod(resolve::DependsOn(def)) => {
636 self.report_error(ck_public(def));
638 resolve::LastImport{value_priv: value_priv,
639 value_used: check_value,
640 type_priv: type_priv,
641 type_used: check_type} => {
642 // This dance with found_error is because we don't want to report
643 // a privacy error twice for the same directive.
644 let found_error = match (type_priv, check_type) {
645 (Some(resolve::DependsOn(def)), resolve::Used) => {
646 !self.report_error(ck_public(def))
651 match (value_priv, check_value) {
652 (Some(resolve::DependsOn(def)), resolve::Used) => {
653 self.report_error(ck_public(def));
658 // If an import is not used in either namespace, we still
659 // want to check that it could be legal. Therefore we check
660 // in both namespaces and only report an error if both would
661 // be illegal. We only report one error, even if it is
662 // illegal to import from both namespaces.
663 match (value_priv, check_value, type_priv, check_type) {
664 (Some(p), resolve::Unused, None, _) |
665 (None, _, Some(p), resolve::Unused) => {
667 resolve::AllPublic => None,
668 resolve::DependsOn(def) => ck_public(def),
671 self.report_error(p);
674 (Some(v), resolve::Unused, Some(t), resolve::Unused) => {
676 resolve::AllPublic => None,
677 resolve::DependsOn(def) => ck_public(def),
680 resolve::AllPublic => None,
681 resolve::DependsOn(def) => ck_public(def),
684 (Some(_), Some(t)) => {
685 self.report_error(Some(t));
695 // FIXME(#12334) Imports can refer to definitions in both the type and
696 // value namespaces. The privacy information is aware of this, but the
697 // def map is not. Therefore the names we work out below will not always
698 // be accurate and we can get slightly wonky error messages (but type
699 // checking is always correct).
700 match self.tcx.def_map.borrow().get_copy(&path_id) {
701 ast::DefStaticMethod(..) => ck("static method"),
702 ast::DefFn(..) => ck("function"),
703 ast::DefStatic(..) => ck("static"),
704 ast::DefVariant(..) => ck("variant"),
705 ast::DefTy(..) => ck("type"),
706 ast::DefTrait(..) => ck("trait"),
707 ast::DefStruct(..) => ck("struct"),
708 ast::DefMethod(_, Some(..)) => ck("trait method"),
709 ast::DefMethod(..) => ck("method"),
710 ast::DefMod(..) => ck("module"),
715 // Checks that a method is in scope.
716 fn check_method(&mut self, span: Span, origin: MethodOrigin,
719 MethodStatic(method_id) => {
720 self.check_static_method(span, method_id, ident)
722 // Trait methods are always all public. The only controlling factor
723 // is whether the trait itself is accessible or not.
724 MethodParam(MethodParam { trait_id: trait_id, .. }) |
725 MethodObject(MethodObject { trait_id: trait_id, .. }) => {
726 self.report_error(self.ensure_public(span, trait_id, None,
733 impl<'a> Visitor<()> for PrivacyVisitor<'a> {
734 fn visit_item(&mut self, item: &ast::Item, _: ()) {
735 // Do not check privacy inside items with the resolve_unexported
736 // attribute. This is used for the test runner.
737 if attr::contains_name(item.attrs.as_slice(), "!resolve_unexported") {
741 let orig_curitem = replace(&mut self.curitem, item.id);
742 visit::walk_item(self, item, ());
743 self.curitem = orig_curitem;
746 fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
748 ast::ExprField(base, ident, _) => {
749 match ty::get(ty::expr_ty_adjusted(self.tcx, base,
750 &*self.method_map.borrow())).sty {
751 ty::ty_struct(id, _) => {
752 self.check_field(expr.span, id, NamedField(ident));
757 ast::ExprMethodCall(ident, _, _) => {
758 let method_call = MethodCall::expr(expr.id);
759 match self.method_map.borrow().find(&method_call) {
761 self.tcx.sess.span_bug(expr.span,
762 "method call not in \
766 debug!("(privacy checking) checking impl method");
767 self.check_method(expr.span, method.origin, ident);
771 ast::ExprStruct(_, ref fields, _) => {
772 match ty::get(ty::expr_ty(self.tcx, expr)).sty {
773 ty::ty_struct(id, _) => {
774 for field in (*fields).iter() {
775 self.check_field(expr.span, id,
776 NamedField(field.ident.node));
779 ty::ty_enum(_, _) => {
780 match self.tcx.def_map.borrow().get_copy(&expr.id) {
781 ast::DefVariant(_, variant_id, _) => {
782 for field in fields.iter() {
783 self.check_field(expr.span, variant_id,
784 NamedField(field.ident.node));
787 _ => self.tcx.sess.span_bug(expr.span,
794 _ => self.tcx.sess.span_bug(expr.span, "struct expr \
799 ast::ExprPath(..) => {
800 let guard = |did: ast::DefId| {
801 let fields = ty::lookup_struct_fields(self.tcx, did);
802 let any_priv = fields.iter().any(|f| {
803 f.vis != ast::Public && (
805 !self.private_accessible(f.id.node))
808 self.tcx.sess.span_err(expr.span,
809 "cannot invoke tuple struct constructor \
810 with private fields");
813 match self.tcx.def_map.borrow().find(&expr.id) {
814 Some(&ast::DefStruct(did)) => {
815 guard(if is_local(did) {
816 local_def(self.tcx.map.get_parent(did.node))
818 // "tuple structs" with zero fields (such as
819 // `pub struct Foo;`) don't have a ctor_id, hence
820 // the unwrap_or to the same struct id.
822 csearch::get_tuple_struct_definition_if_ctor(
823 &self.tcx.sess.cstore, did);
824 maybe_did.unwrap_or(did)
827 // Tuple struct constructors across crates are identified as
828 // DefFn types, so we explicitly handle that case here.
829 Some(&ast::DefFn(did, _)) if !is_local(did) => {
830 match csearch::get_tuple_struct_definition_if_ctor(
831 &self.tcx.sess.cstore, did) {
832 Some(did) => guard(did),
842 visit::walk_expr(self, expr, ());
845 fn visit_view_item(&mut self, a: &ast::ViewItem, _: ()) {
847 ast::ViewItemExternCrate(..) => {}
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: Vec::new(),
858 types: OwnedSlice::empty(),
860 let segs = vec!(seg);
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,
889 NamedField(field.ident));
892 ty::ty_enum(_, _) => {
893 match self.tcx.def_map.borrow().find(&pattern.id) {
894 Some(&ast::DefVariant(_, variant_id, _)) => {
895 for field in fields.iter() {
896 self.check_field(pattern.span, variant_id,
897 NamedField(field.ident));
900 _ => self.tcx.sess.span_bug(pattern.span,
907 _ => self.tcx.sess.span_bug(pattern.span,
908 "struct pattern didn't have \
913 // Patterns which bind no fields are allowable (the path is check
915 ast::PatEnum(_, Some(ref fields)) => {
916 match ty::get(ty::pat_ty(self.tcx, pattern)).sty {
917 ty::ty_struct(id, _) => {
918 for (i, field) in fields.iter().enumerate() {
920 ast::PatWild(..) => continue,
923 self.check_field(field.span, id, UnnamedField(i));
927 // enum fields have no privacy at this time
936 visit::walk_pat(self, pattern, ());
939 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) {
940 self.in_foreign = true;
941 visit::walk_foreign_item(self, fi, ());
942 self.in_foreign = false;
945 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, _: ()) {
946 self.check_path(path.span, id, path);
947 visit::walk_path(self, path, ());
951 ////////////////////////////////////////////////////////////////////////////////
952 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
953 ////////////////////////////////////////////////////////////////////////////////
955 struct SanePrivacyVisitor<'a> {
960 impl<'a> Visitor<()> for SanePrivacyVisitor<'a> {
961 fn visit_item(&mut self, item: &ast::Item, _: ()) {
963 self.check_all_inherited(item);
965 self.check_sane_privacy(item);
968 let orig_in_fn = replace(&mut self.in_fn, match item.node {
969 ast::ItemMod(..) => false, // modules turn privacy back on
970 _ => self.in_fn, // otherwise we inherit
972 visit::walk_item(self, item, ());
973 self.in_fn = orig_in_fn;
976 fn visit_fn(&mut self, fk: &visit::FnKind, fd: &ast::FnDecl,
977 b: &ast::Block, s: Span, n: ast::NodeId, _: ()) {
978 // This catches both functions and methods
979 let orig_in_fn = replace(&mut self.in_fn, true);
980 visit::walk_fn(self, fk, fd, b, s, n, ());
981 self.in_fn = orig_in_fn;
984 fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
989 self.tcx.sess.span_err(i.span, "unnecessary `pub`, imports \
990 in functions are never \
994 ast::ViewItemExternCrate(..) => {
995 self.tcx.sess.span_err(i.span, "`pub` visibility \
1003 visit::walk_view_item(self, i, ());
1007 impl<'a> SanePrivacyVisitor<'a> {
1008 /// Validates all of the visibility qualifers placed on the item given. This
1009 /// ensures that there are no extraneous qualifiers that don't actually do
1010 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1011 /// later on down the road...
1012 fn check_sane_privacy(&self, item: &ast::Item) {
1014 let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
1015 if vis != ast::Inherited {
1016 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1018 tcx.sess.span_note(sp, note);
1023 // implementations of traits don't need visibility qualifiers because
1024 // that's controlled by having the trait in scope.
1025 ast::ItemImpl(_, Some(..), _, ref methods) => {
1026 check_inherited(item.span, item.vis,
1027 "visibility qualifiers have no effect on trait \
1029 for m in methods.iter() {
1030 check_inherited(m.span, m.vis, "");
1034 ast::ItemImpl(..) => {
1035 check_inherited(item.span, item.vis,
1036 "place qualifiers on individual methods instead");
1038 ast::ItemForeignMod(..) => {
1039 check_inherited(item.span, item.vis,
1040 "place qualifiers on individual functions \
1044 ast::ItemEnum(ref def, _) => {
1045 for v in def.variants.iter() {
1048 if item.vis == ast::Public {
1049 tcx.sess.span_err(v.span, "unnecessary `pub` \
1053 ast::Inherited => {}
1058 ast::ItemTrait(_, _, ref methods) => {
1059 for m in methods.iter() {
1061 ast::Provided(ref m) => {
1062 check_inherited(m.span, m.vis,
1063 "unnecessary visibility");
1065 ast::Required(..) => {}
1070 ast::ItemStatic(..) | ast::ItemStruct(..) |
1071 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1072 ast::ItemMac(..) => {}
1076 /// When inside of something like a function or a method, visibility has no
1077 /// control over anything so this forbids any mention of any visibility
1078 fn check_all_inherited(&self, item: &ast::Item) {
1080 let check_inherited = |sp: Span, vis: ast::Visibility| {
1081 if vis != ast::Inherited {
1082 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1085 let check_struct = |def: &@ast::StructDef| {
1086 for f in def.fields.iter() {
1088 ast::NamedField(_, p) => check_inherited(f.span, p),
1089 ast::UnnamedField(..) => {}
1093 check_inherited(item.span, item.vis);
1095 ast::ItemImpl(_, _, _, ref methods) => {
1096 for m in methods.iter() {
1097 check_inherited(m.span, m.vis);
1100 ast::ItemForeignMod(ref fm) => {
1101 for i in fm.items.iter() {
1102 check_inherited(i.span, i.vis);
1105 ast::ItemEnum(ref def, _) => {
1106 for v in def.variants.iter() {
1107 check_inherited(v.span, v.node.vis);
1110 ast::StructVariantKind(ref s) => check_struct(s),
1111 ast::TupleVariantKind(..) => {}
1116 ast::ItemStruct(ref def, _) => check_struct(def),
1118 ast::ItemTrait(_, _, ref methods) => {
1119 for m in methods.iter() {
1121 ast::Required(..) => {}
1122 ast::Provided(ref m) => check_inherited(m.span, m.vis),
1127 ast::ItemStatic(..) |
1128 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1129 ast::ItemMac(..) => {}
1134 struct VisiblePrivateTypesVisitor<'a> {
1136 exported_items: &'a ExportedItems,
1137 public_items: &'a PublicItems,
1140 struct CheckTypeForPrivatenessVisitor<'a, 'b> {
1141 inner: &'b VisiblePrivateTypesVisitor<'a>,
1142 /// whether the type refers to private types.
1143 contains_private: bool,
1144 /// whether we've recurred at all (i.e. if we're pointing at the
1145 /// first type on which visit_ty was called).
1146 at_outer_type: bool,
1147 // whether that first type is a public path.
1148 outer_type_is_public_path: bool,
1151 impl<'a> VisiblePrivateTypesVisitor<'a> {
1152 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1153 let did = match self.tcx.def_map.borrow().find_copy(&path_id) {
1154 // `int` etc. (None doesn't seem to occur.)
1155 None | Some(ast::DefPrimTy(..)) => return false,
1156 Some(def) => def_id_of_def(def)
1158 // A path can only be private if:
1159 // it's in this crate...
1161 // ... it's not exported (obviously) ...
1162 !self.exported_items.contains(&did.node) &&
1163 // .. and it corresponds to a type in the AST (this returns None for
1165 self.tcx.map.find(did.node).is_some()
1168 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1169 // FIXME: this would preferably be using `exported_items`, but all
1170 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1171 self.public_items.contains(&trait_id)
1175 impl<'a, 'b> Visitor<()> for CheckTypeForPrivatenessVisitor<'a, 'b> {
1176 fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
1178 ast::TyPath(_, _, path_id) => {
1179 if self.inner.path_is_private_type(path_id) {
1180 self.contains_private = true;
1181 // found what we're looking for so let's stop
1184 } else if self.at_outer_type {
1185 self.outer_type_is_public_path = true;
1190 self.at_outer_type = false;
1191 visit::walk_ty(self, ty, ())
1194 // don't want to recurse into [, .. expr]
1195 fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
1198 impl<'a> Visitor<()> for VisiblePrivateTypesVisitor<'a> {
1199 fn visit_item(&mut self, item: &ast::Item, _: ()) {
1201 // contents of a private mod can be reexported, so we need
1202 // to check internals.
1203 ast::ItemMod(_) => {}
1205 // An `extern {}` doesn't introduce a new privacy
1206 // namespace (the contents have their own privacies).
1207 ast::ItemForeignMod(_) => {}
1209 ast::ItemTrait(..) if !self.trait_is_public(item.id) => return,
1211 // impls need some special handling to try to offer useful
1212 // error messages without (too many) false positives
1213 // (i.e. we could just return here to not check them at
1214 // all, or some worse estimation of whether an impl is
1215 // publically visible.
1216 ast::ItemImpl(ref g, ref trait_ref, self_, ref methods) => {
1217 // `impl [... for] Private` is never visible.
1218 let self_contains_private;
1219 // impl [... for] Public<...>, but not `impl [... for]
1220 // ~[Public]` or `(Public,)` etc.
1221 let self_is_public_path;
1223 // check the properties of the Self type:
1225 let mut visitor = CheckTypeForPrivatenessVisitor {
1227 contains_private: false,
1228 at_outer_type: true,
1229 outer_type_is_public_path: false,
1231 visitor.visit_ty(self_, ());
1232 self_contains_private = visitor.contains_private;
1233 self_is_public_path = visitor.outer_type_is_public_path;
1236 // miscellanous info about the impl
1238 // `true` iff this is `impl Private for ...`.
1239 let not_private_trait =
1240 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1242 let did = ty::trait_ref_to_def_id(self.tcx, tr);
1244 !is_local(did) || self.trait_is_public(did.node)
1247 // `true` iff this is a trait impl or at least one method is public.
1249 // `impl Public { $( fn ...() {} )* }` is not visible.
1251 // This is required over just using the methods' privacy
1252 // directly because we might have `impl<T: Foo<Private>> ...`,
1253 // and we shouldn't warn about the generics if all the methods
1254 // are private (because `T` won't be visible externally).
1255 let trait_or_some_public_method =
1256 trait_ref.is_some() ||
1257 methods.iter().any(|m| self.exported_items.contains(&m.id));
1259 if !self_contains_private &&
1260 not_private_trait &&
1261 trait_or_some_public_method {
1263 visit::walk_generics(self, g, ());
1267 for method in methods.iter() {
1268 visit::walk_method_helper(self, *method, ())
1272 // Any private types in a trait impl fall into two
1274 // 1. mentioned in the trait definition
1275 // 2. mentioned in the type params/generics
1277 // Those in 1. can only occur if the trait is in
1278 // this crate and will've been warned about on the
1279 // trait definition (there's no need to warn twice
1280 // so we don't check the methods).
1282 // Those in 2. are warned via walk_generics and this
1284 visit::walk_trait_ref_helper(self, tr, ())
1287 } else if trait_ref.is_none() && self_is_public_path {
1288 // impl Public<Private> { ... }. Any public static
1289 // methods will be visible as `Public::foo`.
1290 let mut found_pub_static = false;
1291 for method in methods.iter() {
1292 if method.explicit_self.node == ast::SelfStatic &&
1293 self.exported_items.contains(&method.id) {
1294 found_pub_static = true;
1295 visit::walk_method_helper(self, *method, ());
1298 if found_pub_static {
1299 visit::walk_generics(self, g, ())
1305 // `type ... = ...;` can contain private types, because
1306 // we're introducing a new name.
1307 ast::ItemTy(..) => return,
1309 // not at all public, so we don't care
1310 _ if !self.exported_items.contains(&item.id) => return,
1315 // we've carefully constructed it so that if we're here, then
1316 // any `visit_ty`'s will be called on things that are in
1317 // public signatures, i.e. things that we're interested in for
1319 visit::walk_item(self, item, ());
1322 fn visit_foreign_item(&mut self, item: &ast::ForeignItem, _: ()) {
1323 if self.exported_items.contains(&item.id) {
1324 visit::walk_foreign_item(self, item, ())
1328 fn visit_fn(&mut self,
1329 fk: &visit::FnKind, fd: &ast::FnDecl, b: &ast::Block, s: Span, id: ast::NodeId,
1331 // needs special handling for methods.
1332 if self.exported_items.contains(&id) {
1333 visit::walk_fn(self, fk, fd, b, s, id, ());
1337 fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
1339 ast::TyPath(ref p, _, path_id) => {
1340 if self.path_is_private_type(path_id) {
1341 self.tcx.sess.add_lint(lint::VisiblePrivateTypes,
1343 ~"private type in exported type signature");
1348 visit::walk_ty(self, t, ())
1351 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
1352 if self.exported_items.contains(&v.node.id) {
1353 visit::walk_variant(self, v, g, ());
1357 fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
1359 ast::NamedField(_, ast::Public) => {
1360 visit::walk_struct_field(self, s, ());
1367 // we don't need to introspect into these at all: an
1368 // expression/block context can't possibly contain exported
1369 // things, and neither do view_items. (Making them no-ops stops us
1370 // from traversing the whole AST without having to be super
1371 // careful about our `walk_...` calls above.)
1372 fn visit_view_item(&mut self, _: &ast::ViewItem, _: ()) {}
1373 fn visit_block(&mut self, _: &ast::Block, _: ()) {}
1374 fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
1377 pub fn check_crate(tcx: &ty::ctxt,
1378 method_map: &MethodMap,
1379 exp_map2: &resolve::ExportMap2,
1380 external_exports: resolve::ExternalExports,
1381 last_private_map: resolve::LastPrivateMap,
1382 krate: &ast::Crate) -> (ExportedItems, PublicItems) {
1383 // Figure out who everyone's parent is
1384 let mut visitor = ParentVisitor {
1385 parents: NodeMap::new(),
1386 curparent: ast::DUMMY_NODE_ID,
1388 visit::walk_crate(&mut visitor, krate, ());
1390 // Use the parent map to check the privacy of everything
1391 let mut visitor = PrivacyVisitor {
1392 curitem: ast::DUMMY_NODE_ID,
1396 parents: visitor.parents,
1397 method_map: method_map,
1398 external_exports: external_exports,
1399 last_private_map: last_private_map,
1401 visit::walk_crate(&mut visitor, krate, ());
1403 // Sanity check to make sure that all privacy usage and controls are
1405 let mut visitor = SanePrivacyVisitor {
1409 visit::walk_crate(&mut visitor, krate, ());
1411 tcx.sess.abort_if_errors();
1413 // Build up a set of all exported items in the AST. This is a set of all
1414 // items which are reachable from external crates based on visibility.
1415 let mut visitor = EmbargoVisitor {
1417 exported_items: NodeSet::new(),
1418 public_items: NodeSet::new(),
1419 reexports: NodeSet::new(),
1421 prev_exported: true,
1425 let before = visitor.exported_items.len();
1426 visit::walk_crate(&mut visitor, krate, ());
1427 if before == visitor.exported_items.len() {
1432 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1435 let mut visitor = VisiblePrivateTypesVisitor {
1437 exported_items: &exported_items,
1438 public_items: &public_items
1440 visit::walk_crate(&mut visitor, krate, ());
1442 return (exported_items, public_items);