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/")]
18 #![cfg_attr(not(stage0), deny(warnings))]
20 #![feature(rustc_diagnostic_macros)]
21 #![feature(rustc_private)]
22 #![feature(staged_api)]
24 #[macro_use] extern crate log;
25 #[macro_use] extern crate syntax;
28 extern crate rustc_front;
30 use self::PrivacyResult::*;
31 use self::FieldName::*;
34 use std::mem::replace;
36 use rustc_front::hir::{self, PatKind};
37 use rustc_front::intravisit::{self, Visitor};
39 use rustc::dep_graph::DepNode;
41 use rustc::middle::def::{self, Def};
42 use rustc::middle::def_id::DefId;
43 use rustc::middle::privacy::{AccessLevel, AccessLevels};
44 use rustc::middle::privacy::ExternalExports;
45 use rustc::middle::ty;
46 use rustc::util::nodemap::{NodeMap, NodeSet};
47 use rustc::front::map as ast_map;
50 use syntax::codemap::Span;
54 type Context<'a, 'tcx> = (&'a ty::MethodMap<'tcx>, &'a def::ExportMap);
56 /// Result of a checking operation - None => no errors were found. Some => an
57 /// error and contains the span and message for reporting that error and
58 /// optionally the same for a note about the error.
59 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
61 ////////////////////////////////////////////////////////////////////////////////
62 /// The parent visitor, used to determine what's the parent of what (node-wise)
63 ////////////////////////////////////////////////////////////////////////////////
65 struct ParentVisitor<'a, 'tcx:'a> {
66 tcx: &'a ty::ctxt<'tcx>,
67 parents: NodeMap<ast::NodeId>,
68 curparent: ast::NodeId,
71 impl<'a, 'tcx, 'v> Visitor<'v> for ParentVisitor<'a, 'tcx> {
72 /// We want to visit items in the context of their containing
73 /// module and so forth, so supply a crate for doing a deep walk.
74 fn visit_nested_item(&mut self, item: hir::ItemId) {
75 self.visit_item(self.tcx.map.expect_item(item.id))
77 fn visit_item(&mut self, item: &hir::Item) {
78 self.parents.insert(item.id, self.curparent);
80 let prev = self.curparent;
82 hir::ItemMod(..) => { self.curparent = item.id; }
83 // Enum variants are parented to the enum definition itself because
84 // they inherit privacy
85 hir::ItemEnum(ref def, _) => {
86 for variant in &def.variants {
87 // The parent is considered the enclosing enum because the
88 // enum will dictate the privacy visibility of this variant
90 self.parents.insert(variant.node.data.id(), item.id);
94 // Trait methods are always considered "public", but if the trait is
95 // private then we need some private item in the chain from the
96 // method to the root. In this case, if the trait is private, then
97 // parent all the methods to the trait to indicate that they're
99 hir::ItemTrait(_, _, _, ref trait_items) if item.vis != hir::Public => {
100 for trait_item in trait_items {
101 self.parents.insert(trait_item.id, item.id);
107 intravisit::walk_item(self, item);
108 self.curparent = prev;
111 fn visit_foreign_item(&mut self, a: &hir::ForeignItem) {
112 self.parents.insert(a.id, self.curparent);
113 intravisit::walk_foreign_item(self, a);
116 fn visit_fn(&mut self, a: intravisit::FnKind<'v>, b: &'v hir::FnDecl,
117 c: &'v hir::Block, d: Span, id: ast::NodeId) {
118 // We already took care of some trait methods above, otherwise things
119 // like impl methods and pub trait methods are parented to the
120 // containing module, not the containing trait.
121 if !self.parents.contains_key(&id) {
122 self.parents.insert(id, self.curparent);
124 intravisit::walk_fn(self, a, b, c, d);
127 fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) {
128 // visit_fn handles methods, but associated consts have to be handled
130 if !self.parents.contains_key(&ii.id) {
131 self.parents.insert(ii.id, self.curparent);
133 intravisit::walk_impl_item(self, ii);
136 fn visit_variant_data(&mut self, s: &hir::VariantData, _: ast::Name,
137 _: &'v hir::Generics, item_id: ast::NodeId, _: Span) {
138 // Struct constructors are parented to their struct definitions because
139 // they essentially are the struct definitions.
141 self.parents.insert(s.id(), item_id);
144 // While we have the id of the struct definition, go ahead and parent
146 for field in s.fields() {
147 self.parents.insert(field.node.id, self.curparent);
149 intravisit::walk_struct_def(self, s)
153 ////////////////////////////////////////////////////////////////////////////////
154 /// The embargo visitor, used to determine the exports of the ast
155 ////////////////////////////////////////////////////////////////////////////////
157 struct EmbargoVisitor<'a, 'tcx: 'a> {
158 tcx: &'a ty::ctxt<'tcx>,
159 export_map: &'a def::ExportMap,
161 // Accessibility levels for reachable nodes
162 access_levels: AccessLevels,
163 // Previous accessibility level, None means unreachable
164 prev_level: Option<AccessLevel>,
165 // Have something changed in the level map?
169 struct ReachEverythingInTheInterfaceVisitor<'b, 'a: 'b, 'tcx: 'a> {
170 ev: &'b mut EmbargoVisitor<'a, 'tcx>,
173 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
174 fn ty_level(&self, ty: &hir::Ty) -> Option<AccessLevel> {
175 if let hir::TyPath(..) = ty.node {
176 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
177 Def::PrimTy(..) | Def::SelfTy(..) | Def::TyParam(..) => {
178 Some(AccessLevel::Public)
181 if let Some(node_id) = self.tcx.map.as_local_node_id(def.def_id()) {
184 Some(AccessLevel::Public)
189 Some(AccessLevel::Public)
193 fn trait_level(&self, trait_ref: &hir::TraitRef) -> Option<AccessLevel> {
194 let did = self.tcx.trait_ref_to_def_id(trait_ref);
195 if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
198 Some(AccessLevel::Public)
202 fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
203 self.access_levels.map.get(&id).cloned()
206 // Updates node level and returns the updated level
207 fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
208 let old_level = self.get(id);
209 // Accessibility levels can only grow
210 if level > old_level {
211 self.access_levels.map.insert(id, level.unwrap());
219 fn reach<'b>(&'b mut self) -> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
220 ReachEverythingInTheInterfaceVisitor { ev: self }
224 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
225 /// We want to visit items in the context of their containing
226 /// module and so forth, so supply a crate for doing a deep walk.
227 fn visit_nested_item(&mut self, item: hir::ItemId) {
228 self.visit_item(self.tcx.map.expect_item(item.id))
231 fn visit_item(&mut self, item: &hir::Item) {
232 let inherited_item_level = match item.node {
233 // Impls inherit level from their types and traits
234 hir::ItemImpl(_, _, _, None, ref ty, _) => {
237 hir::ItemImpl(_, _, _, Some(ref trait_ref), ref ty, _) => {
238 cmp::min(self.ty_level(&ty), self.trait_level(trait_ref))
240 hir::ItemDefaultImpl(_, ref trait_ref) => {
241 self.trait_level(trait_ref)
243 // Foreign mods inherit level from parents
244 hir::ItemForeignMod(..) => {
247 // Other `pub` items inherit levels from parents
249 if item.vis == hir::Public { self.prev_level } else { None }
253 // Update level of the item itself
254 let item_level = self.update(item.id, inherited_item_level);
256 // Update levels of nested things
258 hir::ItemEnum(ref def, _) => {
259 for variant in &def.variants {
260 let variant_level = self.update(variant.node.data.id(), item_level);
261 for field in variant.node.data.fields() {
262 self.update(field.node.id, variant_level);
266 hir::ItemImpl(_, _, _, None, _, ref impl_items) => {
267 for impl_item in impl_items {
268 if impl_item.vis == hir::Public {
269 self.update(impl_item.id, item_level);
273 hir::ItemImpl(_, _, _, Some(_), _, ref impl_items) => {
274 for impl_item in impl_items {
275 self.update(impl_item.id, item_level);
278 hir::ItemTrait(_, _, _, ref trait_items) => {
279 for trait_item in trait_items {
280 self.update(trait_item.id, item_level);
283 hir::ItemStruct(ref def, _) => {
284 if !def.is_struct() {
285 self.update(def.id(), item_level);
287 for field in def.fields() {
288 if field.node.kind.visibility() == hir::Public {
289 self.update(field.node.id, item_level);
293 hir::ItemForeignMod(ref foreign_mod) => {
294 for foreign_item in &foreign_mod.items {
295 if foreign_item.vis == hir::Public {
296 self.update(foreign_item.id, item_level);
303 // Mark all items in interfaces of reachable items as reachable
305 // The interface is empty
306 hir::ItemExternCrate(..) => {}
307 // All nested items are checked by visit_item
308 hir::ItemMod(..) => {}
309 // Reexports are handled in visit_mod
310 hir::ItemUse(..) => {}
312 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
313 hir::ItemTrait(..) | hir::ItemTy(..) | hir::ItemImpl(_, _, _, Some(..), _, _) => {
314 if item_level.is_some() {
315 self.reach().visit_item(item);
318 // Visit everything, but enum variants have their own levels
319 hir::ItemEnum(ref def, ref generics) => {
320 if item_level.is_some() {
321 self.reach().visit_generics(generics);
323 for variant in &def.variants {
324 if self.get(variant.node.data.id()).is_some() {
325 for field in variant.node.data.fields() {
326 self.reach().visit_struct_field(field);
328 // Corner case: if the variant is reachable, but its
329 // enum is not, make the enum reachable as well.
330 self.update(item.id, Some(AccessLevel::Reachable));
334 // Visit everything, but foreign items have their own levels
335 hir::ItemForeignMod(ref foreign_mod) => {
336 for foreign_item in &foreign_mod.items {
337 if self.get(foreign_item.id).is_some() {
338 self.reach().visit_foreign_item(foreign_item);
342 // Visit everything except for private fields
343 hir::ItemStruct(ref struct_def, ref generics) => {
344 if item_level.is_some() {
345 self.reach().visit_generics(generics);
346 for field in struct_def.fields() {
347 if self.get(field.node.id).is_some() {
348 self.reach().visit_struct_field(field);
353 // The interface is empty
354 hir::ItemDefaultImpl(..) => {}
355 // Visit everything except for private impl items
356 hir::ItemImpl(_, _, ref generics, None, _, ref impl_items) => {
357 if item_level.is_some() {
358 self.reach().visit_generics(generics);
359 for impl_item in impl_items {
360 if self.get(impl_item.id).is_some() {
361 self.reach().visit_impl_item(impl_item);
368 let orig_level = self.prev_level;
369 self.prev_level = item_level;
371 intravisit::walk_item(self, item);
373 self.prev_level = orig_level;
376 fn visit_block(&mut self, b: &'v hir::Block) {
377 let orig_level = replace(&mut self.prev_level, None);
379 // Blocks can have public items, for example impls, but they always
380 // start as completely private regardless of publicity of a function,
381 // constant, type, field, etc. in which this block resides
382 intravisit::walk_block(self, b);
384 self.prev_level = orig_level;
387 fn visit_mod(&mut self, m: &hir::Mod, _sp: Span, id: ast::NodeId) {
388 // This code is here instead of in visit_item so that the
389 // crate module gets processed as well.
390 if self.prev_level.is_some() {
391 if let Some(exports) = self.export_map.get(&id) {
392 for export in exports {
393 if let Some(node_id) = self.tcx.map.as_local_node_id(export.def_id) {
394 self.update(node_id, Some(AccessLevel::Exported));
400 intravisit::walk_mod(self, m);
403 fn visit_macro_def(&mut self, md: &'v hir::MacroDef) {
404 self.update(md.id, Some(AccessLevel::Public));
408 impl<'b, 'a, 'tcx: 'a> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
409 // Make the type hidden under a type alias reachable
410 fn reach_aliased_type(&mut self, item: &hir::Item, path: &hir::Path) {
411 if let hir::ItemTy(ref ty, ref generics) = item.node {
412 // See `fn is_public_type_alias` for details
414 let provided_params = path.segments.last().unwrap().parameters.types().len();
415 for ty_param in &generics.ty_params[provided_params..] {
416 if let Some(ref default_ty) = ty_param.default {
417 self.visit_ty(default_ty);
424 impl<'b, 'a, 'tcx: 'a, 'v> Visitor<'v> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
425 fn visit_ty(&mut self, ty: &hir::Ty) {
426 if let hir::TyPath(_, ref path) = ty.node {
427 let def = self.ev.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
429 Def::Struct(def_id) | Def::Enum(def_id) | Def::TyAlias(def_id) |
430 Def::Trait(def_id) | Def::AssociatedTy(def_id, _) => {
431 if let Some(node_id) = self.ev.tcx.map.as_local_node_id(def_id) {
432 let item = self.ev.tcx.map.expect_item(node_id);
433 if let Def::TyAlias(..) = def {
434 // Type aliases are substituted. Associated type aliases are not
435 // substituted yet, but ideally they should be.
436 if self.ev.get(item.id).is_none() {
437 self.reach_aliased_type(item, path);
440 self.ev.update(item.id, Some(AccessLevel::Reachable));
449 intravisit::walk_ty(self, ty);
452 fn visit_trait_ref(&mut self, trait_ref: &hir::TraitRef) {
453 let def_id = self.ev.tcx.trait_ref_to_def_id(trait_ref);
454 if let Some(node_id) = self.ev.tcx.map.as_local_node_id(def_id) {
455 let item = self.ev.tcx.map.expect_item(node_id);
456 self.ev.update(item.id, Some(AccessLevel::Reachable));
459 intravisit::walk_trait_ref(self, trait_ref);
462 // Don't recurse into function bodies
463 fn visit_block(&mut self, _: &hir::Block) {}
464 // Don't recurse into expressions in array sizes or const initializers
465 fn visit_expr(&mut self, _: &hir::Expr) {}
466 // Don't recurse into patterns in function arguments
467 fn visit_pat(&mut self, _: &hir::Pat) {}
470 ////////////////////////////////////////////////////////////////////////////////
471 /// The privacy visitor, where privacy checks take place (violations reported)
472 ////////////////////////////////////////////////////////////////////////////////
474 struct PrivacyVisitor<'a, 'tcx: 'a> {
475 tcx: &'a ty::ctxt<'tcx>,
476 curitem: ast::NodeId,
478 parents: NodeMap<ast::NodeId>,
479 external_exports: ExternalExports,
486 DisallowedBy(ast::NodeId),
490 UnnamedField(usize), // index
491 NamedField(ast::Name),
494 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
495 // used when debugging
496 fn nodestr(&self, id: ast::NodeId) -> String {
497 self.tcx.map.node_to_string(id).to_string()
500 // Determines whether the given definition is public from the point of view
501 // of the current item.
502 fn def_privacy(&self, did: DefId) -> PrivacyResult {
503 let node_id = if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
506 if self.external_exports.contains(&did) {
507 debug!("privacy - {:?} was externally exported", did);
510 debug!("privacy - is {:?} a public method", did);
512 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
513 Some(&ty::ConstTraitItem(ref ac)) => {
514 debug!("privacy - it's a const: {:?}", *ac);
516 ty::TraitContainer(id) => {
517 debug!("privacy - recursing on trait {:?}", id);
520 ty::ImplContainer(id) => {
521 match self.tcx.impl_trait_ref(id) {
523 debug!("privacy - impl of trait {:?}", id);
524 self.def_privacy(t.def_id)
527 debug!("privacy - found inherent \
528 associated constant {:?}",
530 if ac.vis == hir::Public {
540 Some(&ty::MethodTraitItem(ref meth)) => {
541 debug!("privacy - well at least it's a method: {:?}",
543 match meth.container {
544 ty::TraitContainer(id) => {
545 debug!("privacy - recursing on trait {:?}", id);
548 ty::ImplContainer(id) => {
549 match self.tcx.impl_trait_ref(id) {
551 debug!("privacy - impl of trait {:?}", id);
552 self.def_privacy(t.def_id)
555 debug!("privacy - found a method {:?}",
557 if meth.vis == hir::Public {
567 Some(&ty::TypeTraitItem(ref typedef)) => {
568 match typedef.container {
569 ty::TraitContainer(id) => {
570 debug!("privacy - recursing on trait {:?}", id);
573 ty::ImplContainer(id) => {
574 match self.tcx.impl_trait_ref(id) {
576 debug!("privacy - impl of trait {:?}", id);
577 self.def_privacy(t.def_id)
580 debug!("privacy - found a typedef {:?}",
582 if typedef.vis == hir::Public {
593 debug!("privacy - nope, not even a method");
599 debug!("privacy - local {} not public all the way down",
600 self.tcx.map.node_to_string(node_id));
601 // return quickly for things in the same module
602 if self.parents.get(&node_id) == self.parents.get(&self.curitem) {
603 debug!("privacy - same parent, we're done here");
607 // We now know that there is at least one private member between the
608 // destination and the root.
609 let mut closest_private_id = node_id;
611 debug!("privacy - examining {}", self.nodestr(closest_private_id));
612 let vis = match self.tcx.map.find(closest_private_id) {
613 // If this item is a method, then we know for sure that it's an
614 // actual method and not a static method. The reason for this is
615 // that these cases are only hit in the ExprMethodCall
616 // expression, and ExprCall will have its path checked later
617 // (the path of the trait/impl) if it's a static method.
619 // With this information, then we can completely ignore all
620 // trait methods. The privacy violation would be if the trait
621 // couldn't get imported, not if the method couldn't be used
622 // (all trait methods are public).
624 // However, if this is an impl method, then we dictate this
625 // decision solely based on the privacy of the method
627 // FIXME(#10573) is this the right behavior? Why not consider
628 // where the method was defined?
629 Some(ast_map::NodeImplItem(ii)) => {
631 hir::ImplItemKind::Const(..) |
632 hir::ImplItemKind::Method(..) => {
633 let imp = self.tcx.map
634 .get_parent_did(closest_private_id);
635 match self.tcx.impl_trait_ref(imp) {
636 Some(..) => return Allowable,
637 _ if ii.vis == hir::Public => {
643 hir::ImplItemKind::Type(_) => return Allowable,
646 Some(ast_map::NodeTraitItem(_)) => {
650 // This is not a method call, extract the visibility as one
651 // would normally look at it
652 Some(ast_map::NodeItem(it)) => it.vis,
653 Some(ast_map::NodeForeignItem(_)) => {
654 self.tcx.map.get_foreign_vis(closest_private_id)
656 Some(ast_map::NodeVariant(..)) => {
657 hir::Public // need to move up a level (to the enum)
661 if vis != hir::Public { break }
662 // if we've reached the root, then everything was allowable and this
664 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
665 closest_private_id = *self.parents.get(&closest_private_id).unwrap();
667 // If we reached the top, then we were public all the way down and
668 // we can allow this access.
669 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
671 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
672 if self.private_accessible(closest_private_id) {
675 DisallowedBy(closest_private_id)
679 /// True if `id` is both local and private-accessible
680 fn local_private_accessible(&self, did: DefId) -> bool {
681 if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
682 self.private_accessible(node_id)
688 /// For a local private node in the AST, this function will determine
689 /// whether the node is accessible by the current module that iteration is
691 fn private_accessible(&self, id: ast::NodeId) -> bool {
692 self.tcx.map.private_item_is_visible_from(id, self.curitem)
695 fn report_error(&self, result: CheckResult) -> bool {
698 Some((span, msg, note)) => {
699 let mut err = self.tcx.sess.struct_span_err(span, &msg[..]);
700 if let Some((span, msg)) = note {
701 err.span_note(span, &msg[..]);
709 /// Guarantee that a particular definition is public. Returns a CheckResult
710 /// which contains any errors found. These can be reported using `report_error`.
711 /// If the result is `None`, no errors were found.
712 fn ensure_public(&self,
715 source_did: Option<DefId>,
718 debug!("ensure_public(span={:?}, to_check={:?}, source_did={:?}, msg={:?})",
719 span, to_check, source_did, msg);
720 let def_privacy = self.def_privacy(to_check);
721 debug!("ensure_public: def_privacy={:?}", def_privacy);
722 let id = match def_privacy {
723 ExternallyDenied => {
724 return Some((span, format!("{} is private", msg), None))
726 Allowable => return None,
727 DisallowedBy(id) => id,
730 // If we're disallowed by a particular id, then we attempt to
731 // give a nice error message to say why it was disallowed. It
732 // was either because the item itself is private or because
733 // its parent is private and its parent isn't in our
734 // ancestry. (Both the item being checked and its parent must
736 let def_id = source_did.unwrap_or(to_check);
737 let node_id = self.tcx.map.as_local_node_id(def_id);
739 let (err_span, err_msg) = if Some(id) == node_id {
740 return Some((span, format!("{} is private", msg), None));
742 (span, format!("{} is inaccessible", msg))
744 let item = match self.tcx.map.find(id) {
745 Some(ast_map::NodeItem(item)) => {
747 // If an impl disallowed this item, then this is resolve's
748 // way of saying that a struct/enum's static method was
749 // invoked, and the struct/enum itself is private. Crawl
750 // back up the chains to find the relevant struct/enum that
752 hir::ItemImpl(_, _, _, _, ref ty, _) => {
754 hir::TyPath(..) => {}
755 _ => return Some((err_span, err_msg, None)),
757 let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
758 let did = def.def_id();
759 let node_id = self.tcx.map.as_local_node_id(did).unwrap();
760 match self.tcx.map.get(node_id) {
761 ast_map::NodeItem(item) => item,
762 _ => self.tcx.sess.span_bug(item.span,
763 "path is not an item")
769 Some(..) | None => return Some((err_span, err_msg, None)),
771 let desc = match item.node {
772 hir::ItemMod(..) => "module",
773 hir::ItemTrait(..) => "trait",
774 hir::ItemStruct(..) => "struct",
775 hir::ItemEnum(..) => "enum",
776 _ => return Some((err_span, err_msg, None))
778 let msg = format!("{} `{}` is private", desc, item.name);
779 Some((err_span, err_msg, Some((span, msg))))
782 // Checks that a field is in scope.
783 fn check_field(&mut self,
785 def: ty::AdtDef<'tcx>,
786 v: ty::VariantDef<'tcx>,
788 let field = match name {
789 NamedField(f_name) => {
790 debug!("privacy - check named field {} in struct {:?}", f_name, def);
791 v.field_named(f_name)
793 UnnamedField(idx) => &v.fields[idx]
795 if field.vis == hir::Public || self.local_private_accessible(def.did) {
799 let struct_desc = match def.adt_kind() {
800 ty::AdtKind::Struct =>
801 format!("struct `{}`", self.tcx.item_path_str(def.did)),
802 // struct variant fields have inherited visibility
803 ty::AdtKind::Enum => return
805 let msg = match name {
806 NamedField(name) => format!("field `{}` of {} is private",
808 UnnamedField(idx) => format!("field #{} of {} is private",
811 span_err!(self.tcx.sess, span, E0451,
815 // Given the ID of a method, checks to ensure it's in scope.
816 fn check_static_method(&mut self,
820 self.report_error(self.ensure_public(span,
823 &format!("method `{}`",
827 // Checks that a method is in scope.
828 fn check_method(&mut self, span: Span, method_def_id: DefId,
830 match self.tcx.impl_or_trait_item(method_def_id).container() {
831 ty::ImplContainer(_) => {
832 self.check_static_method(span, method_def_id, name)
834 // Trait methods are always all public. The only controlling factor
835 // is whether the trait itself is accessible or not.
836 ty::TraitContainer(trait_def_id) => {
837 self.report_error(self.ensure_public(span, trait_def_id,
838 None, "source trait"));
844 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
845 /// We want to visit items in the context of their containing
846 /// module and so forth, so supply a crate for doing a deep walk.
847 fn visit_nested_item(&mut self, item: hir::ItemId) {
848 self.visit_item(self.tcx.map.expect_item(item.id))
851 fn visit_item(&mut self, item: &hir::Item) {
852 let orig_curitem = replace(&mut self.curitem, item.id);
853 intravisit::walk_item(self, item);
854 self.curitem = orig_curitem;
857 fn visit_expr(&mut self, expr: &hir::Expr) {
859 hir::ExprField(ref base, name) => {
860 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&base).sty {
861 self.check_field(expr.span,
863 def.struct_variant(),
864 NamedField(name.node));
867 hir::ExprTupField(ref base, idx) => {
868 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&base).sty {
869 self.check_field(expr.span,
871 def.struct_variant(),
872 UnnamedField(idx.node));
875 hir::ExprMethodCall(name, _, _) => {
876 let method_call = ty::MethodCall::expr(expr.id);
877 let method = self.tcx.tables.borrow().method_map[&method_call];
878 debug!("(privacy checking) checking impl method");
879 self.check_method(expr.span, method.def_id, name.node);
881 hir::ExprStruct(..) => {
882 let adt = self.tcx.expr_ty(expr).ty_adt_def().unwrap();
883 let variant = adt.variant_of_def(self.tcx.resolve_expr(expr));
884 // RFC 736: ensure all unmentioned fields are visible.
885 // Rather than computing the set of unmentioned fields
886 // (i.e. `all_fields - fields`), just check them all.
887 for field in &variant.fields {
888 self.check_field(expr.span, adt, variant, NamedField(field.name));
891 hir::ExprPath(..) => {
893 if let Def::Struct(..) = self.tcx.resolve_expr(expr) {
894 let expr_ty = self.tcx.expr_ty(expr);
895 let def = match expr_ty.sty {
896 ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
897 output: ty::FnConverging(ty), ..
900 }.ty_adt_def().unwrap();
901 let any_priv = def.struct_variant().fields.iter().any(|f| {
902 f.vis != hir::Public && !self.local_private_accessible(def.did)
905 span_err!(self.tcx.sess, expr.span, E0450,
906 "cannot invoke tuple struct constructor with private \
914 intravisit::walk_expr(self, expr);
917 fn visit_pat(&mut self, pattern: &hir::Pat) {
918 // Foreign functions do not have their patterns mapped in the def_map,
919 // and there's nothing really relevant there anyway, so don't bother
920 // checking privacy. If you can name the type then you can pass it to an
921 // external C function anyway.
922 if self.in_foreign { return }
925 PatKind::Struct(_, ref fields, _) => {
926 let adt = self.tcx.pat_ty(pattern).ty_adt_def().unwrap();
927 let def = self.tcx.def_map.borrow().get(&pattern.id).unwrap().full_def();
928 let variant = adt.variant_of_def(def);
929 for field in fields {
930 self.check_field(pattern.span, adt, variant,
931 NamedField(field.node.name));
935 // Patterns which bind no fields are allowable (the path is check
937 PatKind::TupleStruct(_, Some(ref fields)) => {
938 match self.tcx.pat_ty(pattern).sty {
939 ty::TyStruct(def, _) => {
940 for (i, field) in fields.iter().enumerate() {
941 if let PatKind::Wild = field.node {
944 self.check_field(field.span,
946 def.struct_variant(),
951 // enum fields have no privacy at this time
960 intravisit::walk_pat(self, pattern);
963 fn visit_foreign_item(&mut self, fi: &hir::ForeignItem) {
964 self.in_foreign = true;
965 intravisit::walk_foreign_item(self, fi);
966 self.in_foreign = false;
970 ////////////////////////////////////////////////////////////////////////////////
971 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
972 ////////////////////////////////////////////////////////////////////////////////
974 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
975 tcx: &'a ty::ctxt<'tcx>,
979 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
980 /// We want to visit items in the context of their containing
981 /// module and so forth, so supply a crate for doing a deep walk.
982 fn visit_nested_item(&mut self, item: hir::ItemId) {
983 self.visit_item(self.tcx.map.expect_item(item.id))
986 fn visit_item(&mut self, item: &hir::Item) {
987 self.check_sane_privacy(item);
989 self.check_all_inherited(item);
992 let orig_in_block = self.in_block;
994 // Modules turn privacy back on, otherwise we inherit
995 self.in_block = if let hir::ItemMod(..) = item.node { false } else { orig_in_block };
997 intravisit::walk_item(self, item);
998 self.in_block = orig_in_block;
1001 fn visit_block(&mut self, b: &'v hir::Block) {
1002 let orig_in_block = replace(&mut self.in_block, true);
1003 intravisit::walk_block(self, b);
1004 self.in_block = orig_in_block;
1008 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1009 /// Validates all of the visibility qualifiers placed on the item given. This
1010 /// ensures that there are no extraneous qualifiers that don't actually do
1011 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1012 /// later on down the road...
1013 fn check_sane_privacy(&self, item: &hir::Item) {
1014 let check_inherited = |sp, vis, note: &str| {
1015 if vis != hir::Inherited {
1016 let mut err = struct_span_err!(self.tcx.sess, sp, E0449,
1017 "unnecessary visibility qualifier");
1018 if !note.is_empty() {
1019 err.span_note(sp, note);
1026 // implementations of traits don't need visibility qualifiers because
1027 // that's controlled by having the trait in scope.
1028 hir::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1029 check_inherited(item.span, item.vis,
1030 "visibility qualifiers have no effect on trait impls");
1031 for impl_item in impl_items {
1032 check_inherited(impl_item.span, impl_item.vis, "");
1035 hir::ItemImpl(_, _, _, None, _, _) => {
1036 check_inherited(item.span, item.vis,
1037 "place qualifiers on individual methods instead");
1039 hir::ItemDefaultImpl(..) => {
1040 check_inherited(item.span, item.vis,
1041 "visibility qualifiers have no effect on trait impls");
1043 hir::ItemForeignMod(..) => {
1044 check_inherited(item.span, item.vis,
1045 "place qualifiers on individual functions instead");
1047 hir::ItemStruct(..) | hir::ItemEnum(..) | hir::ItemTrait(..) |
1048 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1049 hir::ItemMod(..) | hir::ItemExternCrate(..) |
1050 hir::ItemUse(..) | hir::ItemTy(..) => {}
1054 /// When inside of something like a function or a method, visibility has no
1055 /// control over anything so this forbids any mention of any visibility
1056 fn check_all_inherited(&self, item: &hir::Item) {
1057 let check_inherited = |sp, vis| {
1058 if vis != hir::Inherited {
1059 span_err!(self.tcx.sess, sp, E0447,
1060 "visibility has no effect inside functions or block expressions");
1064 check_inherited(item.span, item.vis);
1066 hir::ItemImpl(_, _, _, _, _, ref impl_items) => {
1067 for impl_item in impl_items {
1068 check_inherited(impl_item.span, impl_item.vis);
1071 hir::ItemForeignMod(ref fm) => {
1072 for fi in &fm.items {
1073 check_inherited(fi.span, fi.vis);
1076 hir::ItemStruct(ref vdata, _) => {
1077 for f in vdata.fields() {
1078 check_inherited(f.span, f.node.kind.visibility());
1081 hir::ItemDefaultImpl(..) | hir::ItemEnum(..) | hir::ItemTrait(..) |
1082 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1083 hir::ItemMod(..) | hir::ItemExternCrate(..) |
1084 hir::ItemUse(..) | hir::ItemTy(..) => {}
1089 ///////////////////////////////////////////////////////////////////////////////
1090 /// Obsolete visitors for checking for private items in public interfaces.
1091 /// These visitors are supposed to be kept in frozen state and produce an
1092 /// "old error node set". For backward compatibility the new visitor reports
1093 /// warnings instead of hard errors when the erroneous node is not in this old set.
1094 ///////////////////////////////////////////////////////////////////////////////
1096 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1097 tcx: &'a ty::ctxt<'tcx>,
1098 access_levels: &'a AccessLevels,
1100 // set of errors produced by this obsolete visitor
1101 old_error_set: NodeSet,
1104 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1105 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1106 /// whether the type refers to private types.
1107 contains_private: bool,
1108 /// whether we've recurred at all (i.e. if we're pointing at the
1109 /// first type on which visit_ty was called).
1110 at_outer_type: bool,
1111 // whether that first type is a public path.
1112 outer_type_is_public_path: bool,
1115 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1116 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1117 let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) {
1118 // `int` etc. (None doesn't seem to occur.)
1119 None | Some(Def::PrimTy(..)) | Some(Def::SelfTy(..)) => return false,
1120 Some(def) => def.def_id(),
1123 // A path can only be private if:
1124 // it's in this crate...
1125 if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
1126 // .. and it corresponds to a private type in the AST (this returns
1127 // None for type parameters)
1128 match self.tcx.map.find(node_id) {
1129 Some(ast_map::NodeItem(ref item)) => item.vis != hir::Public,
1130 Some(_) | None => false,
1137 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1138 // FIXME: this would preferably be using `exported_items`, but all
1139 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1140 self.access_levels.is_public(trait_id)
1143 fn check_ty_param_bound(&mut self,
1144 ty_param_bound: &hir::TyParamBound) {
1145 if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1146 if self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1147 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1152 fn item_is_public(&self, id: &ast::NodeId, vis: hir::Visibility) -> bool {
1153 self.access_levels.is_reachable(*id) || vis == hir::Public
1157 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1158 fn visit_ty(&mut self, ty: &hir::Ty) {
1159 if let hir::TyPath(..) = ty.node {
1160 if self.inner.path_is_private_type(ty.id) {
1161 self.contains_private = true;
1162 // found what we're looking for so let's stop
1165 } else if self.at_outer_type {
1166 self.outer_type_is_public_path = true;
1169 self.at_outer_type = false;
1170 intravisit::walk_ty(self, ty)
1173 // don't want to recurse into [, .. expr]
1174 fn visit_expr(&mut self, _: &hir::Expr) {}
1177 impl<'a, 'tcx, 'v> Visitor<'v> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1178 /// We want to visit items in the context of their containing
1179 /// module and so forth, so supply a crate for doing a deep walk.
1180 fn visit_nested_item(&mut self, item: hir::ItemId) {
1181 self.visit_item(self.tcx.map.expect_item(item.id))
1184 fn visit_item(&mut self, item: &hir::Item) {
1186 // contents of a private mod can be reexported, so we need
1187 // to check internals.
1188 hir::ItemMod(_) => {}
1190 // An `extern {}` doesn't introduce a new privacy
1191 // namespace (the contents have their own privacies).
1192 hir::ItemForeignMod(_) => {}
1194 hir::ItemTrait(_, _, ref bounds, _) => {
1195 if !self.trait_is_public(item.id) {
1199 for bound in bounds.iter() {
1200 self.check_ty_param_bound(bound)
1204 // impls need some special handling to try to offer useful
1205 // error messages without (too many) false positives
1206 // (i.e. we could just return here to not check them at
1207 // all, or some worse estimation of whether an impl is
1208 // publicly visible).
1209 hir::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1210 // `impl [... for] Private` is never visible.
1211 let self_contains_private;
1212 // impl [... for] Public<...>, but not `impl [... for]
1213 // Vec<Public>` or `(Public,)` etc.
1214 let self_is_public_path;
1216 // check the properties of the Self type:
1218 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1220 contains_private: false,
1221 at_outer_type: true,
1222 outer_type_is_public_path: false,
1224 visitor.visit_ty(&self_);
1225 self_contains_private = visitor.contains_private;
1226 self_is_public_path = visitor.outer_type_is_public_path;
1229 // miscellaneous info about the impl
1231 // `true` iff this is `impl Private for ...`.
1232 let not_private_trait =
1233 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1235 let did = self.tcx.trait_ref_to_def_id(tr);
1237 if let Some(node_id) = self.tcx.map.as_local_node_id(did) {
1238 self.trait_is_public(node_id)
1240 true // external traits must be public
1244 // `true` iff this is a trait impl or at least one method is public.
1246 // `impl Public { $( fn ...() {} )* }` is not visible.
1248 // This is required over just using the methods' privacy
1249 // directly because we might have `impl<T: Foo<Private>> ...`,
1250 // and we shouldn't warn about the generics if all the methods
1251 // are private (because `T` won't be visible externally).
1252 let trait_or_some_public_method =
1253 trait_ref.is_some() ||
1256 match impl_item.node {
1257 hir::ImplItemKind::Const(..) |
1258 hir::ImplItemKind::Method(..) => {
1259 self.access_levels.is_reachable(impl_item.id)
1261 hir::ImplItemKind::Type(_) => false,
1265 if !self_contains_private &&
1266 not_private_trait &&
1267 trait_or_some_public_method {
1269 intravisit::walk_generics(self, g);
1273 for impl_item in impl_items {
1274 // This is where we choose whether to walk down
1275 // further into the impl to check its items. We
1276 // should only walk into public items so that we
1277 // don't erroneously report errors for private
1278 // types in private items.
1279 match impl_item.node {
1280 hir::ImplItemKind::Const(..) |
1281 hir::ImplItemKind::Method(..)
1282 if self.item_is_public(&impl_item.id, impl_item.vis) =>
1284 intravisit::walk_impl_item(self, impl_item)
1286 hir::ImplItemKind::Type(..) => {
1287 intravisit::walk_impl_item(self, impl_item)
1294 // Any private types in a trait impl fall into three
1296 // 1. mentioned in the trait definition
1297 // 2. mentioned in the type params/generics
1298 // 3. mentioned in the associated types of the impl
1300 // Those in 1. can only occur if the trait is in
1301 // this crate and will've been warned about on the
1302 // trait definition (there's no need to warn twice
1303 // so we don't check the methods).
1305 // Those in 2. are warned via walk_generics and this
1307 intravisit::walk_path(self, &tr.path);
1309 // Those in 3. are warned with this call.
1310 for impl_item in impl_items {
1311 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1317 } else if trait_ref.is_none() && self_is_public_path {
1318 // impl Public<Private> { ... }. Any public static
1319 // methods will be visible as `Public::foo`.
1320 let mut found_pub_static = false;
1321 for impl_item in impl_items {
1322 match impl_item.node {
1323 hir::ImplItemKind::Const(..) => {
1324 if self.item_is_public(&impl_item.id, impl_item.vis) {
1325 found_pub_static = true;
1326 intravisit::walk_impl_item(self, impl_item);
1329 hir::ImplItemKind::Method(ref sig, _) => {
1330 if sig.explicit_self.node == hir::SelfStatic &&
1331 self.item_is_public(&impl_item.id, impl_item.vis) {
1332 found_pub_static = true;
1333 intravisit::walk_impl_item(self, impl_item);
1339 if found_pub_static {
1340 intravisit::walk_generics(self, g)
1346 // `type ... = ...;` can contain private types, because
1347 // we're introducing a new name.
1348 hir::ItemTy(..) => return,
1350 // not at all public, so we don't care
1351 _ if !self.item_is_public(&item.id, item.vis) => {
1358 // We've carefully constructed it so that if we're here, then
1359 // any `visit_ty`'s will be called on things that are in
1360 // public signatures, i.e. things that we're interested in for
1362 debug!("VisiblePrivateTypesVisitor entering item {:?}", item);
1363 intravisit::walk_item(self, item);
1366 fn visit_generics(&mut self, generics: &hir::Generics) {
1367 for ty_param in generics.ty_params.iter() {
1368 for bound in ty_param.bounds.iter() {
1369 self.check_ty_param_bound(bound)
1372 for predicate in &generics.where_clause.predicates {
1374 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1375 for bound in bound_pred.bounds.iter() {
1376 self.check_ty_param_bound(bound)
1379 &hir::WherePredicate::RegionPredicate(_) => {}
1380 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1381 self.visit_ty(&eq_pred.ty);
1387 fn visit_foreign_item(&mut self, item: &hir::ForeignItem) {
1388 if self.access_levels.is_reachable(item.id) {
1389 intravisit::walk_foreign_item(self, item)
1393 fn visit_ty(&mut self, t: &hir::Ty) {
1394 debug!("VisiblePrivateTypesVisitor checking ty {:?}", t);
1395 if let hir::TyPath(..) = t.node {
1396 if self.path_is_private_type(t.id) {
1397 self.old_error_set.insert(t.id);
1400 intravisit::walk_ty(self, t)
1403 fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics, item_id: ast::NodeId) {
1404 if self.access_levels.is_reachable(v.node.data.id()) {
1405 self.in_variant = true;
1406 intravisit::walk_variant(self, v, g, item_id);
1407 self.in_variant = false;
1411 fn visit_struct_field(&mut self, s: &hir::StructField) {
1412 let vis = match s.node.kind {
1413 hir::NamedField(_, vis) | hir::UnnamedField(vis) => vis
1415 if vis == hir::Public || self.in_variant {
1416 intravisit::walk_struct_field(self, s);
1420 // we don't need to introspect into these at all: an
1421 // expression/block context can't possibly contain exported things.
1422 // (Making them no-ops stops us from traversing the whole AST without
1423 // having to be super careful about our `walk_...` calls above.)
1424 // FIXME(#29524): Unfortunately this ^^^ is not true, blocks can contain
1425 // exported items (e.g. impls) and actual code in rustc itself breaks
1426 // if we don't traverse blocks in `EmbargoVisitor`
1427 fn visit_block(&mut self, _: &hir::Block) {}
1428 fn visit_expr(&mut self, _: &hir::Expr) {}
1431 ///////////////////////////////////////////////////////////////////////////////
1432 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1433 /// finds any private components in it.
1434 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1435 /// and traits in public interfaces.
1436 ///////////////////////////////////////////////////////////////////////////////
1438 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1439 tcx: &'a ty::ctxt<'tcx>,
1440 // Do not report an error when a private type is found
1442 // Is private component found?
1444 old_error_set: &'a NodeSet,
1447 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1448 // Check if the type alias contain private types when substituted
1449 fn is_public_type_alias(&self, item: &hir::Item, path: &hir::Path) -> bool {
1450 // We substitute type aliases only when determining impl publicity
1451 // FIXME: This will probably change and all type aliases will be substituted,
1452 // requires an amendment to RFC 136.
1456 // Type alias is considered public if the aliased type is
1457 // public, even if the type alias itself is private. So, something
1458 // like `type A = u8; pub fn f() -> A {...}` doesn't cause an error.
1459 if let hir::ItemTy(ref ty, ref generics) = item.node {
1460 let mut check = SearchInterfaceForPrivateItemsVisitor { is_public: true, ..*self };
1462 // If a private type alias with default type parameters is used in public
1463 // interface we must ensure, that the defaults are public if they are actually used.
1465 // type Alias<T = Private> = T;
1466 // pub fn f() -> Alias {...} // `Private` is implicitly used here, so it must be public
1468 let provided_params = path.segments.last().unwrap().parameters.types().len();
1469 for ty_param in &generics.ty_params[provided_params..] {
1470 if let Some(ref default_ty) = ty_param.default {
1471 check.visit_ty(default_ty);
1481 impl<'a, 'tcx: 'a, 'v> Visitor<'v> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1482 fn visit_ty(&mut self, ty: &hir::Ty) {
1483 if self.is_quiet && !self.is_public {
1484 // We are in quiet mode and a private type is already found, no need to proceed
1487 if let hir::TyPath(_, ref path) = ty.node {
1488 let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
1490 Def::PrimTy(..) | Def::SelfTy(..) | Def::TyParam(..) => {
1493 Def::AssociatedTy(..) if self.is_quiet => {
1494 // Conservatively approximate the whole type alias as public without
1495 // recursing into its components when determining impl publicity.
1496 // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
1497 // even if both `Type` and `Trait` are private.
1498 // Ideally, associated types should be substituted in the same way as
1499 // free type aliases, but this isn't done yet.
1502 Def::Struct(def_id) | Def::Enum(def_id) | Def::TyAlias(def_id) |
1503 Def::Trait(def_id) | Def::AssociatedTy(def_id, _) => {
1504 // Non-local means public (private items can't leave their crate, modulo bugs)
1505 if let Some(node_id) = self.tcx.map.as_local_node_id(def_id) {
1506 let item = self.tcx.map.expect_item(node_id);
1507 if item.vis != hir::Public && !self.is_public_type_alias(item, path) {
1509 if self.old_error_set.contains(&ty.id) {
1510 span_err!(self.tcx.sess, ty.span, E0446,
1511 "private type in public interface");
1513 self.tcx.sess.add_lint (
1514 lint::builtin::PRIVATE_IN_PUBLIC,
1517 format!("private type in public interface"),
1521 self.is_public = false;
1529 intravisit::walk_ty(self, ty);
1532 fn visit_trait_ref(&mut self, trait_ref: &hir::TraitRef) {
1533 if self.is_quiet && !self.is_public {
1534 // We are in quiet mode and a private type is already found, no need to proceed
1537 // Non-local means public (private items can't leave their crate, modulo bugs)
1538 let def_id = self.tcx.trait_ref_to_def_id(trait_ref);
1539 if let Some(node_id) = self.tcx.map.as_local_node_id(def_id) {
1540 let item = self.tcx.map.expect_item(node_id);
1541 if item.vis != hir::Public {
1543 if self.old_error_set.contains(&trait_ref.ref_id) {
1544 span_err!(self.tcx.sess, trait_ref.path.span, E0445,
1545 "private trait in public interface");
1547 self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
1549 trait_ref.path.span,
1550 "private trait in public interface (error E0445)"
1554 self.is_public = false;
1558 intravisit::walk_trait_ref(self, trait_ref);
1561 // Don't recurse into function bodies
1562 fn visit_block(&mut self, _: &hir::Block) {}
1563 // Don't recurse into expressions in array sizes or const initializers
1564 fn visit_expr(&mut self, _: &hir::Expr) {}
1565 // Don't recurse into patterns in function arguments
1566 fn visit_pat(&mut self, _: &hir::Pat) {}
1569 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1570 tcx: &'a ty::ctxt<'tcx>,
1571 old_error_set: &'a NodeSet,
1574 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1575 // A type is considered public if it doesn't contain any private components
1576 fn is_public_ty(&self, ty: &hir::Ty) -> bool {
1577 let mut check = SearchInterfaceForPrivateItemsVisitor {
1578 tcx: self.tcx, is_quiet: true, is_public: true, old_error_set: self.old_error_set
1584 // A trait reference is considered public if it doesn't contain any private components
1585 fn is_public_trait_ref(&self, trait_ref: &hir::TraitRef) -> bool {
1586 let mut check = SearchInterfaceForPrivateItemsVisitor {
1587 tcx: self.tcx, is_quiet: true, is_public: true, old_error_set: self.old_error_set
1589 check.visit_trait_ref(trait_ref);
1594 impl<'a, 'tcx, 'v> Visitor<'v> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1595 fn visit_item(&mut self, item: &hir::Item) {
1596 let mut check = SearchInterfaceForPrivateItemsVisitor {
1597 tcx: self.tcx, is_quiet: false, is_public: true, old_error_set: self.old_error_set
1600 // Crates are always public
1601 hir::ItemExternCrate(..) => {}
1602 // All nested items are checked by visit_item
1603 hir::ItemMod(..) => {}
1604 // Checked in resolve
1605 hir::ItemUse(..) => {}
1606 // Subitems of these items have inherited publicity
1607 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1608 hir::ItemEnum(..) | hir::ItemTrait(..) | hir::ItemTy(..) => {
1609 if item.vis == hir::Public {
1610 check.visit_item(item);
1613 // Subitems of foreign modules have their own publicity
1614 hir::ItemForeignMod(ref foreign_mod) => {
1615 for foreign_item in &foreign_mod.items {
1616 if foreign_item.vis == hir::Public {
1617 check.visit_foreign_item(foreign_item);
1621 // Subitems of structs have their own publicity
1622 hir::ItemStruct(ref struct_def, ref generics) => {
1623 if item.vis == hir::Public {
1624 check.visit_generics(generics);
1625 for field in struct_def.fields() {
1626 if field.node.kind.visibility() == hir::Public {
1627 check.visit_struct_field(field);
1632 // The interface is empty
1633 hir::ItemDefaultImpl(..) => {}
1634 // An inherent impl is public when its type is public
1635 // Subitems of inherent impls have their own publicity
1636 hir::ItemImpl(_, _, ref generics, None, ref ty, ref impl_items) => {
1637 if self.is_public_ty(ty) {
1638 check.visit_generics(generics);
1639 for impl_item in impl_items {
1640 if impl_item.vis == hir::Public {
1641 check.visit_impl_item(impl_item);
1646 // A trait impl is public when both its type and its trait are public
1647 // Subitems of trait impls have inherited publicity
1648 hir::ItemImpl(_, _, ref generics, Some(ref trait_ref), ref ty, ref impl_items) => {
1649 if self.is_public_ty(ty) && self.is_public_trait_ref(trait_ref) {
1650 check.visit_generics(generics);
1651 for impl_item in impl_items {
1652 check.visit_impl_item(impl_item);
1660 pub fn check_crate(tcx: &ty::ctxt,
1661 export_map: &def::ExportMap,
1662 external_exports: ExternalExports)
1664 let _task = tcx.dep_graph.in_task(DepNode::Privacy);
1666 let krate = tcx.map.krate();
1668 // Sanity check to make sure that all privacy usage and controls are
1670 let mut visitor = SanePrivacyVisitor {
1674 intravisit::walk_crate(&mut visitor, krate);
1676 // Figure out who everyone's parent is
1677 let mut visitor = ParentVisitor {
1680 curparent: ast::DUMMY_NODE_ID,
1682 intravisit::walk_crate(&mut visitor, krate);
1684 // Use the parent map to check the privacy of everything
1685 let mut visitor = PrivacyVisitor {
1686 curitem: ast::DUMMY_NODE_ID,
1689 parents: visitor.parents,
1690 external_exports: external_exports,
1692 intravisit::walk_crate(&mut visitor, krate);
1694 tcx.sess.abort_if_errors();
1696 // Build up a set of all exported items in the AST. This is a set of all
1697 // items which are reachable from external crates based on visibility.
1698 let mut visitor = EmbargoVisitor {
1700 export_map: export_map,
1701 access_levels: Default::default(),
1702 prev_level: Some(AccessLevel::Public),
1706 intravisit::walk_crate(&mut visitor, krate);
1707 if visitor.changed {
1708 visitor.changed = false;
1713 visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1716 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1718 access_levels: &visitor.access_levels,
1720 old_error_set: NodeSet(),
1722 intravisit::walk_crate(&mut visitor, krate);
1724 // Check for private types and traits in public interfaces
1725 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1727 old_error_set: &visitor.old_error_set,
1729 krate.visit_all_items(&mut visitor);
1732 visitor.access_levels
1735 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }