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"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17 html_root_url = "https://doc.rust-lang.org/nightly/")]
19 #![feature(rustc_diagnostic_macros)]
20 #![feature(rustc_private)]
21 #![feature(staged_api)]
23 #[macro_use] extern crate log;
24 #[macro_use] extern crate syntax;
27 extern crate rustc_front;
29 use self::PrivacyResult::*;
30 use self::FieldName::*;
33 use std::mem::replace;
36 use rustc_front::intravisit::{self, Visitor};
39 use rustc::middle::def;
40 use rustc::middle::def_id::DefId;
41 use rustc::middle::privacy::{AccessLevel, AccessLevels};
42 use rustc::middle::privacy::ImportUse::*;
43 use rustc::middle::privacy::LastPrivate::*;
44 use rustc::middle::privacy::PrivateDep::*;
45 use rustc::middle::privacy::ExternalExports;
46 use rustc::middle::ty;
47 use rustc::util::nodemap::{NodeMap, NodeSet};
48 use rustc::front::map as ast_map;
51 use syntax::codemap::Span;
55 type Context<'a, 'tcx> = (&'a ty::MethodMap<'tcx>, &'a def::ExportMap);
57 /// Result of a checking operation - None => no errors were found. Some => an
58 /// error and contains the span and message for reporting that error and
59 /// optionally the same for a note about the error.
60 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
62 ////////////////////////////////////////////////////////////////////////////////
63 /// The parent visitor, used to determine what's the parent of what (node-wise)
64 ////////////////////////////////////////////////////////////////////////////////
66 struct ParentVisitor<'a, 'tcx:'a> {
67 tcx: &'a ty::ctxt<'tcx>,
68 parents: NodeMap<ast::NodeId>,
69 curparent: ast::NodeId,
72 impl<'a, 'tcx, 'v> Visitor<'v> for ParentVisitor<'a, 'tcx> {
73 /// We want to visit items in the context of their containing
74 /// module and so forth, so supply a crate for doing a deep walk.
75 fn visit_nested_item(&mut self, item: hir::ItemId) {
76 self.visit_item(self.tcx.map.expect_item(item.id))
78 fn visit_item(&mut self, item: &hir::Item) {
79 self.parents.insert(item.id, self.curparent);
81 let prev = self.curparent;
83 hir::ItemMod(..) => { self.curparent = item.id; }
84 // Enum variants are parented to the enum definition itself because
85 // they inherit privacy
86 hir::ItemEnum(ref def, _) => {
87 for variant in &def.variants {
88 // The parent is considered the enclosing enum because the
89 // enum will dictate the privacy visibility of this variant
91 self.parents.insert(variant.node.data.id(), item.id);
95 // Trait methods are always considered "public", but if the trait is
96 // private then we need some private item in the chain from the
97 // method to the root. In this case, if the trait is private, then
98 // parent all the methods to the trait to indicate that they're
100 hir::ItemTrait(_, _, _, ref trait_items) if item.vis != hir::Public => {
101 for trait_item in trait_items {
102 self.parents.insert(trait_item.id, item.id);
108 intravisit::walk_item(self, item);
109 self.curparent = prev;
112 fn visit_foreign_item(&mut self, a: &hir::ForeignItem) {
113 self.parents.insert(a.id, self.curparent);
114 intravisit::walk_foreign_item(self, a);
117 fn visit_fn(&mut self, a: intravisit::FnKind<'v>, b: &'v hir::FnDecl,
118 c: &'v hir::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 intravisit::walk_fn(self, a, b, c, d);
128 fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) {
129 // visit_fn handles methods, but associated consts have to be handled
131 if !self.parents.contains_key(&ii.id) {
132 self.parents.insert(ii.id, self.curparent);
134 intravisit::walk_impl_item(self, ii);
137 fn visit_variant_data(&mut self, s: &hir::VariantData, _: ast::Name,
138 _: &'v hir::Generics, item_id: ast::NodeId, _: Span) {
139 // Struct constructors are parented to their struct definitions because
140 // they essentially are the struct definitions.
142 self.parents.insert(s.id(), item_id);
145 // While we have the id of the struct definition, go ahead and parent
147 for field in s.fields() {
148 self.parents.insert(field.node.id, self.curparent);
150 intravisit::walk_struct_def(self, s)
154 ////////////////////////////////////////////////////////////////////////////////
155 /// The embargo visitor, used to determine the exports of the ast
156 ////////////////////////////////////////////////////////////////////////////////
158 struct EmbargoVisitor<'a, 'tcx: 'a> {
159 tcx: &'a ty::ctxt<'tcx>,
160 export_map: &'a def::ExportMap,
162 // Accessibility levels for reachable nodes
163 access_levels: AccessLevels,
164 // Previous accessibility level, None means unreachable
165 prev_level: Option<AccessLevel>,
166 // Have something changed in the level map?
170 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
171 fn ty_level(&self, ty: &hir::Ty) -> Option<AccessLevel> {
172 if let hir::TyPath(..) = ty.node {
173 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
174 def::DefPrimTy(..) | def::DefSelfTy(..) | def::DefTyParam(..) => {
175 Some(AccessLevel::Public)
178 if let Some(node_id) = self.tcx.map.as_local_node_id(def.def_id()) {
181 Some(AccessLevel::Public)
186 Some(AccessLevel::Public)
190 fn trait_level(&self, trait_ref: &hir::TraitRef) -> Option<AccessLevel> {
191 let did = self.tcx.trait_ref_to_def_id(trait_ref);
192 if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
195 Some(AccessLevel::Public)
199 fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
200 self.access_levels.map.get(&id).cloned()
203 // Updates node level and returns the updated level
204 fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
205 let old_level = self.get(id);
206 // Accessibility levels can only grow
207 if level > old_level {
208 self.access_levels.map.insert(id, level.unwrap());
217 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
218 /// We want to visit items in the context of their containing
219 /// module and so forth, so supply a crate for doing a deep walk.
220 fn visit_nested_item(&mut self, item: hir::ItemId) {
221 self.visit_item(self.tcx.map.expect_item(item.id))
224 fn visit_item(&mut self, item: &hir::Item) {
225 let inherited_item_level = match item.node {
226 // Impls inherit level from their types and traits
227 hir::ItemImpl(_, _, _, None, ref ty, _) => {
230 hir::ItemImpl(_, _, _, Some(ref trait_ref), ref ty, _) => {
231 cmp::min(self.ty_level(&ty), self.trait_level(trait_ref))
233 hir::ItemDefaultImpl(_, ref trait_ref) => {
234 self.trait_level(trait_ref)
236 // Foreign mods inherit level from parents
237 hir::ItemForeignMod(..) => {
240 // Other `pub` items inherit levels from parents
242 if item.vis == hir::Public { self.prev_level } else { None }
246 // Update id of the item itself
247 let item_level = self.update(item.id, inherited_item_level);
249 // Update ids of nested things
251 hir::ItemEnum(ref def, _) => {
252 for variant in &def.variants {
253 let variant_level = self.update(variant.node.data.id(), item_level);
254 for field in variant.node.data.fields() {
255 self.update(field.node.id, variant_level);
259 hir::ItemImpl(_, _, _, None, _, ref impl_items) => {
260 for impl_item in impl_items {
261 if impl_item.vis == hir::Public {
262 self.update(impl_item.id, item_level);
266 hir::ItemImpl(_, _, _, Some(_), _, ref impl_items) => {
267 for impl_item in impl_items {
268 self.update(impl_item.id, item_level);
271 hir::ItemTrait(_, _, _, ref trait_items) => {
272 for trait_item in trait_items {
273 self.update(trait_item.id, item_level);
276 hir::ItemStruct(ref def, _) => {
277 if !def.is_struct() {
278 self.update(def.id(), item_level);
280 for field in def.fields() {
281 if field.node.kind.visibility() == hir::Public {
282 self.update(field.node.id, item_level);
286 hir::ItemForeignMod(ref foreign_mod) => {
287 for foreign_item in &foreign_mod.items {
288 if foreign_item.vis == hir::Public {
289 self.update(foreign_item.id, item_level);
293 hir::ItemTy(ref ty, _) if item_level.is_some() => {
294 if let hir::TyPath(..) = ty.node {
295 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
296 def::DefPrimTy(..) | def::DefSelfTy(..) | def::DefTyParam(..) => {},
298 if let Some(node_id) = self.tcx.map.as_local_node_id(def.def_id()) {
299 self.update(node_id, Some(AccessLevel::Reachable));
308 let orig_level = self.prev_level;
309 self.prev_level = item_level;
311 intravisit::walk_item(self, item);
313 self.prev_level = orig_level;
316 fn visit_block(&mut self, b: &'v hir::Block) {
317 let orig_level = replace(&mut self.prev_level, None);
319 // Blocks can have public items, for example impls, but they always
320 // start as completely private regardless of publicity of a function,
321 // constant, type, field, etc. in which this block resides
322 intravisit::walk_block(self, b);
324 self.prev_level = orig_level;
327 fn visit_mod(&mut self, m: &hir::Mod, _sp: Span, id: ast::NodeId) {
328 // This code is here instead of in visit_item so that the
329 // crate module gets processed as well.
330 if self.prev_level.is_some() {
331 for export in self.export_map.get(&id).expect("module isn't found in export map") {
332 if let Some(node_id) = self.tcx.map.as_local_node_id(export.def_id) {
333 self.update(node_id, Some(AccessLevel::Exported));
338 intravisit::walk_mod(self, m);
341 fn visit_macro_def(&mut self, md: &'v hir::MacroDef) {
342 self.update(md.id, Some(AccessLevel::Public));
346 ////////////////////////////////////////////////////////////////////////////////
347 /// The privacy visitor, where privacy checks take place (violations reported)
348 ////////////////////////////////////////////////////////////////////////////////
350 struct PrivacyVisitor<'a, 'tcx: 'a> {
351 tcx: &'a ty::ctxt<'tcx>,
352 curitem: ast::NodeId,
354 parents: NodeMap<ast::NodeId>,
355 external_exports: ExternalExports,
362 DisallowedBy(ast::NodeId),
366 UnnamedField(usize), // index
367 NamedField(ast::Name),
370 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
371 // used when debugging
372 fn nodestr(&self, id: ast::NodeId) -> String {
373 self.tcx.map.node_to_string(id).to_string()
376 // Determines whether the given definition is public from the point of view
377 // of the current item.
378 fn def_privacy(&self, did: DefId) -> PrivacyResult {
379 let node_id = if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
382 if self.external_exports.contains(&did) {
383 debug!("privacy - {:?} was externally exported", did);
386 debug!("privacy - is {:?} a public method", did);
388 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
389 Some(&ty::ConstTraitItem(ref ac)) => {
390 debug!("privacy - it's a const: {:?}", *ac);
392 ty::TraitContainer(id) => {
393 debug!("privacy - recursing on trait {:?}", id);
396 ty::ImplContainer(id) => {
397 match self.tcx.impl_trait_ref(id) {
399 debug!("privacy - impl of trait {:?}", id);
400 self.def_privacy(t.def_id)
403 debug!("privacy - found inherent \
404 associated constant {:?}",
406 if ac.vis == hir::Public {
416 Some(&ty::MethodTraitItem(ref meth)) => {
417 debug!("privacy - well at least it's a method: {:?}",
419 match meth.container {
420 ty::TraitContainer(id) => {
421 debug!("privacy - recursing on trait {:?}", id);
424 ty::ImplContainer(id) => {
425 match self.tcx.impl_trait_ref(id) {
427 debug!("privacy - impl of trait {:?}", id);
428 self.def_privacy(t.def_id)
431 debug!("privacy - found a method {:?}",
433 if meth.vis == hir::Public {
443 Some(&ty::TypeTraitItem(ref typedef)) => {
444 match typedef.container {
445 ty::TraitContainer(id) => {
446 debug!("privacy - recursing on trait {:?}", id);
449 ty::ImplContainer(id) => {
450 match self.tcx.impl_trait_ref(id) {
452 debug!("privacy - impl of trait {:?}", id);
453 self.def_privacy(t.def_id)
456 debug!("privacy - found a typedef {:?}",
458 if typedef.vis == hir::Public {
469 debug!("privacy - nope, not even a method");
475 debug!("privacy - local {} not public all the way down",
476 self.tcx.map.node_to_string(node_id));
477 // return quickly for things in the same module
478 if self.parents.get(&node_id) == self.parents.get(&self.curitem) {
479 debug!("privacy - same parent, we're done here");
483 // We now know that there is at least one private member between the
484 // destination and the root.
485 let mut closest_private_id = node_id;
487 debug!("privacy - examining {}", self.nodestr(closest_private_id));
488 let vis = match self.tcx.map.find(closest_private_id) {
489 // If this item is a method, then we know for sure that it's an
490 // actual method and not a static method. The reason for this is
491 // that these cases are only hit in the ExprMethodCall
492 // expression, and ExprCall will have its path checked later
493 // (the path of the trait/impl) if it's a static method.
495 // With this information, then we can completely ignore all
496 // trait methods. The privacy violation would be if the trait
497 // couldn't get imported, not if the method couldn't be used
498 // (all trait methods are public).
500 // However, if this is an impl method, then we dictate this
501 // decision solely based on the privacy of the method
503 // FIXME(#10573) is this the right behavior? Why not consider
504 // where the method was defined?
505 Some(ast_map::NodeImplItem(ii)) => {
507 hir::ImplItemKind::Const(..) |
508 hir::ImplItemKind::Method(..) => {
509 let imp = self.tcx.map
510 .get_parent_did(closest_private_id);
511 match self.tcx.impl_trait_ref(imp) {
512 Some(..) => return Allowable,
513 _ if ii.vis == hir::Public => {
519 hir::ImplItemKind::Type(_) => return Allowable,
522 Some(ast_map::NodeTraitItem(_)) => {
526 // This is not a method call, extract the visibility as one
527 // would normally look at it
528 Some(ast_map::NodeItem(it)) => it.vis,
529 Some(ast_map::NodeForeignItem(_)) => {
530 self.tcx.map.get_foreign_vis(closest_private_id)
532 Some(ast_map::NodeVariant(..)) => {
533 hir::Public // need to move up a level (to the enum)
537 if vis != hir::Public { break }
538 // if we've reached the root, then everything was allowable and this
540 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
541 closest_private_id = *self.parents.get(&closest_private_id).unwrap();
543 // If we reached the top, then we were public all the way down and
544 // we can allow this access.
545 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
547 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
548 if self.private_accessible(closest_private_id) {
551 DisallowedBy(closest_private_id)
555 /// True if `id` is both local and private-accessible
556 fn local_private_accessible(&self, did: DefId) -> bool {
557 if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
558 self.private_accessible(node_id)
564 /// For a local private node in the AST, this function will determine
565 /// whether the node is accessible by the current module that iteration is
567 fn private_accessible(&self, id: ast::NodeId) -> bool {
568 let parent = *self.parents.get(&id).unwrap();
569 debug!("privacy - accessible parent {}", self.nodestr(parent));
571 // After finding `did`'s closest private member, we roll ourselves back
572 // to see if this private member's parent is anywhere in our ancestry.
573 // By the privacy rules, we can access all of our ancestor's private
574 // members, so that's why we test the parent, and not the did itself.
575 let mut cur = self.curitem;
577 debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
579 // If the relevant parent is in our history, then we're allowed
580 // to look inside any of our ancestor's immediate private items,
581 // so this access is valid.
582 x if x == parent => return true,
584 // If we've reached the root, then we couldn't access this item
585 // in the first place
586 ast::DUMMY_NODE_ID => return false,
592 cur = *self.parents.get(&cur).unwrap();
596 fn report_error(&self, result: CheckResult) -> bool {
599 Some((span, msg, note)) => {
600 self.tcx.sess.span_err(span, &msg[..]);
602 Some((span, msg)) => {
603 self.tcx.sess.span_note(span, &msg[..])
612 /// Guarantee that a particular definition is public. Returns a CheckResult
613 /// which contains any errors found. These can be reported using `report_error`.
614 /// If the result is `None`, no errors were found.
615 fn ensure_public(&self,
618 source_did: Option<DefId>,
621 debug!("ensure_public(span={:?}, to_check={:?}, source_did={:?}, msg={:?})",
622 span, to_check, source_did, msg);
623 let def_privacy = self.def_privacy(to_check);
624 debug!("ensure_public: def_privacy={:?}", def_privacy);
625 let id = match def_privacy {
626 ExternallyDenied => {
627 return Some((span, format!("{} is private", msg), None))
629 Allowable => return None,
630 DisallowedBy(id) => id,
633 // If we're disallowed by a particular id, then we attempt to
634 // give a nice error message to say why it was disallowed. It
635 // was either because the item itself is private or because
636 // its parent is private and its parent isn't in our
637 // ancestry. (Both the item being checked and its parent must
639 let def_id = source_did.unwrap_or(to_check);
640 let node_id = self.tcx.map.as_local_node_id(def_id);
641 let (err_span, err_msg) = if Some(id) == node_id {
642 return Some((span, format!("{} is private", msg), None));
644 (span, format!("{} is inaccessible", msg))
646 let item = match self.tcx.map.find(id) {
647 Some(ast_map::NodeItem(item)) => {
649 // If an impl disallowed this item, then this is resolve's
650 // way of saying that a struct/enum's static method was
651 // invoked, and the struct/enum itself is private. Crawl
652 // back up the chains to find the relevant struct/enum that
654 hir::ItemImpl(_, _, _, _, ref ty, _) => {
656 hir::TyPath(..) => {}
657 _ => return Some((err_span, err_msg, None)),
659 let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
660 let did = def.def_id();
661 let node_id = self.tcx.map.as_local_node_id(did).unwrap();
662 match self.tcx.map.get(node_id) {
663 ast_map::NodeItem(item) => item,
664 _ => self.tcx.sess.span_bug(item.span,
665 "path is not an item")
671 Some(..) | None => return Some((err_span, err_msg, None)),
673 let desc = match item.node {
674 hir::ItemMod(..) => "module",
675 hir::ItemTrait(..) => "trait",
676 hir::ItemStruct(..) => "struct",
677 hir::ItemEnum(..) => "enum",
678 _ => return Some((err_span, err_msg, None))
680 let msg = format!("{} `{}` is private", desc, item.name);
681 Some((err_span, err_msg, Some((span, msg))))
684 // Checks that a field is in scope.
685 fn check_field(&mut self,
687 def: ty::AdtDef<'tcx>,
688 v: ty::VariantDef<'tcx>,
690 let field = match name {
691 NamedField(f_name) => {
692 debug!("privacy - check named field {} in struct {:?}", f_name, def);
693 v.field_named(f_name)
695 UnnamedField(idx) => &v.fields[idx]
697 if field.vis == hir::Public || self.local_private_accessible(field.did) {
701 let struct_desc = match def.adt_kind() {
702 ty::AdtKind::Struct =>
703 format!("struct `{}`", self.tcx.item_path_str(def.did)),
704 // struct variant fields have inherited visibility
705 ty::AdtKind::Enum => return
707 let msg = match name {
708 NamedField(name) => format!("field `{}` of {} is private",
710 UnnamedField(idx) => format!("field #{} of {} is private",
711 idx + 1, struct_desc),
713 span_err!(self.tcx.sess, span, E0451,
717 // Given the ID of a method, checks to ensure it's in scope.
718 fn check_static_method(&mut self,
722 self.report_error(self.ensure_public(span,
725 &format!("method `{}`",
729 // Checks that a path is in scope.
730 fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Name) {
731 debug!("privacy - path {}", self.nodestr(path_id));
732 let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap();
733 let ck = |tyname: &str| {
734 let ck_public = |def: DefId| {
735 debug!("privacy - ck_public {:?}", def);
736 let origdid = path_res.def_id();
737 self.ensure_public(span,
740 &format!("{} `{}`", tyname, last))
743 match path_res.last_private {
744 LastMod(AllPublic) => {},
745 LastMod(DependsOn(def)) => {
746 self.report_error(ck_public(def));
748 LastImport { value_priv,
749 value_used: check_value,
751 type_used: check_type } => {
752 // This dance with found_error is because we don't want to
753 // report a privacy error twice for the same directive.
754 let found_error = match (type_priv, check_type) {
755 (Some(DependsOn(def)), Used) => {
756 !self.report_error(ck_public(def))
761 match (value_priv, check_value) {
762 (Some(DependsOn(def)), Used) => {
763 self.report_error(ck_public(def));
768 // If an import is not used in either namespace, we still
769 // want to check that it could be legal. Therefore we check
770 // in both namespaces and only report an error if both would
771 // be illegal. We only report one error, even if it is
772 // illegal to import from both namespaces.
773 match (value_priv, check_value, type_priv, check_type) {
774 (Some(p), Unused, None, _) |
775 (None, _, Some(p), Unused) => {
778 DependsOn(def) => ck_public(def),
781 self.report_error(p);
784 (Some(v), Unused, Some(t), Unused) => {
787 DependsOn(def) => ck_public(def),
791 DependsOn(def) => ck_public(def),
793 if let (Some(_), Some(t)) = (v, t) {
794 self.report_error(Some(t));
802 // FIXME(#12334) Imports can refer to definitions in both the type and
803 // value namespaces. The privacy information is aware of this, but the
804 // def map is not. Therefore the names we work out below will not always
805 // be accurate and we can get slightly wonky error messages (but type
806 // checking is always correct).
807 match path_res.full_def() {
808 def::DefFn(..) => ck("function"),
809 def::DefStatic(..) => ck("static"),
810 def::DefConst(..) => ck("const"),
811 def::DefAssociatedConst(..) => ck("associated const"),
812 def::DefVariant(..) => ck("variant"),
813 def::DefTy(_, false) => ck("type"),
814 def::DefTy(_, true) => ck("enum"),
815 def::DefTrait(..) => ck("trait"),
816 def::DefStruct(..) => ck("struct"),
817 def::DefMethod(..) => ck("method"),
818 def::DefMod(..) => ck("module"),
823 // Checks that a method is in scope.
824 fn check_method(&mut self, span: Span, method_def_id: DefId,
826 match self.tcx.impl_or_trait_item(method_def_id).container() {
827 ty::ImplContainer(_) => {
828 self.check_static_method(span, method_def_id, name)
830 // Trait methods are always all public. The only controlling factor
831 // is whether the trait itself is accessible or not.
832 ty::TraitContainer(trait_def_id) => {
833 self.report_error(self.ensure_public(span, trait_def_id,
834 None, "source trait"));
840 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
841 /// We want to visit items in the context of their containing
842 /// module and so forth, so supply a crate for doing a deep walk.
843 fn visit_nested_item(&mut self, item: hir::ItemId) {
844 self.visit_item(self.tcx.map.expect_item(item.id))
847 fn visit_item(&mut self, item: &hir::Item) {
848 let orig_curitem = replace(&mut self.curitem, item.id);
849 intravisit::walk_item(self, item);
850 self.curitem = orig_curitem;
853 fn visit_expr(&mut self, expr: &hir::Expr) {
855 hir::ExprField(ref base, name) => {
856 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
857 self.check_field(expr.span,
859 def.struct_variant(),
860 NamedField(name.node));
863 hir::ExprTupField(ref base, idx) => {
864 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
865 self.check_field(expr.span,
867 def.struct_variant(),
868 UnnamedField(idx.node));
871 hir::ExprMethodCall(name, _, _) => {
872 let method_call = ty::MethodCall::expr(expr.id);
873 let method = self.tcx.tables.borrow().method_map[&method_call];
874 debug!("(privacy checking) checking impl method");
875 self.check_method(expr.span, method.def_id, name.node);
877 hir::ExprStruct(..) => {
878 let adt = self.tcx.expr_ty(expr).ty_adt_def().unwrap();
879 let variant = adt.variant_of_def(self.tcx.resolve_expr(expr));
880 // RFC 736: ensure all unmentioned fields are visible.
881 // Rather than computing the set of unmentioned fields
882 // (i.e. `all_fields - fields`), just check them all.
883 for field in &variant.fields {
884 self.check_field(expr.span, adt, variant, NamedField(field.name));
887 hir::ExprPath(..) => {
889 if let def::DefStruct(_) = self.tcx.resolve_expr(expr) {
890 let expr_ty = self.tcx.expr_ty(expr);
891 let def = match expr_ty.sty {
892 ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
893 output: ty::FnConverging(ty), ..
896 }.ty_adt_def().unwrap();
897 let any_priv = def.struct_variant().fields.iter().any(|f| {
898 f.vis != hir::Public && !self.local_private_accessible(f.did)
901 span_err!(self.tcx.sess, expr.span, E0450,
902 "cannot invoke tuple struct constructor with private \
910 intravisit::walk_expr(self, expr);
913 fn visit_pat(&mut self, pattern: &hir::Pat) {
914 // Foreign functions do not have their patterns mapped in the def_map,
915 // and there's nothing really relevant there anyway, so don't bother
916 // checking privacy. If you can name the type then you can pass it to an
917 // external C function anyway.
918 if self.in_foreign { return }
921 hir::PatStruct(_, ref fields, _) => {
922 let adt = self.tcx.pat_ty(pattern).ty_adt_def().unwrap();
923 let def = self.tcx.def_map.borrow().get(&pattern.id).unwrap().full_def();
924 let variant = adt.variant_of_def(def);
925 for field in fields {
926 self.check_field(pattern.span, adt, variant,
927 NamedField(field.node.name));
931 // Patterns which bind no fields are allowable (the path is check
933 hir::PatEnum(_, Some(ref fields)) => {
934 match self.tcx.pat_ty(pattern).sty {
935 ty::TyStruct(def, _) => {
936 for (i, field) in fields.iter().enumerate() {
937 if let hir::PatWild = field.node {
940 self.check_field(field.span,
942 def.struct_variant(),
947 // enum fields have no privacy at this time
956 intravisit::walk_pat(self, pattern);
959 fn visit_foreign_item(&mut self, fi: &hir::ForeignItem) {
960 self.in_foreign = true;
961 intravisit::walk_foreign_item(self, fi);
962 self.in_foreign = false;
965 fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
966 if !path.segments.is_empty() {
967 self.check_path(path.span, id, path.segments.last().unwrap().identifier.name);
968 intravisit::walk_path(self, path);
972 fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
973 let name = if let hir::PathListIdent { name, .. } = item.node {
975 } else if !prefix.segments.is_empty() {
976 prefix.segments.last().unwrap().identifier.name
978 self.tcx.sess.bug("`self` import in an import list with empty prefix");
980 self.check_path(item.span, item.node.id(), name);
981 intravisit::walk_path_list_item(self, prefix, item);
985 ////////////////////////////////////////////////////////////////////////////////
986 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
987 ////////////////////////////////////////////////////////////////////////////////
989 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
990 tcx: &'a ty::ctxt<'tcx>,
994 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
995 /// We want to visit items in the context of their containing
996 /// module and so forth, so supply a crate for doing a deep walk.
997 fn visit_nested_item(&mut self, item: hir::ItemId) {
998 self.visit_item(self.tcx.map.expect_item(item.id))
1001 fn visit_item(&mut self, item: &hir::Item) {
1002 self.check_sane_privacy(item);
1004 self.check_all_inherited(item);
1007 let orig_in_block = self.in_block;
1009 // Modules turn privacy back on, otherwise we inherit
1010 self.in_block = if let hir::ItemMod(..) = item.node { false } else { orig_in_block };
1012 intravisit::walk_item(self, item);
1013 self.in_block = orig_in_block;
1016 fn visit_block(&mut self, b: &'v hir::Block) {
1017 let orig_in_block = replace(&mut self.in_block, true);
1018 intravisit::walk_block(self, b);
1019 self.in_block = orig_in_block;
1023 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1024 /// Validates all of the visibility qualifiers placed on the item given. This
1025 /// ensures that there are no extraneous qualifiers that don't actually do
1026 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1027 /// later on down the road...
1028 fn check_sane_privacy(&self, item: &hir::Item) {
1029 let check_inherited = |sp, vis, note: &str| {
1030 if vis != hir::Inherited {
1031 span_err!(self.tcx.sess, sp, E0449, "unnecessary visibility qualifier");
1032 if !note.is_empty() {
1033 self.tcx.sess.span_note(sp, note);
1039 // implementations of traits don't need visibility qualifiers because
1040 // that's controlled by having the trait in scope.
1041 hir::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1042 check_inherited(item.span, item.vis,
1043 "visibility qualifiers have no effect on trait impls");
1044 for impl_item in impl_items {
1045 check_inherited(impl_item.span, impl_item.vis, "");
1048 hir::ItemImpl(_, _, _, None, _, _) => {
1049 check_inherited(item.span, item.vis,
1050 "place qualifiers on individual methods instead");
1052 hir::ItemDefaultImpl(..) => {
1053 check_inherited(item.span, item.vis,
1054 "visibility qualifiers have no effect on trait impls");
1056 hir::ItemForeignMod(..) => {
1057 check_inherited(item.span, item.vis,
1058 "place qualifiers on individual functions instead");
1060 hir::ItemStruct(..) | hir::ItemEnum(..) | hir::ItemTrait(..) |
1061 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1062 hir::ItemMod(..) | hir::ItemExternCrate(..) |
1063 hir::ItemUse(..) | hir::ItemTy(..) => {}
1067 /// When inside of something like a function or a method, visibility has no
1068 /// control over anything so this forbids any mention of any visibility
1069 fn check_all_inherited(&self, item: &hir::Item) {
1070 let check_inherited = |sp, vis| {
1071 if vis != hir::Inherited {
1072 span_err!(self.tcx.sess, sp, E0447,
1073 "visibility has no effect inside functions or block expressions");
1077 check_inherited(item.span, item.vis);
1079 hir::ItemImpl(_, _, _, _, _, ref impl_items) => {
1080 for impl_item in impl_items {
1081 check_inherited(impl_item.span, impl_item.vis);
1084 hir::ItemForeignMod(ref fm) => {
1085 for fi in &fm.items {
1086 check_inherited(fi.span, fi.vis);
1089 hir::ItemStruct(ref vdata, _) => {
1090 for f in vdata.fields() {
1091 check_inherited(f.span, f.node.kind.visibility());
1094 hir::ItemDefaultImpl(..) | hir::ItemEnum(..) | hir::ItemTrait(..) |
1095 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1096 hir::ItemMod(..) | hir::ItemExternCrate(..) |
1097 hir::ItemUse(..) | hir::ItemTy(..) => {}
1102 ///////////////////////////////////////////////////////////////////////////////
1103 /// Obsolete visitors for checking for private items in public interfaces.
1104 /// These visitors are supposed to be kept in frozen state and produce an
1105 /// "old error node set". For backward compatibility the new visitor reports
1106 /// warnings instead of hard errors when the erroneous node is not in this old set.
1107 ///////////////////////////////////////////////////////////////////////////////
1109 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1110 tcx: &'a ty::ctxt<'tcx>,
1111 access_levels: &'a AccessLevels,
1113 // set of errors produced by this obsolete visitor
1114 old_error_set: NodeSet,
1117 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1118 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1119 /// whether the type refers to private types.
1120 contains_private: bool,
1121 /// whether we've recurred at all (i.e. if we're pointing at the
1122 /// first type on which visit_ty was called).
1123 at_outer_type: bool,
1124 // whether that first type is a public path.
1125 outer_type_is_public_path: bool,
1128 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1129 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1130 let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) {
1131 // `int` etc. (None doesn't seem to occur.)
1132 None | Some(def::DefPrimTy(..)) | Some(def::DefSelfTy(..)) => return false,
1133 Some(def) => def.def_id(),
1136 // A path can only be private if:
1137 // it's in this crate...
1138 if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
1139 // .. and it corresponds to a private type in the AST (this returns
1140 // None for type parameters)
1141 match self.tcx.map.find(node_id) {
1142 Some(ast_map::NodeItem(ref item)) => item.vis != hir::Public,
1143 Some(_) | None => false,
1150 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1151 // FIXME: this would preferably be using `exported_items`, but all
1152 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1153 self.access_levels.is_public(trait_id)
1156 fn check_ty_param_bound(&mut self,
1157 ty_param_bound: &hir::TyParamBound) {
1158 if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1159 if self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1160 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1165 fn item_is_public(&self, id: &ast::NodeId, vis: hir::Visibility) -> bool {
1166 self.access_levels.is_reachable(*id) || vis == hir::Public
1170 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1171 fn visit_ty(&mut self, ty: &hir::Ty) {
1172 if let hir::TyPath(..) = ty.node {
1173 if self.inner.path_is_private_type(ty.id) {
1174 self.contains_private = true;
1175 // found what we're looking for so let's stop
1178 } else if self.at_outer_type {
1179 self.outer_type_is_public_path = true;
1182 self.at_outer_type = false;
1183 intravisit::walk_ty(self, ty)
1186 // don't want to recurse into [, .. expr]
1187 fn visit_expr(&mut self, _: &hir::Expr) {}
1190 impl<'a, 'tcx, 'v> Visitor<'v> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1191 /// We want to visit items in the context of their containing
1192 /// module and so forth, so supply a crate for doing a deep walk.
1193 fn visit_nested_item(&mut self, item: hir::ItemId) {
1194 self.visit_item(self.tcx.map.expect_item(item.id))
1197 fn visit_item(&mut self, item: &hir::Item) {
1199 // contents of a private mod can be reexported, so we need
1200 // to check internals.
1201 hir::ItemMod(_) => {}
1203 // An `extern {}` doesn't introduce a new privacy
1204 // namespace (the contents have their own privacies).
1205 hir::ItemForeignMod(_) => {}
1207 hir::ItemTrait(_, _, ref bounds, _) => {
1208 if !self.trait_is_public(item.id) {
1212 for bound in bounds.iter() {
1213 self.check_ty_param_bound(bound)
1217 // impls need some special handling to try to offer useful
1218 // error messages without (too many) false positives
1219 // (i.e. we could just return here to not check them at
1220 // all, or some worse estimation of whether an impl is
1221 // publicly visible).
1222 hir::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1223 // `impl [... for] Private` is never visible.
1224 let self_contains_private;
1225 // impl [... for] Public<...>, but not `impl [... for]
1226 // Vec<Public>` or `(Public,)` etc.
1227 let self_is_public_path;
1229 // check the properties of the Self type:
1231 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1233 contains_private: false,
1234 at_outer_type: true,
1235 outer_type_is_public_path: false,
1237 visitor.visit_ty(&**self_);
1238 self_contains_private = visitor.contains_private;
1239 self_is_public_path = visitor.outer_type_is_public_path;
1242 // miscellaneous info about the impl
1244 // `true` iff this is `impl Private for ...`.
1245 let not_private_trait =
1246 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1248 let did = self.tcx.trait_ref_to_def_id(tr);
1250 if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
1251 self.trait_is_public(node_id)
1253 true // external traits must be public
1257 // `true` iff this is a trait impl or at least one method is public.
1259 // `impl Public { $( fn ...() {} )* }` is not visible.
1261 // This is required over just using the methods' privacy
1262 // directly because we might have `impl<T: Foo<Private>> ...`,
1263 // and we shouldn't warn about the generics if all the methods
1264 // are private (because `T` won't be visible externally).
1265 let trait_or_some_public_method =
1266 trait_ref.is_some() ||
1269 match impl_item.node {
1270 hir::ImplItemKind::Const(..) |
1271 hir::ImplItemKind::Method(..) => {
1272 self.access_levels.is_reachable(impl_item.id)
1274 hir::ImplItemKind::Type(_) => false,
1278 if !self_contains_private &&
1279 not_private_trait &&
1280 trait_or_some_public_method {
1282 intravisit::walk_generics(self, g);
1286 for impl_item in impl_items {
1287 // This is where we choose whether to walk down
1288 // further into the impl to check its items. We
1289 // should only walk into public items so that we
1290 // don't erroneously report errors for private
1291 // types in private items.
1292 match impl_item.node {
1293 hir::ImplItemKind::Const(..) |
1294 hir::ImplItemKind::Method(..)
1295 if self.item_is_public(&impl_item.id, impl_item.vis) =>
1297 intravisit::walk_impl_item(self, impl_item)
1299 hir::ImplItemKind::Type(..) => {
1300 intravisit::walk_impl_item(self, impl_item)
1307 // Any private types in a trait impl fall into three
1309 // 1. mentioned in the trait definition
1310 // 2. mentioned in the type params/generics
1311 // 3. mentioned in the associated types of the impl
1313 // Those in 1. can only occur if the trait is in
1314 // this crate and will've been warned about on the
1315 // trait definition (there's no need to warn twice
1316 // so we don't check the methods).
1318 // Those in 2. are warned via walk_generics and this
1320 intravisit::walk_path(self, &tr.path);
1322 // Those in 3. are warned with this call.
1323 for impl_item in impl_items {
1324 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1330 } else if trait_ref.is_none() && self_is_public_path {
1331 // impl Public<Private> { ... }. Any public static
1332 // methods will be visible as `Public::foo`.
1333 let mut found_pub_static = false;
1334 for impl_item in impl_items {
1335 match impl_item.node {
1336 hir::ImplItemKind::Const(..) => {
1337 if self.item_is_public(&impl_item.id, impl_item.vis) {
1338 found_pub_static = true;
1339 intravisit::walk_impl_item(self, impl_item);
1342 hir::ImplItemKind::Method(ref sig, _) => {
1343 if sig.explicit_self.node == hir::SelfStatic &&
1344 self.item_is_public(&impl_item.id, impl_item.vis) {
1345 found_pub_static = true;
1346 intravisit::walk_impl_item(self, impl_item);
1352 if found_pub_static {
1353 intravisit::walk_generics(self, g)
1359 // `type ... = ...;` can contain private types, because
1360 // we're introducing a new name.
1361 hir::ItemTy(..) => return,
1363 // not at all public, so we don't care
1364 _ if !self.item_is_public(&item.id, item.vis) => {
1371 // We've carefully constructed it so that if we're here, then
1372 // any `visit_ty`'s will be called on things that are in
1373 // public signatures, i.e. things that we're interested in for
1375 debug!("VisiblePrivateTypesVisitor entering item {:?}", item);
1376 intravisit::walk_item(self, item);
1379 fn visit_generics(&mut self, generics: &hir::Generics) {
1380 for ty_param in generics.ty_params.iter() {
1381 for bound in ty_param.bounds.iter() {
1382 self.check_ty_param_bound(bound)
1385 for predicate in &generics.where_clause.predicates {
1387 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1388 for bound in bound_pred.bounds.iter() {
1389 self.check_ty_param_bound(bound)
1392 &hir::WherePredicate::RegionPredicate(_) => {}
1393 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1394 self.visit_ty(&*eq_pred.ty);
1400 fn visit_foreign_item(&mut self, item: &hir::ForeignItem) {
1401 if self.access_levels.is_reachable(item.id) {
1402 intravisit::walk_foreign_item(self, item)
1406 fn visit_ty(&mut self, t: &hir::Ty) {
1407 debug!("VisiblePrivateTypesVisitor checking ty {:?}", t);
1408 if let hir::TyPath(..) = t.node {
1409 if self.path_is_private_type(t.id) {
1410 self.old_error_set.insert(t.id);
1413 intravisit::walk_ty(self, t)
1416 fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics, item_id: ast::NodeId) {
1417 if self.access_levels.is_reachable(v.node.data.id()) {
1418 self.in_variant = true;
1419 intravisit::walk_variant(self, v, g, item_id);
1420 self.in_variant = false;
1424 fn visit_struct_field(&mut self, s: &hir::StructField) {
1425 let vis = match s.node.kind {
1426 hir::NamedField(_, vis) | hir::UnnamedField(vis) => vis
1428 if vis == hir::Public || self.in_variant {
1429 intravisit::walk_struct_field(self, s);
1433 // we don't need to introspect into these at all: an
1434 // expression/block context can't possibly contain exported things.
1435 // (Making them no-ops stops us from traversing the whole AST without
1436 // having to be super careful about our `walk_...` calls above.)
1437 // FIXME(#29524): Unfortunately this ^^^ is not true, blocks can contain
1438 // exported items (e.g. impls) and actual code in rustc itself breaks
1439 // if we don't traverse blocks in `EmbargoVisitor`
1440 fn visit_block(&mut self, _: &hir::Block) {}
1441 fn visit_expr(&mut self, _: &hir::Expr) {}
1444 ///////////////////////////////////////////////////////////////////////////////
1445 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1446 /// finds any private components in it.
1447 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1448 /// and traits in public interfaces.
1449 ///////////////////////////////////////////////////////////////////////////////
1451 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1452 tcx: &'a ty::ctxt<'tcx>,
1453 // Do not report an error when a private type is found
1455 // Is private component found?
1457 old_error_set: &'a NodeSet,
1460 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1461 // Check if the type alias contain private types when substituted
1462 fn is_public_type_alias(&self, item: &hir::Item, path: &hir::Path) -> bool {
1463 // We substitute type aliases only when determining impl publicity
1464 // FIXME: This will probably change and all type aliases will be substituted,
1465 // requires an amendment to RFC 136.
1469 // Type alias is considered public if the aliased type is
1470 // public, even if the type alias itself is private. So, something
1471 // like `type A = u8; pub fn f() -> A {...}` doesn't cause an error.
1472 if let hir::ItemTy(ref ty, ref generics) = item.node {
1473 let mut check = SearchInterfaceForPrivateItemsVisitor { is_public: true, ..*self };
1475 // If a private type alias with default type parameters is used in public
1476 // interface we must ensure, that the defaults are public if they are actually used.
1478 // type Alias<T = Private> = T;
1479 // pub fn f() -> Alias {...} // `Private` is implicitly used here, so it must be public
1481 let provided_params = path.segments.last().unwrap().parameters.types().len();
1482 for ty_param in &generics.ty_params[provided_params..] {
1483 if let Some(ref default_ty) = ty_param.default {
1484 check.visit_ty(default_ty);
1494 impl<'a, 'tcx: 'a, 'v> Visitor<'v> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1495 fn visit_ty(&mut self, ty: &hir::Ty) {
1496 if self.is_quiet && !self.is_public {
1497 // We are in quiet mode and a private type is already found, no need to proceed
1500 if let hir::TyPath(_, ref path) = ty.node {
1501 let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
1503 def::DefPrimTy(..) | def::DefSelfTy(..) | def::DefTyParam(..) => {
1506 def::DefAssociatedTy(..) if self.is_quiet => {
1507 // Conservatively approximate the whole type alias as public without
1508 // recursing into its components when determining impl publicity.
1509 // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
1510 // even if both `Type` and `Trait` are private.
1511 // Ideally, associated types should be substituted in the same way as
1512 // free type aliases, but this isn't done yet.
1515 def::DefStruct(def_id) | def::DefTy(def_id, _) |
1516 def::DefTrait(def_id) | def::DefAssociatedTy(def_id, _) => {
1517 // Non-local means public (private items can't leave their crate, modulo bugs)
1518 if let Some(node_id) = self.tcx.map.as_local_node_id(def_id) {
1519 let item = self.tcx.map.expect_item(node_id);
1520 if item.vis != hir::Public && !self.is_public_type_alias(item, path) {
1522 if self.old_error_set.contains(&ty.id) {
1523 span_err!(self.tcx.sess, ty.span, E0446,
1524 "private type in public interface");
1526 self.tcx.sess.add_lint (
1527 lint::builtin::PRIVATE_IN_PUBLIC,
1530 "private type in public interface (error E0446)".to_string()
1534 self.is_public = false;
1542 intravisit::walk_ty(self, ty);
1545 fn visit_trait_ref(&mut self, trait_ref: &hir::TraitRef) {
1546 if self.is_quiet && !self.is_public {
1547 // We are in quiet mode and a private type is already found, no need to proceed
1550 // Non-local means public (private items can't leave their crate, modulo bugs)
1551 let def_id = self.tcx.trait_ref_to_def_id(trait_ref);
1552 if let Some(node_id) = self.tcx.map.as_local_node_id(def_id) {
1553 let item = self.tcx.map.expect_item(node_id);
1554 if item.vis != hir::Public {
1556 if self.old_error_set.contains(&trait_ref.ref_id) {
1557 span_err!(self.tcx.sess, trait_ref.path.span, E0445,
1558 "private trait in public interface");
1560 self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
1562 trait_ref.path.span,
1563 "private trait in public interface (error E0445)"
1567 self.is_public = false;
1571 intravisit::walk_trait_ref(self, trait_ref);
1574 // Don't recurse into function bodies
1575 fn visit_block(&mut self, _: &hir::Block) {}
1576 // Don't recurse into expressions in array sizes or const initializers
1577 fn visit_expr(&mut self, _: &hir::Expr) {}
1578 // Don't recurse into patterns in function arguments
1579 fn visit_pat(&mut self, _: &hir::Pat) {}
1582 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1583 tcx: &'a ty::ctxt<'tcx>,
1584 old_error_set: &'a NodeSet,
1587 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1588 // A type is considered public if it doesn't contain any private components
1589 fn is_public_ty(&self, ty: &hir::Ty) -> bool {
1590 let mut check = SearchInterfaceForPrivateItemsVisitor {
1591 tcx: self.tcx, is_quiet: true, is_public: true, old_error_set: self.old_error_set
1597 // A trait reference is considered public if it doesn't contain any private components
1598 fn is_public_trait_ref(&self, trait_ref: &hir::TraitRef) -> bool {
1599 let mut check = SearchInterfaceForPrivateItemsVisitor {
1600 tcx: self.tcx, is_quiet: true, is_public: true, old_error_set: self.old_error_set
1602 check.visit_trait_ref(trait_ref);
1607 impl<'a, 'tcx, 'v> Visitor<'v> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1608 fn visit_item(&mut self, item: &hir::Item) {
1609 let mut check = SearchInterfaceForPrivateItemsVisitor {
1610 tcx: self.tcx, is_quiet: false, is_public: true, old_error_set: self.old_error_set
1613 // Crates are always public
1614 hir::ItemExternCrate(..) => {}
1615 // All nested items are checked by visit_item
1616 hir::ItemMod(..) => {}
1617 // Checked in resolve
1618 hir::ItemUse(..) => {}
1619 // Subitems of these items have inherited publicity
1620 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1621 hir::ItemEnum(..) | hir::ItemTrait(..) | hir::ItemTy(..) => {
1622 if item.vis == hir::Public {
1623 check.visit_item(item);
1626 // Subitems of foreign modules have their own publicity
1627 hir::ItemForeignMod(ref foreign_mod) => {
1628 for foreign_item in &foreign_mod.items {
1629 if foreign_item.vis == hir::Public {
1630 check.visit_foreign_item(foreign_item);
1634 // Subitems of structs have their own publicity
1635 hir::ItemStruct(ref struct_def, ref generics) => {
1636 if item.vis == hir::Public {
1637 check.visit_generics(generics);
1638 for field in struct_def.fields() {
1639 if field.node.kind.visibility() == hir::Public {
1640 check.visit_struct_field(field);
1645 // The interface is empty
1646 hir::ItemDefaultImpl(..) => {}
1647 // An inherent impl is public when its type is public
1648 // Subitems of inherent impls have their own publicity
1649 hir::ItemImpl(_, _, ref generics, None, ref ty, ref impl_items) => {
1650 if self.is_public_ty(ty) {
1651 check.visit_generics(generics);
1652 for impl_item in impl_items {
1653 if impl_item.vis == hir::Public {
1654 check.visit_impl_item(impl_item);
1659 // A trait impl is public when both its type and its trait are public
1660 // Subitems of trait impls have inherited publicity
1661 hir::ItemImpl(_, _, ref generics, Some(ref trait_ref), ref ty, ref impl_items) => {
1662 if self.is_public_ty(ty) && self.is_public_trait_ref(trait_ref) {
1663 check.visit_generics(generics);
1664 for impl_item in impl_items {
1665 check.visit_impl_item(impl_item);
1673 pub fn check_crate(tcx: &ty::ctxt,
1674 export_map: &def::ExportMap,
1675 external_exports: ExternalExports)
1677 let krate = tcx.map.krate();
1679 // Sanity check to make sure that all privacy usage and controls are
1681 let mut visitor = SanePrivacyVisitor {
1685 intravisit::walk_crate(&mut visitor, krate);
1687 // Figure out who everyone's parent is
1688 let mut visitor = ParentVisitor {
1691 curparent: ast::DUMMY_NODE_ID,
1693 intravisit::walk_crate(&mut visitor, krate);
1695 // Use the parent map to check the privacy of everything
1696 let mut visitor = PrivacyVisitor {
1697 curitem: ast::DUMMY_NODE_ID,
1700 parents: visitor.parents,
1701 external_exports: external_exports,
1703 intravisit::walk_crate(&mut visitor, krate);
1705 tcx.sess.abort_if_errors();
1707 // Build up a set of all exported items in the AST. This is a set of all
1708 // items which are reachable from external crates based on visibility.
1709 let mut visitor = EmbargoVisitor {
1711 export_map: export_map,
1712 access_levels: Default::default(),
1713 prev_level: Some(AccessLevel::Public),
1717 intravisit::walk_crate(&mut visitor, krate);
1718 if visitor.changed {
1719 visitor.changed = false;
1724 visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1727 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1729 access_levels: &visitor.access_levels,
1731 old_error_set: NodeSet(),
1733 intravisit::walk_crate(&mut visitor, krate);
1735 // Check for private types and traits in public interfaces
1736 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1738 old_error_set: &visitor.old_error_set,
1740 krate.visit_all_items(&mut visitor);
1743 visitor.access_levels
1746 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }