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 #![crate_type = "dylib"]
13 #![crate_type = "rlib"]
14 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
15 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
16 html_root_url = "https://doc.rust-lang.org/nightly/")]
19 #![feature(rustc_diagnostic_macros)]
21 #![cfg_attr(stage0, unstable(feature = "rustc_private", issue = "27812"))]
22 #![cfg_attr(stage0, feature(rustc_private))]
23 #![cfg_attr(stage0, feature(staged_api))]
26 #[macro_use] extern crate syntax;
27 extern crate syntax_pos;
29 use rustc::hir::{self, PatKind};
30 use rustc::hir::def::Def;
31 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
32 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
33 use rustc::hir::itemlikevisit::DeepVisitor;
35 use rustc::middle::privacy::{AccessLevel, AccessLevels};
36 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable};
37 use rustc::ty::fold::TypeVisitor;
38 use rustc::ty::maps::Providers;
39 use rustc::util::nodemap::NodeSet;
44 use std::mem::replace;
49 ////////////////////////////////////////////////////////////////////////////////
50 /// Visitor used to determine if pub(restricted) is used anywhere in the crate.
52 /// This is done so that `private_in_public` warnings can be turned into hard errors
53 /// in crates that have been updated to use pub(restricted).
54 ////////////////////////////////////////////////////////////////////////////////
55 struct PubRestrictedVisitor<'a, 'tcx: 'a> {
56 tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 has_pub_restricted: bool,
60 impl<'a, 'tcx> Visitor<'tcx> for PubRestrictedVisitor<'a, 'tcx> {
61 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
62 NestedVisitorMap::All(&self.tcx.hir)
64 fn visit_vis(&mut self, vis: &'tcx hir::Visibility) {
65 self.has_pub_restricted = self.has_pub_restricted || vis.is_pub_restricted();
69 ////////////////////////////////////////////////////////////////////////////////
70 /// The embargo visitor, used to determine the exports of the ast
71 ////////////////////////////////////////////////////////////////////////////////
73 struct EmbargoVisitor<'a, 'tcx: 'a> {
74 tcx: TyCtxt<'a, 'tcx, 'tcx>,
76 // Accessibility levels for reachable nodes
77 access_levels: AccessLevels,
78 // Previous accessibility level, None means unreachable
79 prev_level: Option<AccessLevel>,
80 // Have something changed in the level map?
84 struct ReachEverythingInTheInterfaceVisitor<'b, 'a: 'b, 'tcx: 'a> {
86 ev: &'b mut EmbargoVisitor<'a, 'tcx>,
89 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
90 fn item_ty_level(&self, item_def_id: DefId) -> Option<AccessLevel> {
91 let ty_def_id = match self.tcx.type_of(item_def_id).sty {
92 ty::TyAdt(adt, _) => adt.did,
93 ty::TyDynamic(ref obj, ..) if obj.principal().is_some() =>
94 obj.principal().unwrap().def_id(),
95 ty::TyProjection(ref proj) => proj.trait_ref.def_id,
96 _ => return Some(AccessLevel::Public)
98 if let Some(node_id) = self.tcx.hir.as_local_node_id(ty_def_id) {
101 Some(AccessLevel::Public)
105 fn impl_trait_level(&self, impl_def_id: DefId) -> Option<AccessLevel> {
106 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_def_id) {
107 if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
108 return self.get(node_id);
111 Some(AccessLevel::Public)
114 fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
115 self.access_levels.map.get(&id).cloned()
118 // Updates node level and returns the updated level
119 fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
120 let old_level = self.get(id);
121 // Accessibility levels can only grow
122 if level > old_level {
123 self.access_levels.map.insert(id, level.unwrap());
131 fn reach<'b>(&'b mut self, item_id: ast::NodeId)
132 -> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
133 ReachEverythingInTheInterfaceVisitor {
134 item_def_id: self.tcx.hir.local_def_id(item_id),
140 impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> {
141 /// We want to visit items in the context of their containing
142 /// module and so forth, so supply a crate for doing a deep walk.
143 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
144 NestedVisitorMap::All(&self.tcx.hir)
147 fn visit_item(&mut self, item: &'tcx hir::Item) {
148 let inherited_item_level = match item.node {
149 // Impls inherit level from their types and traits
150 hir::ItemImpl(..) => {
151 let def_id = self.tcx.hir.local_def_id(item.id);
152 cmp::min(self.item_ty_level(def_id), self.impl_trait_level(def_id))
154 hir::ItemDefaultImpl(..) => {
155 let def_id = self.tcx.hir.local_def_id(item.id);
156 self.impl_trait_level(def_id)
158 // Foreign mods inherit level from parents
159 hir::ItemForeignMod(..) => {
162 // Other `pub` items inherit levels from parents
163 hir::ItemConst(..) | hir::ItemEnum(..) | hir::ItemExternCrate(..) |
164 hir::ItemGlobalAsm(..) | hir::ItemFn(..) | hir::ItemMod(..) |
165 hir::ItemStatic(..) | hir::ItemStruct(..) | hir::ItemTrait(..) |
166 hir::ItemTy(..) | hir::ItemUnion(..) | hir::ItemUse(..) => {
167 if item.vis == hir::Public { self.prev_level } else { None }
171 // Update level of the item itself
172 let item_level = self.update(item.id, inherited_item_level);
174 // Update levels of nested things
176 hir::ItemEnum(ref def, _) => {
177 for variant in &def.variants {
178 let variant_level = self.update(variant.node.data.id(), item_level);
179 for field in variant.node.data.fields() {
180 self.update(field.id, variant_level);
184 hir::ItemImpl(.., None, _, ref impl_item_refs) => {
185 for impl_item_ref in impl_item_refs {
186 if impl_item_ref.vis == hir::Public {
187 self.update(impl_item_ref.id.node_id, item_level);
191 hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
192 for impl_item_ref in impl_item_refs {
193 self.update(impl_item_ref.id.node_id, item_level);
196 hir::ItemTrait(.., ref trait_item_refs) => {
197 for trait_item_ref in trait_item_refs {
198 self.update(trait_item_ref.id.node_id, item_level);
201 hir::ItemStruct(ref def, _) | hir::ItemUnion(ref def, _) => {
202 if !def.is_struct() {
203 self.update(def.id(), item_level);
205 for field in def.fields() {
206 if field.vis == hir::Public {
207 self.update(field.id, item_level);
211 hir::ItemForeignMod(ref foreign_mod) => {
212 for foreign_item in &foreign_mod.items {
213 if foreign_item.vis == hir::Public {
214 self.update(foreign_item.id, item_level);
218 hir::ItemUse(..) | hir::ItemStatic(..) | hir::ItemConst(..) |
219 hir::ItemGlobalAsm(..) | hir::ItemTy(..) | hir::ItemMod(..) |
220 hir::ItemFn(..) | hir::ItemExternCrate(..) | hir::ItemDefaultImpl(..) => {}
223 // Mark all items in interfaces of reachable items as reachable
225 // The interface is empty
226 hir::ItemExternCrate(..) => {}
227 // All nested items are checked by visit_item
228 hir::ItemMod(..) => {}
229 // Reexports are handled in visit_mod
230 hir::ItemUse(..) => {}
231 // The interface is empty
232 hir::ItemDefaultImpl(..) => {}
233 // The interface is empty
234 hir::ItemGlobalAsm(..) => {}
236 hir::ItemConst(..) | hir::ItemStatic(..) |
237 hir::ItemFn(..) | hir::ItemTy(..) => {
238 if item_level.is_some() {
239 self.reach(item.id).generics().predicates().ty();
242 hir::ItemTrait(.., ref trait_item_refs) => {
243 if item_level.is_some() {
244 self.reach(item.id).generics().predicates();
246 for trait_item_ref in trait_item_refs {
247 let mut reach = self.reach(trait_item_ref.id.node_id);
248 reach.generics().predicates();
250 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
251 !trait_item_ref.defaultness.has_value() {
259 // Visit everything except for private impl items
260 hir::ItemImpl(.., ref trait_ref, _, ref impl_item_refs) => {
261 if item_level.is_some() {
262 self.reach(item.id).generics().predicates().impl_trait_ref();
264 for impl_item_ref in impl_item_refs {
265 let id = impl_item_ref.id.node_id;
266 if trait_ref.is_some() || self.get(id).is_some() {
267 self.reach(id).generics().predicates().ty();
273 // Visit everything, but enum variants have their own levels
274 hir::ItemEnum(ref def, _) => {
275 if item_level.is_some() {
276 self.reach(item.id).generics().predicates();
278 for variant in &def.variants {
279 if self.get(variant.node.data.id()).is_some() {
280 for field in variant.node.data.fields() {
281 self.reach(field.id).ty();
283 // Corner case: if the variant is reachable, but its
284 // enum is not, make the enum reachable as well.
285 self.update(item.id, Some(AccessLevel::Reachable));
289 // Visit everything, but foreign items have their own levels
290 hir::ItemForeignMod(ref foreign_mod) => {
291 for foreign_item in &foreign_mod.items {
292 if self.get(foreign_item.id).is_some() {
293 self.reach(foreign_item.id).generics().predicates().ty();
297 // Visit everything except for private fields
298 hir::ItemStruct(ref struct_def, _) |
299 hir::ItemUnion(ref struct_def, _) => {
300 if item_level.is_some() {
301 self.reach(item.id).generics().predicates();
302 for field in struct_def.fields() {
303 if self.get(field.id).is_some() {
304 self.reach(field.id).ty();
311 let orig_level = self.prev_level;
312 self.prev_level = item_level;
314 intravisit::walk_item(self, item);
316 self.prev_level = orig_level;
319 fn visit_block(&mut self, b: &'tcx hir::Block) {
320 let orig_level = replace(&mut self.prev_level, None);
322 // Blocks can have public items, for example impls, but they always
323 // start as completely private regardless of publicity of a function,
324 // constant, type, field, etc. in which this block resides
325 intravisit::walk_block(self, b);
327 self.prev_level = orig_level;
330 fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
331 // This code is here instead of in visit_item so that the
332 // crate module gets processed as well.
333 if self.prev_level.is_some() {
334 if let Some(exports) = self.tcx.export_map.get(&id) {
335 for export in exports {
336 if let Some(node_id) = self.tcx.hir.as_local_node_id(export.def.def_id()) {
337 self.update(node_id, Some(AccessLevel::Exported));
343 intravisit::walk_mod(self, m, id);
346 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
347 self.update(md.id, Some(AccessLevel::Public));
350 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
351 if let hir::TyImplTrait(..) = ty.node {
352 if self.get(ty.id).is_some() {
353 // Reach the (potentially private) type and the API being exposed.
354 self.reach(ty.id).ty().predicates();
358 intravisit::walk_ty(self, ty);
362 impl<'b, 'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
363 fn generics(&mut self) -> &mut Self {
364 for def in &self.ev.tcx.generics_of(self.item_def_id).types {
366 self.ev.tcx.type_of(def.def_id).visit_with(self);
372 fn predicates(&mut self) -> &mut Self {
373 self.ev.tcx.predicates_of(self.item_def_id).visit_with(self);
377 fn ty(&mut self) -> &mut Self {
378 self.ev.tcx.type_of(self.item_def_id).visit_with(self);
382 fn impl_trait_ref(&mut self) -> &mut Self {
383 self.ev.tcx.impl_trait_ref(self.item_def_id).visit_with(self);
388 impl<'b, 'a, 'tcx> TypeVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
389 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
390 let ty_def_id = match ty.sty {
391 ty::TyAdt(adt, _) => Some(adt.did),
392 ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
393 ty::TyProjection(ref proj) => Some(proj.trait_ref.def_id),
394 ty::TyFnDef(def_id, ..) |
395 ty::TyAnon(def_id, _) => Some(def_id),
399 if let Some(def_id) = ty_def_id {
400 if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(def_id) {
401 self.ev.update(node_id, Some(AccessLevel::Reachable));
405 ty.super_visit_with(self)
408 fn visit_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
409 if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(trait_ref.def_id) {
410 let item = self.ev.tcx.hir.expect_item(node_id);
411 self.ev.update(item.id, Some(AccessLevel::Reachable));
414 trait_ref.super_visit_with(self)
418 //////////////////////////////////////////////////////////////////////////////////////
419 /// Name privacy visitor, checks privacy and reports violations.
420 /// Most of name privacy checks are performed during the main resolution phase,
421 /// or later in type checking when field accesses and associated items are resolved.
422 /// This pass performs remaining checks for fields in struct expressions and patterns.
423 //////////////////////////////////////////////////////////////////////////////////////
425 struct NamePrivacyVisitor<'a, 'tcx: 'a> {
426 tcx: TyCtxt<'a, 'tcx, 'tcx>,
427 tables: &'a ty::TypeckTables<'tcx>,
431 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
432 // Checks that a field is accessible.
433 fn check_field(&mut self, span: Span, def: &'tcx ty::AdtDef, field: &'tcx ty::FieldDef) {
434 if !def.is_enum() && !field.vis.is_accessible_from(self.current_item, self.tcx) {
435 struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
436 field.name, def.variant_descr(), self.tcx.item_path_str(def.did))
437 .span_label(span, format!("field `{}` is private", field.name))
443 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
444 /// We want to visit items in the context of their containing
445 /// module and so forth, so supply a crate for doing a deep walk.
446 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
447 NestedVisitorMap::All(&self.tcx.hir)
450 fn visit_nested_body(&mut self, body: hir::BodyId) {
451 let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
452 let body = self.tcx.hir.body(body);
453 self.visit_body(body);
454 self.tables = orig_tables;
457 fn visit_item(&mut self, item: &'tcx hir::Item) {
458 let orig_current_item = replace(&mut self.current_item, self.tcx.hir.local_def_id(item.id));
459 intravisit::walk_item(self, item);
460 self.current_item = orig_current_item;
463 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
465 hir::ExprStruct(ref qpath, ref fields, ref base) => {
466 let def = self.tables.qpath_def(qpath, expr.id);
467 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
468 let variant = adt.variant_of_def(def);
469 if let Some(ref base) = *base {
470 // If the expression uses FRU we need to make sure all the unmentioned fields
471 // are checked for privacy (RFC 736). Rather than computing the set of
472 // unmentioned fields, just check them all.
473 for variant_field in &variant.fields {
474 let field = fields.iter().find(|f| f.name.node == variant_field.name);
475 let span = if let Some(f) = field { f.span } else { base.span };
476 self.check_field(span, adt, variant_field);
479 for field in fields {
480 self.check_field(field.span, adt, variant.field_named(field.name.node));
487 intravisit::walk_expr(self, expr);
490 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
492 PatKind::Struct(ref qpath, ref fields, _) => {
493 let def = self.tables.qpath_def(qpath, pat.id);
494 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
495 let variant = adt.variant_of_def(def);
496 for field in fields {
497 self.check_field(field.span, adt, variant.field_named(field.node.name));
503 intravisit::walk_pat(self, pat);
507 ///////////////////////////////////////////////////////////////////////////////
508 /// Obsolete visitors for checking for private items in public interfaces.
509 /// These visitors are supposed to be kept in frozen state and produce an
510 /// "old error node set". For backward compatibility the new visitor reports
511 /// warnings instead of hard errors when the erroneous node is not in this old set.
512 ///////////////////////////////////////////////////////////////////////////////
514 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
515 tcx: TyCtxt<'a, 'tcx, 'tcx>,
516 access_levels: &'a AccessLevels,
518 // set of errors produced by this obsolete visitor
519 old_error_set: NodeSet,
522 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
523 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
524 /// whether the type refers to private types.
525 contains_private: bool,
526 /// whether we've recurred at all (i.e. if we're pointing at the
527 /// first type on which visit_ty was called).
529 // whether that first type is a public path.
530 outer_type_is_public_path: bool,
533 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
534 fn path_is_private_type(&self, path: &hir::Path) -> bool {
535 let did = match path.def {
536 Def::PrimTy(..) | Def::SelfTy(..) => return false,
540 // A path can only be private if:
541 // it's in this crate...
542 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
543 // .. and it corresponds to a private type in the AST (this returns
544 // None for type parameters)
545 match self.tcx.hir.find(node_id) {
546 Some(hir::map::NodeItem(ref item)) => item.vis != hir::Public,
547 Some(_) | None => false,
554 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
555 // FIXME: this would preferably be using `exported_items`, but all
556 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
557 self.access_levels.is_public(trait_id)
560 fn check_ty_param_bound(&mut self,
561 ty_param_bound: &hir::TyParamBound) {
562 if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
563 if self.path_is_private_type(&trait_ref.trait_ref.path) {
564 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
569 fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
570 self.access_levels.is_reachable(*id) || *vis == hir::Public
574 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
575 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
576 NestedVisitorMap::None
579 fn visit_ty(&mut self, ty: &hir::Ty) {
580 if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = ty.node {
581 if self.inner.path_is_private_type(path) {
582 self.contains_private = true;
583 // found what we're looking for so let's stop
588 if let hir::TyPath(_) = ty.node {
589 if self.at_outer_type {
590 self.outer_type_is_public_path = true;
593 self.at_outer_type = false;
594 intravisit::walk_ty(self, ty)
597 // don't want to recurse into [, .. expr]
598 fn visit_expr(&mut self, _: &hir::Expr) {}
601 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
602 /// We want to visit items in the context of their containing
603 /// module and so forth, so supply a crate for doing a deep walk.
604 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
605 NestedVisitorMap::All(&self.tcx.hir)
608 fn visit_item(&mut self, item: &'tcx hir::Item) {
610 // contents of a private mod can be reexported, so we need
611 // to check internals.
612 hir::ItemMod(_) => {}
614 // An `extern {}` doesn't introduce a new privacy
615 // namespace (the contents have their own privacies).
616 hir::ItemForeignMod(_) => {}
618 hir::ItemTrait(.., ref bounds, _) => {
619 if !self.trait_is_public(item.id) {
623 for bound in bounds.iter() {
624 self.check_ty_param_bound(bound)
628 // impls need some special handling to try to offer useful
629 // error messages without (too many) false positives
630 // (i.e. we could just return here to not check them at
631 // all, or some worse estimation of whether an impl is
632 // publicly visible).
633 hir::ItemImpl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
634 // `impl [... for] Private` is never visible.
635 let self_contains_private;
636 // impl [... for] Public<...>, but not `impl [... for]
637 // Vec<Public>` or `(Public,)` etc.
638 let self_is_public_path;
640 // check the properties of the Self type:
642 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
644 contains_private: false,
646 outer_type_is_public_path: false,
648 visitor.visit_ty(&self_);
649 self_contains_private = visitor.contains_private;
650 self_is_public_path = visitor.outer_type_is_public_path;
653 // miscellaneous info about the impl
655 // `true` iff this is `impl Private for ...`.
656 let not_private_trait =
657 trait_ref.as_ref().map_or(true, // no trait counts as public trait
659 let did = tr.path.def.def_id();
661 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
662 self.trait_is_public(node_id)
664 true // external traits must be public
668 // `true` iff this is a trait impl or at least one method is public.
670 // `impl Public { $( fn ...() {} )* }` is not visible.
672 // This is required over just using the methods' privacy
673 // directly because we might have `impl<T: Foo<Private>> ...`,
674 // and we shouldn't warn about the generics if all the methods
675 // are private (because `T` won't be visible externally).
676 let trait_or_some_public_method =
677 trait_ref.is_some() ||
678 impl_item_refs.iter()
679 .any(|impl_item_ref| {
680 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
681 match impl_item.node {
682 hir::ImplItemKind::Const(..) |
683 hir::ImplItemKind::Method(..) => {
684 self.access_levels.is_reachable(impl_item.id)
686 hir::ImplItemKind::Type(_) => false,
690 if !self_contains_private &&
692 trait_or_some_public_method {
694 intravisit::walk_generics(self, g);
698 for impl_item_ref in impl_item_refs {
699 // This is where we choose whether to walk down
700 // further into the impl to check its items. We
701 // should only walk into public items so that we
702 // don't erroneously report errors for private
703 // types in private items.
704 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
705 match impl_item.node {
706 hir::ImplItemKind::Const(..) |
707 hir::ImplItemKind::Method(..)
708 if self.item_is_public(&impl_item.id, &impl_item.vis) =>
710 intravisit::walk_impl_item(self, impl_item)
712 hir::ImplItemKind::Type(..) => {
713 intravisit::walk_impl_item(self, impl_item)
720 // Any private types in a trait impl fall into three
722 // 1. mentioned in the trait definition
723 // 2. mentioned in the type params/generics
724 // 3. mentioned in the associated types of the impl
726 // Those in 1. can only occur if the trait is in
727 // this crate and will've been warned about on the
728 // trait definition (there's no need to warn twice
729 // so we don't check the methods).
731 // Those in 2. are warned via walk_generics and this
733 intravisit::walk_path(self, &tr.path);
735 // Those in 3. are warned with this call.
736 for impl_item_ref in impl_item_refs {
737 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
738 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
744 } else if trait_ref.is_none() && self_is_public_path {
745 // impl Public<Private> { ... }. Any public static
746 // methods will be visible as `Public::foo`.
747 let mut found_pub_static = false;
748 for impl_item_ref in impl_item_refs {
749 if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
750 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
751 match impl_item_ref.kind {
752 hir::AssociatedItemKind::Const => {
753 found_pub_static = true;
754 intravisit::walk_impl_item(self, impl_item);
756 hir::AssociatedItemKind::Method { has_self: false } => {
757 found_pub_static = true;
758 intravisit::walk_impl_item(self, impl_item);
764 if found_pub_static {
765 intravisit::walk_generics(self, g)
771 // `type ... = ...;` can contain private types, because
772 // we're introducing a new name.
773 hir::ItemTy(..) => return,
775 // not at all public, so we don't care
776 _ if !self.item_is_public(&item.id, &item.vis) => {
783 // We've carefully constructed it so that if we're here, then
784 // any `visit_ty`'s will be called on things that are in
785 // public signatures, i.e. things that we're interested in for
787 intravisit::walk_item(self, item);
790 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
791 for ty_param in generics.ty_params.iter() {
792 for bound in ty_param.bounds.iter() {
793 self.check_ty_param_bound(bound)
796 for predicate in &generics.where_clause.predicates {
798 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
799 for bound in bound_pred.bounds.iter() {
800 self.check_ty_param_bound(bound)
803 &hir::WherePredicate::RegionPredicate(_) => {}
804 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
805 self.visit_ty(&eq_pred.rhs_ty);
811 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
812 if self.access_levels.is_reachable(item.id) {
813 intravisit::walk_foreign_item(self, item)
817 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
818 if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = t.node {
819 if self.path_is_private_type(path) {
820 self.old_error_set.insert(t.id);
823 intravisit::walk_ty(self, t)
826 fn visit_variant(&mut self,
827 v: &'tcx hir::Variant,
828 g: &'tcx hir::Generics,
829 item_id: ast::NodeId) {
830 if self.access_levels.is_reachable(v.node.data.id()) {
831 self.in_variant = true;
832 intravisit::walk_variant(self, v, g, item_id);
833 self.in_variant = false;
837 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
838 if s.vis == hir::Public || self.in_variant {
839 intravisit::walk_struct_field(self, s);
843 // we don't need to introspect into these at all: an
844 // expression/block context can't possibly contain exported things.
845 // (Making them no-ops stops us from traversing the whole AST without
846 // having to be super careful about our `walk_...` calls above.)
847 fn visit_block(&mut self, _: &'tcx hir::Block) {}
848 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
851 ///////////////////////////////////////////////////////////////////////////////
852 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
853 /// finds any private components in it.
854 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
855 /// and traits in public interfaces.
856 ///////////////////////////////////////////////////////////////////////////////
858 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
859 tcx: TyCtxt<'a, 'tcx, 'tcx>,
862 /// The visitor checks that each component type is at least this visible
863 required_visibility: ty::Visibility,
864 /// The visibility of the least visible component that has been visited
865 min_visibility: ty::Visibility,
866 has_pub_restricted: bool,
867 has_old_errors: bool,
870 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
871 fn generics(&mut self) -> &mut Self {
872 for def in &self.tcx.generics_of(self.item_def_id).types {
874 self.tcx.type_of(def.def_id).visit_with(self);
880 fn predicates(&mut self) -> &mut Self {
881 self.tcx.predicates_of(self.item_def_id).visit_with(self);
885 fn ty(&mut self) -> &mut Self {
886 self.tcx.type_of(self.item_def_id).visit_with(self);
890 fn impl_trait_ref(&mut self) -> &mut Self {
891 self.tcx.impl_trait_ref(self.item_def_id).visit_with(self);
896 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
897 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
898 let ty_def_id = match ty.sty {
899 ty::TyAdt(adt, _) => Some(adt.did),
900 ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
901 ty::TyProjection(ref proj) => {
902 if self.required_visibility == ty::Visibility::Invisible {
903 // Conservatively approximate the whole type alias as public without
904 // recursing into its components when determining impl publicity.
905 // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
906 // even if both `Type` and `Trait` are private.
907 // Ideally, associated types should be substituted in the same way as
908 // free type aliases, but this isn't done yet.
912 Some(proj.trait_ref.def_id)
917 if let Some(def_id) = ty_def_id {
918 // Non-local means public (private items can't leave their crate, modulo bugs)
919 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
920 let item = self.tcx.hir.expect_item(node_id);
921 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
923 if !vis.is_at_least(self.min_visibility, self.tcx) {
924 self.min_visibility = vis;
926 if !vis.is_at_least(self.required_visibility, self.tcx) {
927 if self.has_pub_restricted || self.has_old_errors {
928 let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
929 "private type `{}` in public interface", ty);
930 err.span_label(self.span, "can't leak private type");
933 self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
936 format!("private type `{}` in public \
937 interface (error E0446)", ty));
943 if let ty::TyProjection(ref proj) = ty.sty {
944 // Avoid calling `visit_trait_ref` below on the trait,
945 // as we have already checked the trait itself above.
946 proj.trait_ref.super_visit_with(self)
948 ty.super_visit_with(self)
952 fn visit_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
953 // Non-local means public (private items can't leave their crate, modulo bugs)
954 if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
955 let item = self.tcx.hir.expect_item(node_id);
956 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
958 if !vis.is_at_least(self.min_visibility, self.tcx) {
959 self.min_visibility = vis;
961 if !vis.is_at_least(self.required_visibility, self.tcx) {
962 if self.has_pub_restricted || self.has_old_errors {
963 struct_span_err!(self.tcx.sess, self.span, E0445,
964 "private trait `{}` in public interface", trait_ref)
965 .span_label(self.span, format!(
966 "private trait can't be public"))
969 self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
972 format!("private trait `{}` in public \
973 interface (error E0445)", trait_ref));
978 trait_ref.super_visit_with(self)
982 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
983 tcx: TyCtxt<'a, 'tcx, 'tcx>,
984 has_pub_restricted: bool,
985 old_error_set: &'a NodeSet,
986 inner_visibility: ty::Visibility,
989 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
990 fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
991 -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
992 let mut has_old_errors = false;
994 // Slow path taken only if there any errors in the crate.
995 for &id in self.old_error_set {
996 // Walk up the nodes until we find `item_id` (or we hit a root).
1000 has_old_errors = true;
1003 let parent = self.tcx.hir.get_parent_node(id);
1015 SearchInterfaceForPrivateItemsVisitor {
1017 item_def_id: self.tcx.hir.local_def_id(item_id),
1018 span: self.tcx.hir.span(item_id),
1019 min_visibility: ty::Visibility::Public,
1020 required_visibility: required_visibility,
1021 has_pub_restricted: self.has_pub_restricted,
1022 has_old_errors: has_old_errors,
1027 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1028 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1029 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
1032 fn visit_item(&mut self, item: &'tcx hir::Item) {
1034 let min = |vis1: ty::Visibility, vis2| {
1035 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1038 let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1041 // Crates are always public
1042 hir::ItemExternCrate(..) => {}
1043 // All nested items are checked by visit_item
1044 hir::ItemMod(..) => {}
1045 // Checked in resolve
1046 hir::ItemUse(..) => {}
1048 hir::ItemGlobalAsm(..) => {}
1049 // Subitems of these items have inherited publicity
1050 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1051 hir::ItemTy(..) => {
1052 self.check(item.id, item_visibility).generics().predicates().ty();
1054 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1055 self.inner_visibility = item_visibility;
1056 intravisit::walk_item(self, item);
1058 hir::ItemTrait(.., ref trait_item_refs) => {
1059 self.check(item.id, item_visibility).generics().predicates();
1061 for trait_item_ref in trait_item_refs {
1062 let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1063 check.generics().predicates();
1065 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1066 !trait_item_ref.defaultness.has_value() {
1067 // No type to visit.
1073 hir::ItemEnum(ref def, _) => {
1074 self.check(item.id, item_visibility).generics().predicates();
1076 for variant in &def.variants {
1077 for field in variant.node.data.fields() {
1078 self.check(field.id, item_visibility).ty();
1082 // Subitems of foreign modules have their own publicity
1083 hir::ItemForeignMod(ref foreign_mod) => {
1084 for foreign_item in &foreign_mod.items {
1085 let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1086 self.check(foreign_item.id, vis).generics().predicates().ty();
1089 // Subitems of structs and unions have their own publicity
1090 hir::ItemStruct(ref struct_def, _) |
1091 hir::ItemUnion(ref struct_def, _) => {
1092 self.check(item.id, item_visibility).generics().predicates();
1094 for field in struct_def.fields() {
1095 let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1096 self.check(field.id, min(item_visibility, field_visibility)).ty();
1099 // The interface is empty
1100 hir::ItemDefaultImpl(..) => {}
1101 // An inherent impl is public when its type is public
1102 // Subitems of inherent impls have their own publicity
1103 hir::ItemImpl(.., None, _, ref impl_item_refs) => {
1105 self.check(item.id, ty::Visibility::Invisible).ty().min_visibility;
1106 self.check(item.id, ty_vis).generics().predicates();
1108 for impl_item_ref in impl_item_refs {
1109 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1111 ty::Visibility::from_hir(&impl_item.vis, item.id, tcx);
1112 self.check(impl_item.id, min(impl_item_vis, ty_vis))
1113 .generics().predicates().ty();
1115 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1116 self.inner_visibility = impl_item_vis;
1117 intravisit::walk_impl_item(self, impl_item);
1120 // A trait impl is public when both its type and its trait are public
1121 // Subitems of trait impls have inherited publicity
1122 hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
1123 let vis = self.check(item.id, ty::Visibility::Invisible)
1124 .ty().impl_trait_ref().min_visibility;
1125 self.check(item.id, vis).generics().predicates();
1126 for impl_item_ref in impl_item_refs {
1127 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1128 self.check(impl_item.id, vis).generics().predicates().ty();
1130 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1131 self.inner_visibility = vis;
1132 intravisit::walk_impl_item(self, impl_item);
1138 fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
1139 // handled in `visit_item` above
1142 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1143 if let hir::TyImplTrait(..) = ty.node {
1144 // Check the traits being exposed, as they're separate,
1145 // e.g. `impl Iterator<Item=T>` has two predicates,
1146 // `X: Iterator` and `<X as Iterator>::Item == T`,
1147 // where `X` is the `impl Iterator<Item=T>` itself,
1148 // stored in `predicates_of`, not in the `Ty` itself.
1149 self.check(ty.id, self.inner_visibility).predicates();
1152 intravisit::walk_ty(self, ty);
1155 // Don't recurse into expressions in array sizes or const initializers
1156 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1157 // Don't recurse into patterns in function arguments
1158 fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
1161 pub fn provide(providers: &mut Providers) {
1162 *providers = Providers {
1163 privacy_access_levels,
1168 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Rc<AccessLevels> {
1169 tcx.dep_graph.with_ignore(|| { // FIXME
1170 tcx.privacy_access_levels(LOCAL_CRATE)
1174 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1176 -> Rc<AccessLevels> {
1177 assert_eq!(krate, LOCAL_CRATE);
1179 let krate = tcx.hir.krate();
1181 // Check privacy of names not checked in previous compilation stages.
1182 let mut visitor = NamePrivacyVisitor {
1184 tables: &ty::TypeckTables::empty(),
1185 current_item: DefId::local(CRATE_DEF_INDEX),
1187 intravisit::walk_crate(&mut visitor, krate);
1189 // Build up a set of all exported items in the AST. This is a set of all
1190 // items which are reachable from external crates based on visibility.
1191 let mut visitor = EmbargoVisitor {
1193 access_levels: Default::default(),
1194 prev_level: Some(AccessLevel::Public),
1198 intravisit::walk_crate(&mut visitor, krate);
1199 if visitor.changed {
1200 visitor.changed = false;
1205 visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1208 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1210 access_levels: &visitor.access_levels,
1212 old_error_set: NodeSet(),
1214 intravisit::walk_crate(&mut visitor, krate);
1217 let has_pub_restricted = {
1218 let mut pub_restricted_visitor = PubRestrictedVisitor {
1220 has_pub_restricted: false
1222 intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1223 pub_restricted_visitor.has_pub_restricted
1226 // Check for private types and traits in public interfaces
1227 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1229 has_pub_restricted: has_pub_restricted,
1230 old_error_set: &visitor.old_error_set,
1231 inner_visibility: ty::Visibility::Public,
1233 krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1236 Rc::new(visitor.access_levels)
1239 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }