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)]
23 #[macro_use] extern crate log;
24 #[macro_use] extern crate syntax;
28 use self::PrivacyResult::*;
29 use self::FieldName::*;
31 use std::mem::replace;
33 use rustc::metadata::csearch;
34 use rustc::middle::def;
35 use rustc::middle::privacy::ImportUse::*;
36 use rustc::middle::privacy::LastPrivate::*;
37 use rustc::middle::privacy::PrivateDep::*;
38 use rustc::middle::privacy::{ExportedItems, PublicItems, LastPrivateMap};
39 use rustc::middle::privacy::{ExternalExports};
40 use rustc::middle::ty::{MethodTypeParam, MethodStatic};
41 use rustc::middle::ty::{MethodCall, MethodMap, MethodOrigin, MethodParam};
42 use rustc::middle::ty::{MethodStaticUnboxedClosure, MethodObject};
43 use rustc::middle::ty::{MethodTraitObject};
44 use rustc::middle::ty::{self, Ty};
45 use rustc::util::nodemap::{NodeMap, NodeSet};
47 use syntax::{ast, ast_map};
48 use syntax::ast_util::{is_local, local_def, PostExpansionMethod};
49 use syntax::codemap::Span;
50 use syntax::parse::token;
51 use syntax::visit::{self, Visitor};
53 type Context<'a, 'tcx> = (&'a MethodMap<'tcx>, &'a def::ExportMap);
55 /// Result of a checking operation - None => no errors were found. Some => an
56 /// error and contains the span and message for reporting that error and
57 /// optionally the same for a note about the error.
58 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
60 ////////////////////////////////////////////////////////////////////////////////
61 /// The parent visitor, used to determine what's the parent of what (node-wise)
62 ////////////////////////////////////////////////////////////////////////////////
64 struct ParentVisitor {
65 parents: NodeMap<ast::NodeId>,
66 curparent: ast::NodeId,
69 impl<'v> Visitor<'v> for ParentVisitor {
70 fn visit_item(&mut self, item: &ast::Item) {
71 self.parents.insert(item.id, self.curparent);
73 let prev = self.curparent;
75 ast::ItemMod(..) => { self.curparent = item.id; }
76 // Enum variants are parented to the enum definition itself because
77 // they inherit privacy
78 ast::ItemEnum(ref def, _) => {
79 for variant in def.variants.iter() {
80 // The parent is considered the enclosing enum because the
81 // enum will dictate the privacy visibility of this variant
83 self.parents.insert(variant.node.id, item.id);
87 // Trait methods are always considered "public", but if the trait is
88 // private then we need some private item in the chain from the
89 // method to the root. In this case, if the trait is private, then
90 // parent all the methods to the trait to indicate that they're
92 ast::ItemTrait(_, _, _, ref methods) if item.vis != ast::Public => {
93 for m in methods.iter() {
95 ast::ProvidedMethod(ref m) => {
96 self.parents.insert(m.id, item.id);
98 ast::RequiredMethod(ref m) => {
99 self.parents.insert(m.id, item.id);
101 ast::TypeTraitItem(_) => {}
108 visit::walk_item(self, item);
109 self.curparent = prev;
112 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
113 self.parents.insert(a.id, self.curparent);
114 visit::walk_foreign_item(self, a);
117 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
118 c: &'v ast::Block, d: Span, id: ast::NodeId) {
119 // We already took care of some trait methods above, otherwise things
120 // like impl methods and pub trait methods are parented to the
121 // containing module, not the containing trait.
122 if !self.parents.contains_key(&id) {
123 self.parents.insert(id, self.curparent);
125 visit::walk_fn(self, a, b, c, d);
128 fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
129 _: &'v ast::Generics, n: ast::NodeId) {
130 // Struct constructors are parented to their struct definitions because
131 // they essentially are the struct definitions.
133 Some(id) => { self.parents.insert(id, n); }
137 // While we have the id of the struct definition, go ahead and parent
139 for field in s.fields.iter() {
140 self.parents.insert(field.node.id, self.curparent);
142 visit::walk_struct_def(self, s)
146 ////////////////////////////////////////////////////////////////////////////////
147 /// The embargo visitor, used to determine the exports of the ast
148 ////////////////////////////////////////////////////////////////////////////////
150 struct EmbargoVisitor<'a, 'tcx: 'a> {
151 tcx: &'a ty::ctxt<'tcx>,
152 export_map: &'a def::ExportMap,
154 // This flag is an indicator of whether the previous item in the
155 // hierarchical chain was exported or not. This is the indicator of whether
156 // children should be exported as well. Note that this can flip from false
157 // to true if a reexported module is entered (or an action similar).
160 // This is a list of all exported items in the AST. An exported item is any
161 // function/method/item which is usable by external crates. This essentially
162 // means that the result is "public all the way down", but the "path down"
163 // may jump across private boundaries through reexport statements.
164 exported_items: ExportedItems,
166 // This sets contains all the destination nodes which are publicly
167 // re-exported. This is *not* a set of all reexported nodes, only a set of
168 // all nodes which are reexported *and* reachable from external crates. This
169 // means that the destination of the reexport is exported, and hence the
170 // destination must also be exported.
173 // These two fields are closely related to one another in that they are only
174 // used for generation of the 'PublicItems' set, not for privacy checking at
176 public_items: PublicItems,
180 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
181 // There are checks inside of privacy which depend on knowing whether a
182 // trait should be exported or not. The two current consumers of this are:
184 // 1. Should default methods of a trait be exported?
185 // 2. Should the methods of an implementation of a trait be exported?
187 // The answer to both of these questions partly rely on whether the trait
188 // itself is exported or not. If the trait is somehow exported, then the
189 // answers to both questions must be yes. Right now this question involves
190 // more analysis than is currently done in rustc, so we conservatively
191 // answer "yes" so that all traits need to be exported.
192 fn exported_trait(&self, _id: ast::NodeId) -> bool {
197 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
198 fn visit_item(&mut self, item: &ast::Item) {
199 let orig_all_pub = self.prev_public;
200 self.prev_public = orig_all_pub && item.vis == ast::Public;
201 if self.prev_public {
202 self.public_items.insert(item.id);
205 let orig_all_exported = self.prev_exported;
207 // impls/extern blocks do not break the "public chain" because they
208 // cannot have visibility qualifiers on them anyway
209 ast::ItemImpl(..) | ast::ItemForeignMod(..) => {}
211 // Traits are a little special in that even if they themselves are
212 // not public they may still be exported.
213 ast::ItemTrait(..) => {
214 self.prev_exported = self.exported_trait(item.id);
217 // Private by default, hence we only retain the "public chain" if
218 // `pub` is explicitly listed.
221 (orig_all_exported && item.vis == ast::Public) ||
222 self.reexports.contains(&item.id);
226 let public_first = self.prev_exported &&
227 self.exported_items.insert(item.id);
230 // Enum variants inherit from their parent, so if the enum is
231 // public all variants are public unless they're explicitly priv
232 ast::ItemEnum(ref def, _) if public_first => {
233 for variant in def.variants.iter() {
234 self.exported_items.insert(variant.node.id);
238 // Implementations are a little tricky to determine what's exported
239 // out of them. Here's a few cases which are currently defined:
241 // * Impls for private types do not need to export their methods
242 // (either public or private methods)
244 // * Impls for public types only have public methods exported
246 // * Public trait impls for public types must have all methods
249 // * Private trait impls for public types can be ignored
251 // * Public trait impls for private types have their methods
252 // exported. I'm not entirely certain that this is the correct
253 // thing to do, but I have seen use cases of where this will cause
254 // undefined symbols at linkage time if this case is not handled.
256 // * Private trait impls for private types can be completely ignored
257 ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
258 let public_ty = match ty.node {
259 ast::TyPath(_, id) => {
260 match self.tcx.def_map.borrow()[id].clone() {
261 def::DefPrimTy(..) => true,
263 let did = def.def_id();
265 self.exported_items.contains(&did.node)
271 let tr = ty::impl_trait_ref(self.tcx, local_def(item.id));
272 let public_trait = tr.clone().map_or(false, |tr| {
273 !is_local(tr.def_id) ||
274 self.exported_items.contains(&tr.def_id.node)
277 if public_ty || public_trait {
278 for impl_item in impl_items.iter() {
280 ast::MethodImplItem(ref method) => {
282 match method.pe_explicit_self().node {
283 ast::SelfStatic => public_ty,
285 } && method.pe_vis() == ast::Public;
286 if meth_public || tr.is_some() {
287 self.exported_items.insert(method.id);
290 ast::TypeImplItem(_) => {}
296 // Default methods on traits are all public so long as the trait
298 ast::ItemTrait(_, _, _, ref methods) if public_first => {
299 for method in methods.iter() {
301 ast::ProvidedMethod(ref m) => {
302 debug!("provided {}", m.id);
303 self.exported_items.insert(m.id);
305 ast::RequiredMethod(ref m) => {
306 debug!("required {}", m.id);
307 self.exported_items.insert(m.id);
309 ast::TypeTraitItem(ref t) => {
310 debug!("typedef {}", t.ty_param.id);
311 self.exported_items.insert(t.ty_param.id);
317 // Struct constructors are public if the struct is all public.
318 ast::ItemStruct(ref def, _) if public_first => {
320 Some(id) => { self.exported_items.insert(id); }
325 ast::ItemTy(ref ty, _) if public_first => {
326 if let ast::TyPath(_, id) = ty.node {
327 match self.tcx.def_map.borrow()[id].clone() {
328 def::DefPrimTy(..) | def::DefTyParam(..) => {},
330 let did = def.def_id();
332 self.exported_items.insert(did.node);
342 visit::walk_item(self, item);
344 self.prev_exported = orig_all_exported;
345 self.prev_public = orig_all_pub;
348 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
349 if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) {
350 self.exported_items.insert(a.id);
354 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) {
355 // This code is here instead of in visit_item so that the
356 // crate module gets processed as well.
357 if self.prev_exported {
358 assert!(self.export_map.contains_key(&id), "wut {}", id);
359 for export in self.export_map[id].iter() {
360 if is_local(export.def_id) {
361 self.reexports.insert(export.def_id.node);
365 visit::walk_mod(self, m)
369 ////////////////////////////////////////////////////////////////////////////////
370 /// The privacy visitor, where privacy checks take place (violations reported)
371 ////////////////////////////////////////////////////////////////////////////////
373 struct PrivacyVisitor<'a, 'tcx: 'a> {
374 tcx: &'a ty::ctxt<'tcx>,
375 curitem: ast::NodeId,
377 parents: NodeMap<ast::NodeId>,
378 external_exports: ExternalExports,
379 last_private_map: LastPrivateMap,
385 DisallowedBy(ast::NodeId),
389 UnnamedField(uint), // index
390 // FIXME #6993: change type (and name) from Ident to Name
391 NamedField(ast::Ident),
394 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
395 // used when debugging
396 fn nodestr(&self, id: ast::NodeId) -> String {
397 self.tcx.map.node_to_string(id).to_string()
400 // Determines whether the given definition is public from the point of view
401 // of the current item.
402 fn def_privacy(&self, did: ast::DefId) -> PrivacyResult {
404 if self.external_exports.contains(&did) {
405 debug!("privacy - {:?} was externally exported", did);
408 debug!("privacy - is {:?} a public method", did);
410 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
411 Some(&ty::MethodTraitItem(ref meth)) => {
412 debug!("privacy - well at least it's a method: {:?}",
414 match meth.container {
415 ty::TraitContainer(id) => {
416 debug!("privacy - recursing on trait {:?}", id);
419 ty::ImplContainer(id) => {
420 match ty::impl_trait_ref(self.tcx, id) {
422 debug!("privacy - impl of trait {:?}", id);
423 self.def_privacy(t.def_id)
426 debug!("privacy - found a method {:?}",
428 if meth.vis == ast::Public {
438 Some(&ty::TypeTraitItem(ref typedef)) => {
439 match typedef.container {
440 ty::TraitContainer(id) => {
441 debug!("privacy - recursing on trait {:?}", id);
444 ty::ImplContainer(id) => {
445 match ty::impl_trait_ref(self.tcx, id) {
447 debug!("privacy - impl of trait {:?}", id);
448 self.def_privacy(t.def_id)
451 debug!("privacy - found a typedef {:?}",
453 if typedef.vis == ast::Public {
464 debug!("privacy - nope, not even a method");
470 debug!("privacy - local {} not public all the way down",
471 self.tcx.map.node_to_string(did.node));
472 // return quickly for things in the same module
473 if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
474 debug!("privacy - same parent, we're done here");
478 // We now know that there is at least one private member between the
479 // destination and the root.
480 let mut closest_private_id = did.node;
482 debug!("privacy - examining {}", self.nodestr(closest_private_id));
483 let vis = match self.tcx.map.find(closest_private_id) {
484 // If this item is a method, then we know for sure that it's an
485 // actual method and not a static method. The reason for this is
486 // that these cases are only hit in the ExprMethodCall
487 // expression, and ExprCall will have its path checked later
488 // (the path of the trait/impl) if it's a static method.
490 // With this information, then we can completely ignore all
491 // trait methods. The privacy violation would be if the trait
492 // couldn't get imported, not if the method couldn't be used
493 // (all trait methods are public).
495 // However, if this is an impl method, then we dictate this
496 // decision solely based on the privacy of the method
498 // FIXME(#10573) is this the right behavior? Why not consider
499 // where the method was defined?
500 Some(ast_map::NodeImplItem(ii)) => {
502 ast::MethodImplItem(ref m) => {
503 let imp = self.tcx.map
504 .get_parent_did(closest_private_id);
505 match ty::impl_trait_ref(self.tcx, imp) {
506 Some(..) => return Allowable,
507 _ if m.pe_vis() == ast::Public => {
513 ast::TypeImplItem(_) => return Allowable,
516 Some(ast_map::NodeTraitItem(_)) => {
520 // This is not a method call, extract the visibility as one
521 // would normally look at it
522 Some(ast_map::NodeItem(it)) => it.vis,
523 Some(ast_map::NodeForeignItem(_)) => {
524 self.tcx.map.get_foreign_vis(closest_private_id)
526 Some(ast_map::NodeVariant(..)) => {
527 ast::Public // need to move up a level (to the enum)
531 if vis != ast::Public { break }
532 // if we've reached the root, then everything was allowable and this
534 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
535 closest_private_id = self.parents[closest_private_id];
537 // If we reached the top, then we were public all the way down and
538 // we can allow this access.
539 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
541 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
542 if self.private_accessible(closest_private_id) {
545 DisallowedBy(closest_private_id)
549 /// For a local private node in the AST, this function will determine
550 /// whether the node is accessible by the current module that iteration is
552 fn private_accessible(&self, id: ast::NodeId) -> bool {
553 let parent = self.parents[id];
554 debug!("privacy - accessible parent {}", self.nodestr(parent));
556 // After finding `did`'s closest private member, we roll ourselves back
557 // to see if this private member's parent is anywhere in our ancestry.
558 // By the privacy rules, we can access all of our ancestor's private
559 // members, so that's why we test the parent, and not the did itself.
560 let mut cur = self.curitem;
562 debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
564 // If the relevant parent is in our history, then we're allowed
565 // to look inside any of our ancestor's immediate private items,
566 // so this access is valid.
567 x if x == parent => return true,
569 // If we've reached the root, then we couldn't access this item
570 // in the first place
571 ast::DUMMY_NODE_ID => return false,
577 cur = self.parents[cur];
581 fn report_error(&self, result: CheckResult) -> bool {
584 Some((span, msg, note)) => {
585 self.tcx.sess.span_err(span, &msg[]);
587 Some((span, msg)) => {
588 self.tcx.sess.span_note(span, &msg[])
597 /// Guarantee that a particular definition is public. Returns a CheckResult
598 /// which contains any errors found. These can be reported using `report_error`.
599 /// If the result is `None`, no errors were found.
600 fn ensure_public(&self, span: Span, to_check: ast::DefId,
601 source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
602 let id = match self.def_privacy(to_check) {
603 ExternallyDenied => {
604 return Some((span, format!("{} is private", msg), None))
606 Allowable => return None,
607 DisallowedBy(id) => id,
610 // If we're disallowed by a particular id, then we attempt to give a
611 // nice error message to say why it was disallowed. It was either
612 // because the item itself is private or because its parent is private
613 // and its parent isn't in our ancestry.
614 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
615 return Some((span, format!("{} is private", msg), None));
617 (span, format!("{} is inaccessible", msg))
619 let item = match self.tcx.map.find(id) {
620 Some(ast_map::NodeItem(item)) => {
622 // If an impl disallowed this item, then this is resolve's
623 // way of saying that a struct/enum's static method was
624 // invoked, and the struct/enum itself is private. Crawl
625 // back up the chains to find the relevant struct/enum that
627 ast::ItemImpl(_, _, _, _, ref ty, _) => {
628 let id = match ty.node {
629 ast::TyPath(_, id) => id,
630 _ => return Some((err_span, err_msg, None)),
632 let def = self.tcx.def_map.borrow()[id].clone();
633 let did = def.def_id();
634 assert!(is_local(did));
635 match self.tcx.map.get(did.node) {
636 ast_map::NodeItem(item) => item,
637 _ => self.tcx.sess.span_bug(item.span,
638 "path is not an item")
644 Some(..) | None => return Some((err_span, err_msg, None)),
646 let desc = match item.node {
647 ast::ItemMod(..) => "module",
648 ast::ItemTrait(..) => "trait",
649 ast::ItemStruct(..) => "struct",
650 ast::ItemEnum(..) => "enum",
651 _ => return Some((err_span, err_msg, None))
653 let msg = format!("{} `{}` is private", desc,
654 token::get_ident(item.ident));
655 Some((err_span, err_msg, Some((span, msg))))
658 // Checks that a field is in scope.
659 fn check_field(&mut self,
663 let fields = ty::lookup_struct_fields(self.tcx, id);
664 let field = match name {
665 NamedField(ident) => {
666 debug!("privacy - check named field {} in struct {:?}", ident.name, id);
667 fields.iter().find(|f| f.name == ident.name).unwrap()
669 UnnamedField(idx) => &fields[idx]
671 if field.vis == ast::Public ||
672 (is_local(field.id) && self.private_accessible(field.id.node)) {
676 let struct_type = ty::lookup_item_type(self.tcx, id).ty;
677 let struct_desc = match struct_type.sty {
678 ty::ty_struct(_, _) =>
679 format!("struct `{}`", ty::item_path_str(self.tcx, id)),
680 // struct variant fields have inherited visibility
681 ty::ty_enum(..) => return,
682 _ => self.tcx.sess.span_bug(span, "can't find struct for field")
684 let msg = match name {
685 NamedField(name) => format!("field `{}` of {} is private",
686 token::get_ident(name), struct_desc),
687 UnnamedField(idx) => format!("field #{} of {} is private",
688 idx + 1, struct_desc),
690 self.tcx.sess.span_err(span, &msg[]);
693 // Given the ID of a method, checks to ensure it's in scope.
694 fn check_static_method(&mut self,
696 method_id: ast::DefId,
698 // If the method is a default method, we need to use the def_id of
699 // the default implementation.
700 let method_id = match ty::impl_or_trait_item(self.tcx, method_id) {
701 ty::MethodTraitItem(method_type) => {
702 method_type.provided_source.unwrap_or(method_id)
704 ty::TypeTraitItem(_) => method_id,
707 let string = token::get_ident(name);
708 self.report_error(self.ensure_public(span,
711 &format!("method `{}`",
715 // Checks that a path is in scope.
716 fn check_path(&mut self, span: Span, path_id: ast::NodeId, path: &ast::Path) {
717 debug!("privacy - path {}", self.nodestr(path_id));
718 let orig_def = self.tcx.def_map.borrow()[path_id].clone();
719 let ck = |&: tyname: &str| {
720 let ck_public = |&: def: ast::DefId| {
721 debug!("privacy - ck_public {:?}", def);
722 let name = token::get_ident(path.segments.last().unwrap().identifier);
723 let origdid = orig_def.def_id();
724 self.ensure_public(span,
727 &format!("{} `{}`", tyname, name)[])
730 match self.last_private_map[path_id] {
731 LastMod(AllPublic) => {},
732 LastMod(DependsOn(def)) => {
733 self.report_error(ck_public(def));
735 LastImport { value_priv,
736 value_used: check_value,
738 type_used: check_type } => {
739 // This dance with found_error is because we don't want to
740 // report a privacy error twice for the same directive.
741 let found_error = match (type_priv, check_type) {
742 (Some(DependsOn(def)), Used) => {
743 !self.report_error(ck_public(def))
748 match (value_priv, check_value) {
749 (Some(DependsOn(def)), Used) => {
750 self.report_error(ck_public(def));
755 // If an import is not used in either namespace, we still
756 // want to check that it could be legal. Therefore we check
757 // in both namespaces and only report an error if both would
758 // be illegal. We only report one error, even if it is
759 // illegal to import from both namespaces.
760 match (value_priv, check_value, type_priv, check_type) {
761 (Some(p), Unused, None, _) |
762 (None, _, Some(p), Unused) => {
765 DependsOn(def) => ck_public(def),
768 self.report_error(p);
771 (Some(v), Unused, Some(t), Unused) => {
774 DependsOn(def) => ck_public(def),
778 DependsOn(def) => ck_public(def),
780 if let (Some(_), Some(t)) = (v, t) {
781 self.report_error(Some(t));
789 // FIXME(#12334) Imports can refer to definitions in both the type and
790 // value namespaces. The privacy information is aware of this, but the
791 // def map is not. Therefore the names we work out below will not always
792 // be accurate and we can get slightly wonky error messages (but type
793 // checking is always correct).
794 match self.tcx.def_map.borrow()[path_id].clone() {
795 def::DefStaticMethod(..) => ck("static method"),
796 def::DefFn(..) => ck("function"),
797 def::DefStatic(..) => ck("static"),
798 def::DefConst(..) => ck("const"),
799 def::DefVariant(..) => ck("variant"),
800 def::DefTy(_, false) => ck("type"),
801 def::DefTy(_, true) => ck("enum"),
802 def::DefTrait(..) => ck("trait"),
803 def::DefStruct(..) => ck("struct"),
804 def::DefMethod(_, Some(..), _) => ck("trait method"),
805 def::DefMethod(..) => ck("method"),
806 def::DefMod(..) => ck("module"),
811 // Checks that a method is in scope.
812 fn check_method(&mut self, span: Span, origin: &MethodOrigin,
815 MethodStatic(method_id) => {
816 self.check_static_method(span, method_id, ident)
818 MethodStaticUnboxedClosure(_) => {}
819 // Trait methods are always all public. The only controlling factor
820 // is whether the trait itself is accessible or not.
821 MethodTypeParam(MethodParam { ref trait_ref, .. }) |
822 MethodTraitObject(MethodObject { ref trait_ref, .. }) => {
823 self.report_error(self.ensure_public(span, trait_ref.def_id,
824 None, "source trait"));
830 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
831 fn visit_item(&mut self, item: &ast::Item) {
832 let orig_curitem = replace(&mut self.curitem, item.id);
833 visit::walk_item(self, item);
834 self.curitem = orig_curitem;
837 fn visit_expr(&mut self, expr: &ast::Expr) {
839 ast::ExprField(ref base, ident) => {
840 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
841 self.check_field(expr.span, id, NamedField(ident.node));
844 ast::ExprTupField(ref base, idx) => {
845 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
846 self.check_field(expr.span, id, UnnamedField(idx.node));
849 ast::ExprMethodCall(ident, _, _) => {
850 let method_call = MethodCall::expr(expr.id);
851 match self.tcx.method_map.borrow().get(&method_call) {
853 self.tcx.sess.span_bug(expr.span,
854 "method call not in \
858 debug!("(privacy checking) checking impl method");
859 self.check_method(expr.span, &method.origin, ident.node);
863 ast::ExprStruct(_, ref fields, _) => {
864 match ty::expr_ty(self.tcx, expr).sty {
865 ty::ty_struct(id, _) => {
866 for field in (*fields).iter() {
867 self.check_field(expr.span, id,
868 NamedField(field.ident.node));
871 ty::ty_enum(_, _) => {
872 match self.tcx.def_map.borrow()[expr.id].clone() {
873 def::DefVariant(_, variant_id, _) => {
874 for field in fields.iter() {
875 self.check_field(expr.span, variant_id,
876 NamedField(field.ident.node));
879 _ => self.tcx.sess.span_bug(expr.span,
886 _ => self.tcx.sess.span_bug(expr.span, "struct expr \
891 ast::ExprPath(_) | ast::ExprQPath(_) => {
892 let guard = |&: did: ast::DefId| {
893 let fields = ty::lookup_struct_fields(self.tcx, did);
894 let any_priv = fields.iter().any(|f| {
895 f.vis != ast::Public && (
897 !self.private_accessible(f.id.node))
900 self.tcx.sess.span_err(expr.span,
901 "cannot invoke tuple struct constructor \
902 with private fields");
905 match self.tcx.def_map.borrow().get(&expr.id) {
906 Some(&def::DefStruct(did)) => {
907 guard(if is_local(did) {
908 local_def(self.tcx.map.get_parent(did.node))
910 // "tuple structs" with zero fields (such as
911 // `pub struct Foo;`) don't have a ctor_id, hence
912 // the unwrap_or to the same struct id.
914 csearch::get_tuple_struct_definition_if_ctor(
915 &self.tcx.sess.cstore, did);
916 maybe_did.unwrap_or(did)
925 visit::walk_expr(self, expr);
928 fn visit_view_item(&mut self, a: &ast::ViewItem) {
930 ast::ViewItemExternCrate(..) => {}
931 ast::ViewItemUse(ref vpath) => {
933 ast::ViewPathSimple(..) | ast::ViewPathGlob(..) => {}
934 ast::ViewPathList(ref prefix, ref list, _) => {
935 for pid in list.iter() {
937 ast::PathListIdent { id, name } => {
938 debug!("privacy - ident item {}", id);
939 let seg = ast::PathSegment {
941 parameters: ast::PathParameters::none(),
943 let segs = vec![seg];
944 let path = ast::Path {
949 self.check_path(pid.span, id, &path);
951 ast::PathListMod { id } => {
952 debug!("privacy - mod item {}", id);
953 self.check_path(pid.span, id, prefix);
961 visit::walk_view_item(self, a);
964 fn visit_pat(&mut self, pattern: &ast::Pat) {
965 // Foreign functions do not have their patterns mapped in the def_map,
966 // and there's nothing really relevant there anyway, so don't bother
967 // checking privacy. If you can name the type then you can pass it to an
968 // external C function anyway.
969 if self.in_foreign { return }
972 ast::PatStruct(_, ref fields, _) => {
973 match ty::pat_ty(self.tcx, pattern).sty {
974 ty::ty_struct(id, _) => {
975 for field in fields.iter() {
976 self.check_field(pattern.span, id,
977 NamedField(field.node.ident));
980 ty::ty_enum(_, _) => {
981 match self.tcx.def_map.borrow().get(&pattern.id) {
982 Some(&def::DefVariant(_, variant_id, _)) => {
983 for field in fields.iter() {
984 self.check_field(pattern.span, variant_id,
985 NamedField(field.node.ident));
988 _ => self.tcx.sess.span_bug(pattern.span,
995 _ => self.tcx.sess.span_bug(pattern.span,
996 "struct pattern didn't have \
1001 // Patterns which bind no fields are allowable (the path is check
1003 ast::PatEnum(_, Some(ref fields)) => {
1004 match ty::pat_ty(self.tcx, pattern).sty {
1005 ty::ty_struct(id, _) => {
1006 for (i, field) in fields.iter().enumerate() {
1007 if let ast::PatWild(..) = field.node {
1010 self.check_field(field.span, id, UnnamedField(i));
1013 ty::ty_enum(..) => {
1014 // enum fields have no privacy at this time
1023 visit::walk_pat(self, pattern);
1026 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
1027 self.in_foreign = true;
1028 visit::walk_foreign_item(self, fi);
1029 self.in_foreign = false;
1032 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
1033 self.check_path(path.span, id, path);
1034 visit::walk_path(self, path);
1038 ////////////////////////////////////////////////////////////////////////////////
1039 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1040 ////////////////////////////////////////////////////////////////////////////////
1042 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1043 tcx: &'a ty::ctxt<'tcx>,
1047 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1048 fn visit_item(&mut self, item: &ast::Item) {
1050 self.check_all_inherited(item);
1052 self.check_sane_privacy(item);
1055 let in_fn = self.in_fn;
1056 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1057 ast::ItemMod(..) => false, // modules turn privacy back on
1058 _ => in_fn, // otherwise we inherit
1060 visit::walk_item(self, item);
1061 self.in_fn = orig_in_fn;
1064 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1065 b: &'v ast::Block, s: Span, _: ast::NodeId) {
1066 // This catches both functions and methods
1067 let orig_in_fn = replace(&mut self.in_fn, true);
1068 visit::walk_fn(self, fk, fd, b, s);
1069 self.in_fn = orig_in_fn;
1072 fn visit_view_item(&mut self, i: &ast::ViewItem) {
1074 ast::Inherited => {}
1077 self.tcx.sess.span_err(i.span, "unnecessary `pub`, imports \
1078 in functions are never \
1080 } else if let ast::ViewItemExternCrate(..) = i.node {
1081 self.tcx.sess.span_err(i.span, "`pub` visibility \
1086 visit::walk_view_item(self, i);
1090 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1091 /// Validates all of the visibility qualifiers placed on the item given. This
1092 /// ensures that there are no extraneous qualifiers that don't actually do
1093 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1094 /// later on down the road...
1095 fn check_sane_privacy(&self, item: &ast::Item) {
1097 let check_inherited = |&: sp: Span, vis: ast::Visibility, note: &str| {
1098 if vis != ast::Inherited {
1099 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1101 tcx.sess.span_note(sp, note);
1106 // implementations of traits don't need visibility qualifiers because
1107 // that's controlled by having the trait in scope.
1108 ast::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1109 check_inherited(item.span, item.vis,
1110 "visibility qualifiers have no effect on trait \
1112 for impl_item in impl_items.iter() {
1114 ast::MethodImplItem(ref m) => {
1115 check_inherited(m.span, m.pe_vis(), "");
1117 ast::TypeImplItem(_) => {}
1122 ast::ItemImpl(..) => {
1123 check_inherited(item.span, item.vis,
1124 "place qualifiers on individual methods instead");
1126 ast::ItemForeignMod(..) => {
1127 check_inherited(item.span, item.vis,
1128 "place qualifiers on individual functions \
1132 ast::ItemEnum(ref def, _) => {
1133 for v in def.variants.iter() {
1136 if item.vis == ast::Public {
1137 tcx.sess.span_err(v.span, "unnecessary `pub` \
1141 ast::Inherited => {}
1146 ast::ItemTrait(_, _, _, ref methods) => {
1147 for m in methods.iter() {
1149 ast::ProvidedMethod(ref m) => {
1150 check_inherited(m.span, m.pe_vis(),
1151 "unnecessary visibility");
1153 ast::RequiredMethod(ref m) => {
1154 check_inherited(m.span, m.vis,
1155 "unnecessary visibility");
1157 ast::TypeTraitItem(_) => {}
1162 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemStruct(..) |
1163 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1164 ast::ItemMac(..) => {}
1168 /// When inside of something like a function or a method, visibility has no
1169 /// control over anything so this forbids any mention of any visibility
1170 fn check_all_inherited(&self, item: &ast::Item) {
1172 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
1173 if vis != ast::Inherited {
1174 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1177 let check_struct = |&: def: &ast::StructDef| {
1178 for f in def.fields.iter() {
1180 ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
1181 ast::UnnamedField(..) => {}
1185 check_inherited(tcx, item.span, item.vis);
1187 ast::ItemImpl(_, _, _, _, _, ref impl_items) => {
1188 for impl_item in impl_items.iter() {
1190 ast::MethodImplItem(ref m) => {
1191 check_inherited(tcx, m.span, m.pe_vis());
1193 ast::TypeImplItem(_) => {}
1197 ast::ItemForeignMod(ref fm) => {
1198 for i in fm.items.iter() {
1199 check_inherited(tcx, i.span, i.vis);
1202 ast::ItemEnum(ref def, _) => {
1203 for v in def.variants.iter() {
1204 check_inherited(tcx, v.span, v.node.vis);
1208 ast::ItemStruct(ref def, _) => check_struct(&**def),
1210 ast::ItemTrait(_, _, _, ref methods) => {
1211 for m in methods.iter() {
1213 ast::RequiredMethod(..) => {}
1214 ast::ProvidedMethod(ref m) => check_inherited(tcx, m.span,
1216 ast::TypeTraitItem(_) => {}
1221 ast::ItemStatic(..) | ast::ItemConst(..) |
1222 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1223 ast::ItemMac(..) => {}
1228 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1229 tcx: &'a ty::ctxt<'tcx>,
1230 exported_items: &'a ExportedItems,
1231 public_items: &'a PublicItems,
1235 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1236 inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1237 /// whether the type refers to private types.
1238 contains_private: bool,
1239 /// whether we've recurred at all (i.e. if we're pointing at the
1240 /// first type on which visit_ty was called).
1241 at_outer_type: bool,
1242 // whether that first type is a public path.
1243 outer_type_is_public_path: bool,
1246 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1247 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1248 let did = match self.tcx.def_map.borrow().get(&path_id).cloned() {
1249 // `int` etc. (None doesn't seem to occur.)
1250 None | Some(def::DefPrimTy(..)) => return false,
1251 Some(def) => def.def_id()
1253 // A path can only be private if:
1254 // it's in this crate...
1258 // .. and it corresponds to a private type in the AST (this returns
1259 // None for type parameters)
1260 match self.tcx.map.find(did.node) {
1261 Some(ast_map::NodeItem(ref item)) => item.vis != ast::Public,
1262 Some(_) | None => false,
1266 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1267 // FIXME: this would preferably be using `exported_items`, but all
1268 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1269 self.public_items.contains(&trait_id)
1272 fn check_ty_param_bound(&self,
1273 ty_param_bound: &ast::TyParamBound) {
1274 if let ast::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1275 if !self.tcx.sess.features.borrow().visible_private_types &&
1276 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1277 let span = trait_ref.trait_ref.path.span;
1278 self.tcx.sess.span_err(span,
1279 "private trait in exported type \
1286 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1287 fn visit_ty(&mut self, ty: &ast::Ty) {
1288 if let ast::TyPath(_, path_id) = ty.node {
1289 if self.inner.path_is_private_type(path_id) {
1290 self.contains_private = true;
1291 // found what we're looking for so let's stop
1294 } else if self.at_outer_type {
1295 self.outer_type_is_public_path = true;
1298 self.at_outer_type = false;
1299 visit::walk_ty(self, ty)
1302 // don't want to recurse into [, .. expr]
1303 fn visit_expr(&mut self, _: &ast::Expr) {}
1306 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1307 fn visit_item(&mut self, item: &ast::Item) {
1309 // contents of a private mod can be reexported, so we need
1310 // to check internals.
1311 ast::ItemMod(_) => {}
1313 // An `extern {}` doesn't introduce a new privacy
1314 // namespace (the contents have their own privacies).
1315 ast::ItemForeignMod(_) => {}
1317 ast::ItemTrait(_, _, ref bounds, _) => {
1318 if !self.trait_is_public(item.id) {
1322 for bound in bounds.iter() {
1323 self.check_ty_param_bound(bound)
1327 // impls need some special handling to try to offer useful
1328 // error messages without (too many) false positives
1329 // (i.e. we could just return here to not check them at
1330 // all, or some worse estimation of whether an impl is
1331 // publicly visible.
1332 ast::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1333 // `impl [... for] Private` is never visible.
1334 let self_contains_private;
1335 // impl [... for] Public<...>, but not `impl [... for]
1336 // ~[Public]` or `(Public,)` etc.
1337 let self_is_public_path;
1339 // check the properties of the Self type:
1341 let mut visitor = CheckTypeForPrivatenessVisitor {
1343 contains_private: false,
1344 at_outer_type: true,
1345 outer_type_is_public_path: false,
1347 visitor.visit_ty(&**self_);
1348 self_contains_private = visitor.contains_private;
1349 self_is_public_path = visitor.outer_type_is_public_path;
1352 // miscellaneous info about the impl
1354 // `true` iff this is `impl Private for ...`.
1355 let not_private_trait =
1356 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1358 let did = ty::trait_ref_to_def_id(self.tcx, tr);
1360 !is_local(did) || self.trait_is_public(did.node)
1363 // `true` iff this is a trait impl or at least one method is public.
1365 // `impl Public { $( fn ...() {} )* }` is not visible.
1367 // This is required over just using the methods' privacy
1368 // directly because we might have `impl<T: Foo<Private>> ...`,
1369 // and we shouldn't warn about the generics if all the methods
1370 // are private (because `T` won't be visible externally).
1371 let trait_or_some_public_method =
1372 trait_ref.is_some() ||
1376 ast::MethodImplItem(ref m) => {
1377 self.exported_items.contains(&m.id)
1379 ast::TypeImplItem(_) => false,
1383 if !self_contains_private &&
1384 not_private_trait &&
1385 trait_or_some_public_method {
1387 visit::walk_generics(self, g);
1391 for impl_item in impl_items.iter() {
1393 ast::MethodImplItem(ref method) => {
1394 visit::walk_method_helper(self, &**method)
1396 ast::TypeImplItem(_) => {}
1401 // Any private types in a trait impl fall into two
1403 // 1. mentioned in the trait definition
1404 // 2. mentioned in the type params/generics
1406 // Those in 1. can only occur if the trait is in
1407 // this crate and will've been warned about on the
1408 // trait definition (there's no need to warn twice
1409 // so we don't check the methods).
1411 // Those in 2. are warned via walk_generics and this
1413 self.visit_trait_ref(tr)
1416 } else if trait_ref.is_none() && self_is_public_path {
1417 // impl Public<Private> { ... }. Any public static
1418 // methods will be visible as `Public::foo`.
1419 let mut found_pub_static = false;
1420 for impl_item in impl_items.iter() {
1422 ast::MethodImplItem(ref method) => {
1423 if method.pe_explicit_self().node ==
1426 .contains(&method.id) {
1427 found_pub_static = true;
1428 visit::walk_method_helper(self, &**method);
1431 ast::TypeImplItem(_) => {}
1434 if found_pub_static {
1435 visit::walk_generics(self, g)
1441 // `type ... = ...;` can contain private types, because
1442 // we're introducing a new name.
1443 ast::ItemTy(..) => return,
1445 // not at all public, so we don't care
1446 _ if !self.exported_items.contains(&item.id) => return,
1451 // we've carefully constructed it so that if we're here, then
1452 // any `visit_ty`'s will be called on things that are in
1453 // public signatures, i.e. things that we're interested in for
1455 visit::walk_item(self, item);
1458 fn visit_generics(&mut self, generics: &ast::Generics) {
1459 for ty_param in generics.ty_params.iter() {
1460 for bound in ty_param.bounds.iter() {
1461 self.check_ty_param_bound(bound)
1464 for predicate in generics.where_clause.predicates.iter() {
1466 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
1467 for bound in bound_pred.bounds.iter() {
1468 self.check_ty_param_bound(bound)
1471 &ast::WherePredicate::RegionPredicate(_) => {}
1472 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
1473 self.visit_ty(&*eq_pred.ty);
1479 fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
1480 if self.exported_items.contains(&item.id) {
1481 visit::walk_foreign_item(self, item)
1485 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1486 b: &'v ast::Block, s: Span, id: ast::NodeId) {
1487 // needs special handling for methods.
1488 if self.exported_items.contains(&id) {
1489 visit::walk_fn(self, fk, fd, b, s);
1493 fn visit_ty(&mut self, t: &ast::Ty) {
1494 if let ast::TyPath(ref p, path_id) = t.node {
1495 if !self.tcx.sess.features.borrow().visible_private_types &&
1496 self.path_is_private_type(path_id) {
1497 self.tcx.sess.span_err(p.span,
1498 "private type in exported type signature");
1501 visit::walk_ty(self, t)
1504 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
1505 if self.exported_items.contains(&v.node.id) {
1506 self.in_variant = true;
1507 visit::walk_variant(self, v, g);
1508 self.in_variant = false;
1512 fn visit_struct_field(&mut self, s: &ast::StructField) {
1514 ast::NamedField(_, vis) if vis == ast::Public || self.in_variant => {
1515 visit::walk_struct_field(self, s);
1522 // we don't need to introspect into these at all: an
1523 // expression/block context can't possibly contain exported
1524 // things, and neither do view_items. (Making them no-ops stops us
1525 // from traversing the whole AST without having to be super
1526 // careful about our `walk_...` calls above.)
1527 fn visit_view_item(&mut self, _: &ast::ViewItem) {}
1528 fn visit_block(&mut self, _: &ast::Block) {}
1529 fn visit_expr(&mut self, _: &ast::Expr) {}
1532 pub fn check_crate(tcx: &ty::ctxt,
1533 export_map: &def::ExportMap,
1534 external_exports: ExternalExports,
1535 last_private_map: LastPrivateMap)
1536 -> (ExportedItems, PublicItems) {
1537 let krate = tcx.map.krate();
1539 // Figure out who everyone's parent is
1540 let mut visitor = ParentVisitor {
1541 parents: NodeMap::new(),
1542 curparent: ast::DUMMY_NODE_ID,
1544 visit::walk_crate(&mut visitor, krate);
1546 // Use the parent map to check the privacy of everything
1547 let mut visitor = PrivacyVisitor {
1548 curitem: ast::DUMMY_NODE_ID,
1551 parents: visitor.parents,
1552 external_exports: external_exports,
1553 last_private_map: last_private_map,
1555 visit::walk_crate(&mut visitor, krate);
1557 // Sanity check to make sure that all privacy usage and controls are
1559 let mut visitor = SanePrivacyVisitor {
1563 visit::walk_crate(&mut visitor, krate);
1565 tcx.sess.abort_if_errors();
1567 // Build up a set of all exported items in the AST. This is a set of all
1568 // items which are reachable from external crates based on visibility.
1569 let mut visitor = EmbargoVisitor {
1571 exported_items: NodeSet::new(),
1572 public_items: NodeSet::new(),
1573 reexports: NodeSet::new(),
1574 export_map: export_map,
1575 prev_exported: true,
1579 let before = visitor.exported_items.len();
1580 visit::walk_crate(&mut visitor, krate);
1581 if before == visitor.exported_items.len() {
1586 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1589 let mut visitor = VisiblePrivateTypesVisitor {
1591 exported_items: &exported_items,
1592 public_items: &public_items,
1595 visit::walk_crate(&mut visitor, krate);
1597 return (exported_items, public_items);