1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![crate_name = "rustc_privacy"]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
17 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
18 html_root_url = "http://doc.rust-lang.org/nightly/")]
20 #![feature(rustc_diagnostic_macros)]
21 #![allow(unknown_features)] #![feature(int_uint)]
24 #[macro_use] extern crate log;
25 #[macro_use] extern crate syntax;
29 use self::PrivacyResult::*;
30 use self::FieldName::*;
32 use std::mem::replace;
34 use rustc::metadata::csearch;
35 use rustc::middle::def;
36 use rustc::middle::privacy::ImportUse::*;
37 use rustc::middle::privacy::LastPrivate::*;
38 use rustc::middle::privacy::PrivateDep::*;
39 use rustc::middle::privacy::{ExportedItems, PublicItems, LastPrivateMap};
40 use rustc::middle::privacy::{ExternalExports};
41 use rustc::middle::ty::{MethodTypeParam, MethodStatic};
42 use rustc::middle::ty::{MethodCall, MethodMap, MethodOrigin, MethodParam};
43 use rustc::middle::ty::{MethodStaticUnboxedClosure, MethodObject};
44 use rustc::middle::ty::{MethodTraitObject};
45 use rustc::middle::ty::{self, Ty};
46 use rustc::util::nodemap::{NodeMap, NodeSet};
48 use syntax::{ast, ast_map};
49 use syntax::ast_util::{is_local, local_def, PostExpansionMethod};
50 use syntax::codemap::Span;
51 use syntax::parse::token;
52 use syntax::visit::{self, Visitor};
54 type Context<'a, 'tcx> = (&'a MethodMap<'tcx>, &'a def::ExportMap);
56 /// Result of a checking operation - None => no errors were found. Some => an
57 /// error and contains the span and message for reporting that error and
58 /// optionally the same for a note about the error.
59 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
61 ////////////////////////////////////////////////////////////////////////////////
62 /// The parent visitor, used to determine what's the parent of what (node-wise)
63 ////////////////////////////////////////////////////////////////////////////////
65 struct ParentVisitor {
66 parents: NodeMap<ast::NodeId>,
67 curparent: ast::NodeId,
70 impl<'v> Visitor<'v> for ParentVisitor {
71 fn visit_item(&mut self, item: &ast::Item) {
72 self.parents.insert(item.id, self.curparent);
74 let prev = self.curparent;
76 ast::ItemMod(..) => { self.curparent = item.id; }
77 // Enum variants are parented to the enum definition itself because
78 // they inherit privacy
79 ast::ItemEnum(ref def, _) => {
80 for variant in def.variants.iter() {
81 // The parent is considered the enclosing enum because the
82 // enum will dictate the privacy visibility of this variant
84 self.parents.insert(variant.node.id, item.id);
88 // Trait methods are always considered "public", but if the trait is
89 // private then we need some private item in the chain from the
90 // method to the root. In this case, if the trait is private, then
91 // parent all the methods to the trait to indicate that they're
93 ast::ItemTrait(_, _, _, ref methods) if item.vis != ast::Public => {
94 for m in methods.iter() {
96 ast::ProvidedMethod(ref m) => {
97 self.parents.insert(m.id, item.id);
99 ast::RequiredMethod(ref m) => {
100 self.parents.insert(m.id, item.id);
102 ast::TypeTraitItem(_) => {}
109 visit::walk_item(self, item);
110 self.curparent = prev;
113 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
114 self.parents.insert(a.id, self.curparent);
115 visit::walk_foreign_item(self, a);
118 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
119 c: &'v ast::Block, d: Span, id: ast::NodeId) {
120 // We already took care of some trait methods above, otherwise things
121 // like impl methods and pub trait methods are parented to the
122 // containing module, not the containing trait.
123 if !self.parents.contains_key(&id) {
124 self.parents.insert(id, self.curparent);
126 visit::walk_fn(self, a, b, c, d);
129 fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
130 _: &'v ast::Generics, n: ast::NodeId) {
131 // Struct constructors are parented to their struct definitions because
132 // they essentially are the struct definitions.
134 Some(id) => { self.parents.insert(id, n); }
138 // While we have the id of the struct definition, go ahead and parent
140 for field in s.fields.iter() {
141 self.parents.insert(field.node.id, self.curparent);
143 visit::walk_struct_def(self, s)
147 ////////////////////////////////////////////////////////////////////////////////
148 /// The embargo visitor, used to determine the exports of the ast
149 ////////////////////////////////////////////////////////////////////////////////
151 struct EmbargoVisitor<'a, 'tcx: 'a> {
152 tcx: &'a ty::ctxt<'tcx>,
153 export_map: &'a def::ExportMap,
155 // This flag is an indicator of whether the previous item in the
156 // hierarchical chain was exported or not. This is the indicator of whether
157 // children should be exported as well. Note that this can flip from false
158 // to true if a reexported module is entered (or an action similar).
161 // This is a list of all exported items in the AST. An exported item is any
162 // function/method/item which is usable by external crates. This essentially
163 // means that the result is "public all the way down", but the "path down"
164 // may jump across private boundaries through reexport statements.
165 exported_items: ExportedItems,
167 // This sets contains all the destination nodes which are publicly
168 // re-exported. This is *not* a set of all reexported nodes, only a set of
169 // all nodes which are reexported *and* reachable from external crates. This
170 // means that the destination of the reexport is exported, and hence the
171 // destination must also be exported.
174 // These two fields are closely related to one another in that they are only
175 // used for generation of the 'PublicItems' set, not for privacy checking at
177 public_items: PublicItems,
181 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
182 // There are checks inside of privacy which depend on knowing whether a
183 // trait should be exported or not. The two current consumers of this are:
185 // 1. Should default methods of a trait be exported?
186 // 2. Should the methods of an implementation of a trait be exported?
188 // The answer to both of these questions partly rely on whether the trait
189 // itself is exported or not. If the trait is somehow exported, then the
190 // answers to both questions must be yes. Right now this question involves
191 // more analysis than is currently done in rustc, so we conservatively
192 // answer "yes" so that all traits need to be exported.
193 fn exported_trait(&self, _id: ast::NodeId) -> bool {
198 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
199 fn visit_item(&mut self, item: &ast::Item) {
200 let orig_all_pub = self.prev_public;
201 self.prev_public = orig_all_pub && item.vis == ast::Public;
202 if self.prev_public {
203 self.public_items.insert(item.id);
206 let orig_all_exported = self.prev_exported;
208 // impls/extern blocks do not break the "public chain" because they
209 // cannot have visibility qualifiers on them anyway
210 ast::ItemImpl(..) | ast::ItemForeignMod(..) => {}
212 // Traits are a little special in that even if they themselves are
213 // not public they may still be exported.
214 ast::ItemTrait(..) => {
215 self.prev_exported = self.exported_trait(item.id);
218 // Private by default, hence we only retain the "public chain" if
219 // `pub` is explicitly listed.
222 (orig_all_exported && item.vis == ast::Public) ||
223 self.reexports.contains(&item.id);
227 let public_first = self.prev_exported &&
228 self.exported_items.insert(item.id);
231 // Enum variants inherit from their parent, so if the enum is
232 // public all variants are public unless they're explicitly priv
233 ast::ItemEnum(ref def, _) if public_first => {
234 for variant in def.variants.iter() {
235 self.exported_items.insert(variant.node.id);
239 // Implementations are a little tricky to determine what's exported
240 // out of them. Here's a few cases which are currently defined:
242 // * Impls for private types do not need to export their methods
243 // (either public or private methods)
245 // * Impls for public types only have public methods exported
247 // * Public trait impls for public types must have all methods
250 // * Private trait impls for public types can be ignored
252 // * Public trait impls for private types have their methods
253 // exported. I'm not entirely certain that this is the correct
254 // thing to do, but I have seen use cases of where this will cause
255 // undefined symbols at linkage time if this case is not handled.
257 // * Private trait impls for private types can be completely ignored
258 ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
259 let public_ty = match ty.node {
260 ast::TyPath(_, id) => {
261 match self.tcx.def_map.borrow()[id].clone() {
262 def::DefPrimTy(..) => true,
264 let did = def.def_id();
266 self.exported_items.contains(&did.node)
272 let tr = ty::impl_trait_ref(self.tcx, local_def(item.id));
273 let public_trait = tr.clone().map_or(false, |tr| {
274 !is_local(tr.def_id) ||
275 self.exported_items.contains(&tr.def_id.node)
278 if public_ty || public_trait {
279 for impl_item in impl_items.iter() {
281 ast::MethodImplItem(ref method) => {
283 match method.pe_explicit_self().node {
284 ast::SelfStatic => public_ty,
286 } && method.pe_vis() == ast::Public;
287 if meth_public || tr.is_some() {
288 self.exported_items.insert(method.id);
291 ast::TypeImplItem(_) => {}
297 // Default methods on traits are all public so long as the trait
299 ast::ItemTrait(_, _, _, ref methods) if public_first => {
300 for method in methods.iter() {
302 ast::ProvidedMethod(ref m) => {
303 debug!("provided {}", m.id);
304 self.exported_items.insert(m.id);
306 ast::RequiredMethod(ref m) => {
307 debug!("required {}", m.id);
308 self.exported_items.insert(m.id);
310 ast::TypeTraitItem(ref t) => {
311 debug!("typedef {}", t.ty_param.id);
312 self.exported_items.insert(t.ty_param.id);
318 // Struct constructors are public if the struct is all public.
319 ast::ItemStruct(ref def, _) if public_first => {
321 Some(id) => { self.exported_items.insert(id); }
326 ast::ItemTy(ref ty, _) if public_first => {
327 if let ast::TyPath(_, id) = ty.node {
328 match self.tcx.def_map.borrow()[id].clone() {
329 def::DefPrimTy(..) | def::DefTyParam(..) => {},
331 let did = def.def_id();
333 self.exported_items.insert(did.node);
343 visit::walk_item(self, item);
345 self.prev_exported = orig_all_exported;
346 self.prev_public = orig_all_pub;
349 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
350 if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) {
351 self.exported_items.insert(a.id);
355 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) {
356 // This code is here instead of in visit_item so that the
357 // crate module gets processed as well.
358 if self.prev_exported {
359 assert!(self.export_map.contains_key(&id), "wut {}", id);
360 for export in self.export_map[id].iter() {
361 if is_local(export.def_id) {
362 self.reexports.insert(export.def_id.node);
366 visit::walk_mod(self, m)
370 ////////////////////////////////////////////////////////////////////////////////
371 /// The privacy visitor, where privacy checks take place (violations reported)
372 ////////////////////////////////////////////////////////////////////////////////
374 struct PrivacyVisitor<'a, 'tcx: 'a> {
375 tcx: &'a ty::ctxt<'tcx>,
376 curitem: ast::NodeId,
378 parents: NodeMap<ast::NodeId>,
379 external_exports: ExternalExports,
380 last_private_map: LastPrivateMap,
386 DisallowedBy(ast::NodeId),
390 UnnamedField(uint), // index
391 // FIXME #6993: change type (and name) from Ident to Name
392 NamedField(ast::Ident),
395 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
396 // used when debugging
397 fn nodestr(&self, id: ast::NodeId) -> String {
398 self.tcx.map.node_to_string(id).to_string()
401 // Determines whether the given definition is public from the point of view
402 // of the current item.
403 fn def_privacy(&self, did: ast::DefId) -> PrivacyResult {
405 if self.external_exports.contains(&did) {
406 debug!("privacy - {:?} was externally exported", did);
409 debug!("privacy - is {:?} a public method", did);
411 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
412 Some(&ty::MethodTraitItem(ref meth)) => {
413 debug!("privacy - well at least it's a method: {:?}",
415 match meth.container {
416 ty::TraitContainer(id) => {
417 debug!("privacy - recursing on trait {:?}", id);
420 ty::ImplContainer(id) => {
421 match ty::impl_trait_ref(self.tcx, id) {
423 debug!("privacy - impl of trait {:?}", id);
424 self.def_privacy(t.def_id)
427 debug!("privacy - found a method {:?}",
429 if meth.vis == ast::Public {
439 Some(&ty::TypeTraitItem(ref typedef)) => {
440 match typedef.container {
441 ty::TraitContainer(id) => {
442 debug!("privacy - recursing on trait {:?}", id);
445 ty::ImplContainer(id) => {
446 match ty::impl_trait_ref(self.tcx, id) {
448 debug!("privacy - impl of trait {:?}", id);
449 self.def_privacy(t.def_id)
452 debug!("privacy - found a typedef {:?}",
454 if typedef.vis == ast::Public {
465 debug!("privacy - nope, not even a method");
471 debug!("privacy - local {} not public all the way down",
472 self.tcx.map.node_to_string(did.node));
473 // return quickly for things in the same module
474 if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
475 debug!("privacy - same parent, we're done here");
479 // We now know that there is at least one private member between the
480 // destination and the root.
481 let mut closest_private_id = did.node;
483 debug!("privacy - examining {}", self.nodestr(closest_private_id));
484 let vis = match self.tcx.map.find(closest_private_id) {
485 // If this item is a method, then we know for sure that it's an
486 // actual method and not a static method. The reason for this is
487 // that these cases are only hit in the ExprMethodCall
488 // expression, and ExprCall will have its path checked later
489 // (the path of the trait/impl) if it's a static method.
491 // With this information, then we can completely ignore all
492 // trait methods. The privacy violation would be if the trait
493 // couldn't get imported, not if the method couldn't be used
494 // (all trait methods are public).
496 // However, if this is an impl method, then we dictate this
497 // decision solely based on the privacy of the method
499 // FIXME(#10573) is this the right behavior? Why not consider
500 // where the method was defined?
501 Some(ast_map::NodeImplItem(ii)) => {
503 ast::MethodImplItem(ref m) => {
504 let imp = self.tcx.map
505 .get_parent_did(closest_private_id);
506 match ty::impl_trait_ref(self.tcx, imp) {
507 Some(..) => return Allowable,
508 _ if m.pe_vis() == ast::Public => {
514 ast::TypeImplItem(_) => return Allowable,
517 Some(ast_map::NodeTraitItem(_)) => {
521 // This is not a method call, extract the visibility as one
522 // would normally look at it
523 Some(ast_map::NodeItem(it)) => it.vis,
524 Some(ast_map::NodeForeignItem(_)) => {
525 self.tcx.map.get_foreign_vis(closest_private_id)
527 Some(ast_map::NodeVariant(..)) => {
528 ast::Public // need to move up a level (to the enum)
532 if vis != ast::Public { break }
533 // if we've reached the root, then everything was allowable and this
535 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
536 closest_private_id = self.parents[closest_private_id];
538 // If we reached the top, then we were public all the way down and
539 // we can allow this access.
540 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
542 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
543 if self.private_accessible(closest_private_id) {
546 DisallowedBy(closest_private_id)
550 /// For a local private node in the AST, this function will determine
551 /// whether the node is accessible by the current module that iteration is
553 fn private_accessible(&self, id: ast::NodeId) -> bool {
554 let parent = self.parents[id];
555 debug!("privacy - accessible parent {}", self.nodestr(parent));
557 // After finding `did`'s closest private member, we roll ourselves back
558 // to see if this private member's parent is anywhere in our ancestry.
559 // By the privacy rules, we can access all of our ancestor's private
560 // members, so that's why we test the parent, and not the did itself.
561 let mut cur = self.curitem;
563 debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
565 // If the relevant parent is in our history, then we're allowed
566 // to look inside any of our ancestor's immediate private items,
567 // so this access is valid.
568 x if x == parent => return true,
570 // If we've reached the root, then we couldn't access this item
571 // in the first place
572 ast::DUMMY_NODE_ID => return false,
578 cur = self.parents[cur];
582 fn report_error(&self, result: CheckResult) -> bool {
585 Some((span, msg, note)) => {
586 self.tcx.sess.span_err(span, &msg[]);
588 Some((span, msg)) => {
589 self.tcx.sess.span_note(span, &msg[])
598 /// Guarantee that a particular definition is public. Returns a CheckResult
599 /// which contains any errors found. These can be reported using `report_error`.
600 /// If the result is `None`, no errors were found.
601 fn ensure_public(&self, span: Span, to_check: ast::DefId,
602 source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
603 let id = match self.def_privacy(to_check) {
604 ExternallyDenied => {
605 return Some((span, format!("{} is private", msg), None))
607 Allowable => return None,
608 DisallowedBy(id) => id,
611 // If we're disallowed by a particular id, then we attempt to give a
612 // nice error message to say why it was disallowed. It was either
613 // because the item itself is private or because its parent is private
614 // and its parent isn't in our ancestry.
615 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
616 return Some((span, format!("{} is private", msg), None));
618 (span, format!("{} is inaccessible", msg))
620 let item = match self.tcx.map.find(id) {
621 Some(ast_map::NodeItem(item)) => {
623 // If an impl disallowed this item, then this is resolve's
624 // way of saying that a struct/enum's static method was
625 // invoked, and the struct/enum itself is private. Crawl
626 // back up the chains to find the relevant struct/enum that
628 ast::ItemImpl(_, _, _, _, ref ty, _) => {
629 let id = match ty.node {
630 ast::TyPath(_, id) => id,
631 _ => return Some((err_span, err_msg, None)),
633 let def = self.tcx.def_map.borrow()[id].clone();
634 let did = def.def_id();
635 assert!(is_local(did));
636 match self.tcx.map.get(did.node) {
637 ast_map::NodeItem(item) => item,
638 _ => self.tcx.sess.span_bug(item.span,
639 "path is not an item")
645 Some(..) | None => return Some((err_span, err_msg, None)),
647 let desc = match item.node {
648 ast::ItemMod(..) => "module",
649 ast::ItemTrait(..) => "trait",
650 ast::ItemStruct(..) => "struct",
651 ast::ItemEnum(..) => "enum",
652 _ => return Some((err_span, err_msg, None))
654 let msg = format!("{} `{}` is private", desc,
655 token::get_ident(item.ident));
656 Some((err_span, err_msg, Some((span, msg))))
659 // Checks that a field is in scope.
660 fn check_field(&mut self,
664 let fields = ty::lookup_struct_fields(self.tcx, id);
665 let field = match name {
666 NamedField(ident) => {
667 debug!("privacy - check named field {} in struct {:?}", ident.name, id);
668 fields.iter().find(|f| f.name == ident.name).unwrap()
670 UnnamedField(idx) => &fields[idx]
672 if field.vis == ast::Public ||
673 (is_local(field.id) && self.private_accessible(field.id.node)) {
677 let struct_type = ty::lookup_item_type(self.tcx, id).ty;
678 let struct_desc = match struct_type.sty {
679 ty::ty_struct(_, _) =>
680 format!("struct `{}`", ty::item_path_str(self.tcx, id)),
681 // struct variant fields have inherited visibility
682 ty::ty_enum(..) => return,
683 _ => self.tcx.sess.span_bug(span, "can't find struct for field")
685 let msg = match name {
686 NamedField(name) => format!("field `{}` of {} is private",
687 token::get_ident(name), struct_desc),
688 UnnamedField(idx) => format!("field #{} of {} is private",
689 idx + 1, struct_desc),
691 self.tcx.sess.span_err(span, &msg[]);
694 // Given the ID of a method, checks to ensure it's in scope.
695 fn check_static_method(&mut self,
697 method_id: ast::DefId,
699 // If the method is a default method, we need to use the def_id of
700 // the default implementation.
701 let method_id = match ty::impl_or_trait_item(self.tcx, method_id) {
702 ty::MethodTraitItem(method_type) => {
703 method_type.provided_source.unwrap_or(method_id)
705 ty::TypeTraitItem(_) => method_id,
708 let string = token::get_ident(name);
709 self.report_error(self.ensure_public(span,
712 &format!("method `{}`",
716 // Checks that a path is in scope.
717 fn check_path(&mut self, span: Span, path_id: ast::NodeId, path: &ast::Path) {
718 debug!("privacy - path {}", self.nodestr(path_id));
719 let orig_def = self.tcx.def_map.borrow()[path_id].clone();
720 let ck = |&: tyname: &str| {
721 let ck_public = |&: def: ast::DefId| {
722 debug!("privacy - ck_public {:?}", def);
723 let name = token::get_ident(path.segments.last().unwrap().identifier);
724 let origdid = orig_def.def_id();
725 self.ensure_public(span,
728 &format!("{} `{}`", tyname, name)[])
731 match self.last_private_map[path_id] {
732 LastMod(AllPublic) => {},
733 LastMod(DependsOn(def)) => {
734 self.report_error(ck_public(def));
736 LastImport { value_priv,
737 value_used: check_value,
739 type_used: check_type } => {
740 // This dance with found_error is because we don't want to
741 // report a privacy error twice for the same directive.
742 let found_error = match (type_priv, check_type) {
743 (Some(DependsOn(def)), Used) => {
744 !self.report_error(ck_public(def))
749 match (value_priv, check_value) {
750 (Some(DependsOn(def)), Used) => {
751 self.report_error(ck_public(def));
756 // If an import is not used in either namespace, we still
757 // want to check that it could be legal. Therefore we check
758 // in both namespaces and only report an error if both would
759 // be illegal. We only report one error, even if it is
760 // illegal to import from both namespaces.
761 match (value_priv, check_value, type_priv, check_type) {
762 (Some(p), Unused, None, _) |
763 (None, _, Some(p), Unused) => {
766 DependsOn(def) => ck_public(def),
769 self.report_error(p);
772 (Some(v), Unused, Some(t), Unused) => {
775 DependsOn(def) => ck_public(def),
779 DependsOn(def) => ck_public(def),
781 if let (Some(_), Some(t)) = (v, t) {
782 self.report_error(Some(t));
790 // FIXME(#12334) Imports can refer to definitions in both the type and
791 // value namespaces. The privacy information is aware of this, but the
792 // def map is not. Therefore the names we work out below will not always
793 // be accurate and we can get slightly wonky error messages (but type
794 // checking is always correct).
795 match self.tcx.def_map.borrow()[path_id].clone() {
796 def::DefStaticMethod(..) => ck("static method"),
797 def::DefFn(..) => ck("function"),
798 def::DefStatic(..) => ck("static"),
799 def::DefConst(..) => ck("const"),
800 def::DefVariant(..) => ck("variant"),
801 def::DefTy(_, false) => ck("type"),
802 def::DefTy(_, true) => ck("enum"),
803 def::DefTrait(..) => ck("trait"),
804 def::DefStruct(..) => ck("struct"),
805 def::DefMethod(_, Some(..), _) => ck("trait method"),
806 def::DefMethod(..) => ck("method"),
807 def::DefMod(..) => ck("module"),
812 // Checks that a method is in scope.
813 fn check_method(&mut self, span: Span, origin: &MethodOrigin,
816 MethodStatic(method_id) => {
817 self.check_static_method(span, method_id, ident)
819 MethodStaticUnboxedClosure(_) => {}
820 // Trait methods are always all public. The only controlling factor
821 // is whether the trait itself is accessible or not.
822 MethodTypeParam(MethodParam { ref trait_ref, .. }) |
823 MethodTraitObject(MethodObject { ref trait_ref, .. }) => {
824 self.report_error(self.ensure_public(span, trait_ref.def_id,
825 None, "source trait"));
831 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
832 fn visit_item(&mut self, item: &ast::Item) {
833 let orig_curitem = replace(&mut self.curitem, item.id);
834 visit::walk_item(self, item);
835 self.curitem = orig_curitem;
838 fn visit_expr(&mut self, expr: &ast::Expr) {
840 ast::ExprField(ref base, ident) => {
841 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
842 self.check_field(expr.span, id, NamedField(ident.node));
845 ast::ExprTupField(ref base, idx) => {
846 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
847 self.check_field(expr.span, id, UnnamedField(idx.node));
850 ast::ExprMethodCall(ident, _, _) => {
851 let method_call = MethodCall::expr(expr.id);
852 match self.tcx.method_map.borrow().get(&method_call) {
854 self.tcx.sess.span_bug(expr.span,
855 "method call not in \
859 debug!("(privacy checking) checking impl method");
860 self.check_method(expr.span, &method.origin, ident.node);
864 ast::ExprStruct(_, ref fields, _) => {
865 match ty::expr_ty(self.tcx, expr).sty {
866 ty::ty_struct(id, _) => {
867 for field in (*fields).iter() {
868 self.check_field(expr.span, id,
869 NamedField(field.ident.node));
872 ty::ty_enum(_, _) => {
873 match self.tcx.def_map.borrow()[expr.id].clone() {
874 def::DefVariant(_, variant_id, _) => {
875 for field in fields.iter() {
876 self.check_field(expr.span, variant_id,
877 NamedField(field.ident.node));
880 _ => self.tcx.sess.span_bug(expr.span,
887 _ => self.tcx.sess.span_bug(expr.span, "struct expr \
892 ast::ExprPath(_) | ast::ExprQPath(_) => {
893 let guard = |&: did: ast::DefId| {
894 let fields = ty::lookup_struct_fields(self.tcx, did);
895 let any_priv = fields.iter().any(|f| {
896 f.vis != ast::Public && (
898 !self.private_accessible(f.id.node))
901 self.tcx.sess.span_err(expr.span,
902 "cannot invoke tuple struct constructor \
903 with private fields");
906 match self.tcx.def_map.borrow().get(&expr.id) {
907 Some(&def::DefStruct(did)) => {
908 guard(if is_local(did) {
909 local_def(self.tcx.map.get_parent(did.node))
911 // "tuple structs" with zero fields (such as
912 // `pub struct Foo;`) don't have a ctor_id, hence
913 // the unwrap_or to the same struct id.
915 csearch::get_tuple_struct_definition_if_ctor(
916 &self.tcx.sess.cstore, did);
917 maybe_did.unwrap_or(did)
926 visit::walk_expr(self, expr);
929 fn visit_view_item(&mut self, a: &ast::ViewItem) {
931 ast::ViewItemExternCrate(..) => {}
932 ast::ViewItemUse(ref vpath) => {
934 ast::ViewPathSimple(..) | ast::ViewPathGlob(..) => {}
935 ast::ViewPathList(ref prefix, ref list, _) => {
936 for pid in list.iter() {
938 ast::PathListIdent { id, name } => {
939 debug!("privacy - ident item {}", id);
940 let seg = ast::PathSegment {
942 parameters: ast::PathParameters::none(),
944 let segs = vec![seg];
945 let path = ast::Path {
950 self.check_path(pid.span, id, &path);
952 ast::PathListMod { id } => {
953 debug!("privacy - mod item {}", id);
954 self.check_path(pid.span, id, prefix);
962 visit::walk_view_item(self, a);
965 fn visit_pat(&mut self, pattern: &ast::Pat) {
966 // Foreign functions do not have their patterns mapped in the def_map,
967 // and there's nothing really relevant there anyway, so don't bother
968 // checking privacy. If you can name the type then you can pass it to an
969 // external C function anyway.
970 if self.in_foreign { return }
973 ast::PatStruct(_, ref fields, _) => {
974 match ty::pat_ty(self.tcx, pattern).sty {
975 ty::ty_struct(id, _) => {
976 for field in fields.iter() {
977 self.check_field(pattern.span, id,
978 NamedField(field.node.ident));
981 ty::ty_enum(_, _) => {
982 match self.tcx.def_map.borrow().get(&pattern.id) {
983 Some(&def::DefVariant(_, variant_id, _)) => {
984 for field in fields.iter() {
985 self.check_field(pattern.span, variant_id,
986 NamedField(field.node.ident));
989 _ => self.tcx.sess.span_bug(pattern.span,
996 _ => self.tcx.sess.span_bug(pattern.span,
997 "struct pattern didn't have \
1002 // Patterns which bind no fields are allowable (the path is check
1004 ast::PatEnum(_, Some(ref fields)) => {
1005 match ty::pat_ty(self.tcx, pattern).sty {
1006 ty::ty_struct(id, _) => {
1007 for (i, field) in fields.iter().enumerate() {
1008 if let ast::PatWild(..) = field.node {
1011 self.check_field(field.span, id, UnnamedField(i));
1014 ty::ty_enum(..) => {
1015 // enum fields have no privacy at this time
1024 visit::walk_pat(self, pattern);
1027 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
1028 self.in_foreign = true;
1029 visit::walk_foreign_item(self, fi);
1030 self.in_foreign = false;
1033 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
1034 self.check_path(path.span, id, path);
1035 visit::walk_path(self, path);
1039 ////////////////////////////////////////////////////////////////////////////////
1040 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1041 ////////////////////////////////////////////////////////////////////////////////
1043 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1044 tcx: &'a ty::ctxt<'tcx>,
1048 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1049 fn visit_item(&mut self, item: &ast::Item) {
1051 self.check_all_inherited(item);
1053 self.check_sane_privacy(item);
1056 let in_fn = self.in_fn;
1057 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1058 ast::ItemMod(..) => false, // modules turn privacy back on
1059 _ => in_fn, // otherwise we inherit
1061 visit::walk_item(self, item);
1062 self.in_fn = orig_in_fn;
1065 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1066 b: &'v ast::Block, s: Span, _: ast::NodeId) {
1067 // This catches both functions and methods
1068 let orig_in_fn = replace(&mut self.in_fn, true);
1069 visit::walk_fn(self, fk, fd, b, s);
1070 self.in_fn = orig_in_fn;
1073 fn visit_view_item(&mut self, i: &ast::ViewItem) {
1075 ast::Inherited => {}
1078 self.tcx.sess.span_err(i.span, "unnecessary `pub`, imports \
1079 in functions are never \
1081 } else if let ast::ViewItemExternCrate(..) = i.node {
1082 self.tcx.sess.span_err(i.span, "`pub` visibility \
1087 visit::walk_view_item(self, i);
1091 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1092 /// Validates all of the visibility qualifiers placed on the item given. This
1093 /// ensures that there are no extraneous qualifiers that don't actually do
1094 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1095 /// later on down the road...
1096 fn check_sane_privacy(&self, item: &ast::Item) {
1098 let check_inherited = |&: sp: Span, vis: ast::Visibility, note: &str| {
1099 if vis != ast::Inherited {
1100 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1102 tcx.sess.span_note(sp, note);
1107 // implementations of traits don't need visibility qualifiers because
1108 // that's controlled by having the trait in scope.
1109 ast::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1110 check_inherited(item.span, item.vis,
1111 "visibility qualifiers have no effect on trait \
1113 for impl_item in impl_items.iter() {
1115 ast::MethodImplItem(ref m) => {
1116 check_inherited(m.span, m.pe_vis(), "");
1118 ast::TypeImplItem(_) => {}
1123 ast::ItemImpl(..) => {
1124 check_inherited(item.span, item.vis,
1125 "place qualifiers on individual methods instead");
1127 ast::ItemForeignMod(..) => {
1128 check_inherited(item.span, item.vis,
1129 "place qualifiers on individual functions \
1133 ast::ItemEnum(ref def, _) => {
1134 for v in def.variants.iter() {
1137 if item.vis == ast::Public {
1138 tcx.sess.span_err(v.span, "unnecessary `pub` \
1142 ast::Inherited => {}
1147 ast::ItemTrait(_, _, _, ref methods) => {
1148 for m in methods.iter() {
1150 ast::ProvidedMethod(ref m) => {
1151 check_inherited(m.span, m.pe_vis(),
1152 "unnecessary visibility");
1154 ast::RequiredMethod(ref m) => {
1155 check_inherited(m.span, m.vis,
1156 "unnecessary visibility");
1158 ast::TypeTraitItem(_) => {}
1163 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemStruct(..) |
1164 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1165 ast::ItemMac(..) => {}
1169 /// When inside of something like a function or a method, visibility has no
1170 /// control over anything so this forbids any mention of any visibility
1171 fn check_all_inherited(&self, item: &ast::Item) {
1173 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
1174 if vis != ast::Inherited {
1175 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1178 let check_struct = |&: def: &ast::StructDef| {
1179 for f in def.fields.iter() {
1181 ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
1182 ast::UnnamedField(..) => {}
1186 check_inherited(tcx, item.span, item.vis);
1188 ast::ItemImpl(_, _, _, _, _, ref impl_items) => {
1189 for impl_item in impl_items.iter() {
1191 ast::MethodImplItem(ref m) => {
1192 check_inherited(tcx, m.span, m.pe_vis());
1194 ast::TypeImplItem(_) => {}
1198 ast::ItemForeignMod(ref fm) => {
1199 for i in fm.items.iter() {
1200 check_inherited(tcx, i.span, i.vis);
1203 ast::ItemEnum(ref def, _) => {
1204 for v in def.variants.iter() {
1205 check_inherited(tcx, v.span, v.node.vis);
1209 ast::ItemStruct(ref def, _) => check_struct(&**def),
1211 ast::ItemTrait(_, _, _, ref methods) => {
1212 for m in methods.iter() {
1214 ast::RequiredMethod(..) => {}
1215 ast::ProvidedMethod(ref m) => check_inherited(tcx, m.span,
1217 ast::TypeTraitItem(_) => {}
1222 ast::ItemStatic(..) | ast::ItemConst(..) |
1223 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1224 ast::ItemMac(..) => {}
1229 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1230 tcx: &'a ty::ctxt<'tcx>,
1231 exported_items: &'a ExportedItems,
1232 public_items: &'a PublicItems,
1236 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1237 inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1238 /// whether the type refers to private types.
1239 contains_private: bool,
1240 /// whether we've recurred at all (i.e. if we're pointing at the
1241 /// first type on which visit_ty was called).
1242 at_outer_type: bool,
1243 // whether that first type is a public path.
1244 outer_type_is_public_path: bool,
1247 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1248 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1249 let did = match self.tcx.def_map.borrow().get(&path_id).cloned() {
1250 // `int` etc. (None doesn't seem to occur.)
1251 None | Some(def::DefPrimTy(..)) => return false,
1252 Some(def) => def.def_id()
1254 // A path can only be private if:
1255 // it's in this crate...
1259 // .. and it corresponds to a private type in the AST (this returns
1260 // None for type parameters)
1261 match self.tcx.map.find(did.node) {
1262 Some(ast_map::NodeItem(ref item)) => item.vis != ast::Public,
1263 Some(_) | None => false,
1267 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1268 // FIXME: this would preferably be using `exported_items`, but all
1269 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1270 self.public_items.contains(&trait_id)
1273 fn check_ty_param_bound(&self,
1274 ty_param_bound: &ast::TyParamBound) {
1275 if let ast::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1276 if !self.tcx.sess.features.borrow().visible_private_types &&
1277 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1278 let span = trait_ref.trait_ref.path.span;
1279 self.tcx.sess.span_err(span,
1280 "private trait in exported type \
1287 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1288 fn visit_ty(&mut self, ty: &ast::Ty) {
1289 if let ast::TyPath(_, path_id) = ty.node {
1290 if self.inner.path_is_private_type(path_id) {
1291 self.contains_private = true;
1292 // found what we're looking for so let's stop
1295 } else if self.at_outer_type {
1296 self.outer_type_is_public_path = true;
1299 self.at_outer_type = false;
1300 visit::walk_ty(self, ty)
1303 // don't want to recurse into [, .. expr]
1304 fn visit_expr(&mut self, _: &ast::Expr) {}
1307 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1308 fn visit_item(&mut self, item: &ast::Item) {
1310 // contents of a private mod can be reexported, so we need
1311 // to check internals.
1312 ast::ItemMod(_) => {}
1314 // An `extern {}` doesn't introduce a new privacy
1315 // namespace (the contents have their own privacies).
1316 ast::ItemForeignMod(_) => {}
1318 ast::ItemTrait(_, _, ref bounds, _) => {
1319 if !self.trait_is_public(item.id) {
1323 for bound in bounds.iter() {
1324 self.check_ty_param_bound(bound)
1328 // impls need some special handling to try to offer useful
1329 // error messages without (too many) false positives
1330 // (i.e. we could just return here to not check them at
1331 // all, or some worse estimation of whether an impl is
1332 // publicly visible.
1333 ast::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1334 // `impl [... for] Private` is never visible.
1335 let self_contains_private;
1336 // impl [... for] Public<...>, but not `impl [... for]
1337 // ~[Public]` or `(Public,)` etc.
1338 let self_is_public_path;
1340 // check the properties of the Self type:
1342 let mut visitor = CheckTypeForPrivatenessVisitor {
1344 contains_private: false,
1345 at_outer_type: true,
1346 outer_type_is_public_path: false,
1348 visitor.visit_ty(&**self_);
1349 self_contains_private = visitor.contains_private;
1350 self_is_public_path = visitor.outer_type_is_public_path;
1353 // miscellaneous info about the impl
1355 // `true` iff this is `impl Private for ...`.
1356 let not_private_trait =
1357 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1359 let did = ty::trait_ref_to_def_id(self.tcx, tr);
1361 !is_local(did) || self.trait_is_public(did.node)
1364 // `true` iff this is a trait impl or at least one method is public.
1366 // `impl Public { $( fn ...() {} )* }` is not visible.
1368 // This is required over just using the methods' privacy
1369 // directly because we might have `impl<T: Foo<Private>> ...`,
1370 // and we shouldn't warn about the generics if all the methods
1371 // are private (because `T` won't be visible externally).
1372 let trait_or_some_public_method =
1373 trait_ref.is_some() ||
1377 ast::MethodImplItem(ref m) => {
1378 self.exported_items.contains(&m.id)
1380 ast::TypeImplItem(_) => false,
1384 if !self_contains_private &&
1385 not_private_trait &&
1386 trait_or_some_public_method {
1388 visit::walk_generics(self, g);
1392 for impl_item in impl_items.iter() {
1394 ast::MethodImplItem(ref method) => {
1395 visit::walk_method_helper(self, &**method)
1397 ast::TypeImplItem(_) => {}
1402 // Any private types in a trait impl fall into two
1404 // 1. mentioned in the trait definition
1405 // 2. mentioned in the type params/generics
1407 // Those in 1. can only occur if the trait is in
1408 // this crate and will've been warned about on the
1409 // trait definition (there's no need to warn twice
1410 // so we don't check the methods).
1412 // Those in 2. are warned via walk_generics and this
1414 self.visit_trait_ref(tr)
1417 } else if trait_ref.is_none() && self_is_public_path {
1418 // impl Public<Private> { ... }. Any public static
1419 // methods will be visible as `Public::foo`.
1420 let mut found_pub_static = false;
1421 for impl_item in impl_items.iter() {
1423 ast::MethodImplItem(ref method) => {
1424 if method.pe_explicit_self().node ==
1427 .contains(&method.id) {
1428 found_pub_static = true;
1429 visit::walk_method_helper(self, &**method);
1432 ast::TypeImplItem(_) => {}
1435 if found_pub_static {
1436 visit::walk_generics(self, g)
1442 // `type ... = ...;` can contain private types, because
1443 // we're introducing a new name.
1444 ast::ItemTy(..) => return,
1446 // not at all public, so we don't care
1447 _ if !self.exported_items.contains(&item.id) => return,
1452 // we've carefully constructed it so that if we're here, then
1453 // any `visit_ty`'s will be called on things that are in
1454 // public signatures, i.e. things that we're interested in for
1456 visit::walk_item(self, item);
1459 fn visit_generics(&mut self, generics: &ast::Generics) {
1460 for ty_param in generics.ty_params.iter() {
1461 for bound in ty_param.bounds.iter() {
1462 self.check_ty_param_bound(bound)
1465 for predicate in generics.where_clause.predicates.iter() {
1467 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
1468 for bound in bound_pred.bounds.iter() {
1469 self.check_ty_param_bound(bound)
1472 &ast::WherePredicate::RegionPredicate(_) => {}
1473 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
1474 self.visit_ty(&*eq_pred.ty);
1480 fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
1481 if self.exported_items.contains(&item.id) {
1482 visit::walk_foreign_item(self, item)
1486 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1487 b: &'v ast::Block, s: Span, id: ast::NodeId) {
1488 // needs special handling for methods.
1489 if self.exported_items.contains(&id) {
1490 visit::walk_fn(self, fk, fd, b, s);
1494 fn visit_ty(&mut self, t: &ast::Ty) {
1495 if let ast::TyPath(ref p, path_id) = t.node {
1496 if !self.tcx.sess.features.borrow().visible_private_types &&
1497 self.path_is_private_type(path_id) {
1498 self.tcx.sess.span_err(p.span,
1499 "private type in exported type signature");
1502 visit::walk_ty(self, t)
1505 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
1506 if self.exported_items.contains(&v.node.id) {
1507 self.in_variant = true;
1508 visit::walk_variant(self, v, g);
1509 self.in_variant = false;
1513 fn visit_struct_field(&mut self, s: &ast::StructField) {
1515 ast::NamedField(_, vis) if vis == ast::Public || self.in_variant => {
1516 visit::walk_struct_field(self, s);
1523 // we don't need to introspect into these at all: an
1524 // expression/block context can't possibly contain exported
1525 // things, and neither do view_items. (Making them no-ops stops us
1526 // from traversing the whole AST without having to be super
1527 // careful about our `walk_...` calls above.)
1528 fn visit_view_item(&mut self, _: &ast::ViewItem) {}
1529 fn visit_block(&mut self, _: &ast::Block) {}
1530 fn visit_expr(&mut self, _: &ast::Expr) {}
1533 pub fn check_crate(tcx: &ty::ctxt,
1534 export_map: &def::ExportMap,
1535 external_exports: ExternalExports,
1536 last_private_map: LastPrivateMap)
1537 -> (ExportedItems, PublicItems) {
1538 let krate = tcx.map.krate();
1540 // Figure out who everyone's parent is
1541 let mut visitor = ParentVisitor {
1542 parents: NodeMap::new(),
1543 curparent: ast::DUMMY_NODE_ID,
1545 visit::walk_crate(&mut visitor, krate);
1547 // Use the parent map to check the privacy of everything
1548 let mut visitor = PrivacyVisitor {
1549 curitem: ast::DUMMY_NODE_ID,
1552 parents: visitor.parents,
1553 external_exports: external_exports,
1554 last_private_map: last_private_map,
1556 visit::walk_crate(&mut visitor, krate);
1558 // Sanity check to make sure that all privacy usage and controls are
1560 let mut visitor = SanePrivacyVisitor {
1564 visit::walk_crate(&mut visitor, krate);
1566 tcx.sess.abort_if_errors();
1568 // Build up a set of all exported items in the AST. This is a set of all
1569 // items which are reachable from external crates based on visibility.
1570 let mut visitor = EmbargoVisitor {
1572 exported_items: NodeSet::new(),
1573 public_items: NodeSet::new(),
1574 reexports: NodeSet::new(),
1575 export_map: export_map,
1576 prev_exported: true,
1580 let before = visitor.exported_items.len();
1581 visit::walk_crate(&mut visitor, krate);
1582 if before == visitor.exported_items.len() {
1587 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1590 let mut visitor = VisiblePrivateTypesVisitor {
1592 exported_items: &exported_items,
1593 public_items: &public_items,
1596 visit::walk_crate(&mut visitor, krate);
1598 return (exported_items, public_items);