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/")]
20 #![feature(rustc_diagnostic_macros)]
21 #![feature(rustc_private)]
22 #![feature(staged_api)]
25 #[macro_use] extern crate syntax;
26 extern crate syntax_pos;
28 use rustc::hir::{self, PatKind};
29 use rustc::hir::def::Def;
30 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
31 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
32 use rustc::hir::itemlikevisit::DeepVisitor;
33 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
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;
41 use syntax_pos::{DUMMY_SP, Span};
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.item_type(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().item_type();
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().item_type();
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).item_type();
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().item_type();
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).item_type();
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).item_type().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.item_generics(self.item_def_id).types {
366 self.ev.tcx.item_type(def.def_id).visit_with(self);
372 fn predicates(&mut self) -> &mut Self {
373 self.ev.tcx.item_predicates(self.item_def_id).visit_with(self);
377 fn item_type(&mut self) -> &mut Self {
378 self.ev.tcx.item_type(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 /// The privacy visitor, where privacy checks take place (violations reported)
420 ////////////////////////////////////////////////////////////////////////////////
422 struct PrivacyVisitor<'a, 'tcx: 'a> {
423 tcx: TyCtxt<'a, 'tcx, 'tcx>,
426 tables: &'a ty::TypeckTables<'tcx>,
429 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
430 fn item_is_accessible(&self, did: DefId) -> bool {
431 match self.tcx.hir.as_local_node_id(did) {
433 ty::Visibility::from_hir(&self.tcx.hir.expect_item(node_id).vis, node_id, self.tcx),
434 None => self.tcx.sess.cstore.visibility(did),
435 }.is_accessible_from(self.curitem, self.tcx)
438 // Checks that a field is in scope.
439 fn check_field(&mut self, span: Span, def: &'tcx ty::AdtDef, field: &'tcx ty::FieldDef) {
440 if !def.is_enum() && !field.vis.is_accessible_from(self.curitem, self.tcx) {
441 struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
442 field.name, def.variant_descr(), self.tcx.item_path_str(def.did))
443 .span_label(span, &format!("field `{}` is private", field.name))
448 // Checks that a method is in scope.
449 fn check_method(&mut self, span: Span, method_def_id: DefId) {
450 match self.tcx.associated_item(method_def_id).container {
451 // Trait methods are always all public. The only controlling factor
452 // is whether the trait itself is accessible or not.
453 ty::TraitContainer(trait_def_id) if !self.item_is_accessible(trait_def_id) => {
454 let msg = format!("source trait `{}` is private",
455 self.tcx.item_path_str(trait_def_id));
456 self.tcx.sess.span_err(span, &msg);
463 impl<'a, 'tcx> Visitor<'tcx> for PrivacyVisitor<'a, 'tcx> {
464 /// We want to visit items in the context of their containing
465 /// module and so forth, so supply a crate for doing a deep walk.
466 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
467 NestedVisitorMap::All(&self.tcx.hir)
470 fn visit_nested_body(&mut self, body: hir::BodyId) {
471 let old_tables = self.tables;
472 self.tables = self.tcx.body_tables(body);
473 let body = self.tcx.hir.body(body);
474 self.visit_body(body);
475 self.tables = old_tables;
478 fn visit_item(&mut self, item: &'tcx hir::Item) {
479 let orig_curitem = replace(&mut self.curitem, self.tcx.hir.local_def_id(item.id));
480 intravisit::walk_item(self, item);
481 self.curitem = orig_curitem;
484 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
486 hir::ExprMethodCall(..) => {
487 let method_call = ty::MethodCall::expr(expr.id);
488 let method = self.tables.method_map[&method_call];
489 self.check_method(expr.span, method.def_id);
491 hir::ExprStruct(ref qpath, ref expr_fields, _) => {
492 let def = self.tables.qpath_def(qpath, expr.id);
493 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
494 let variant = adt.variant_of_def(def);
495 // RFC 736: ensure all unmentioned fields are visible.
496 // Rather than computing the set of unmentioned fields
497 // (i.e. `all_fields - fields`), just check them all,
498 // unless the ADT is a union, then unmentioned fields
501 for expr_field in expr_fields {
502 self.check_field(expr.span, adt, variant.field_named(expr_field.name.node));
505 for field in &variant.fields {
506 let expr_field = expr_fields.iter().find(|f| f.name.node == field.name);
507 let span = if let Some(f) = expr_field { f.span } else { expr.span };
508 self.check_field(span, adt, field);
515 intravisit::walk_expr(self, expr);
518 fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
519 // Foreign functions do not have their patterns mapped in the def_map,
520 // and there's nothing really relevant there anyway, so don't bother
521 // checking privacy. If you can name the type then you can pass it to an
522 // external C function anyway.
523 if self.in_foreign { return }
526 PatKind::Struct(ref qpath, ref fields, _) => {
527 let def = self.tables.qpath_def(qpath, pattern.id);
528 let adt = self.tables.pat_ty(pattern).ty_adt_def().unwrap();
529 let variant = adt.variant_of_def(def);
530 for field in fields {
531 self.check_field(field.span, adt, variant.field_named(field.node.name));
534 PatKind::TupleStruct(_, ref fields, ddpos) => {
535 match self.tables.pat_ty(pattern).sty {
536 // enum fields have no privacy at this time
537 ty::TyAdt(def, _) if !def.is_enum() => {
538 let expected_len = def.struct_variant().fields.len();
539 for (i, field) in fields.iter().enumerate_and_adjust(expected_len, ddpos) {
540 if let PatKind::Wild = field.node {
543 self.check_field(field.span, def, &def.struct_variant().fields[i]);
552 intravisit::walk_pat(self, pattern);
555 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem) {
556 self.in_foreign = true;
557 intravisit::walk_foreign_item(self, fi);
558 self.in_foreign = false;
562 ///////////////////////////////////////////////////////////////////////////////
563 /// Obsolete visitors for checking for private items in public interfaces.
564 /// These visitors are supposed to be kept in frozen state and produce an
565 /// "old error node set". For backward compatibility the new visitor reports
566 /// warnings instead of hard errors when the erroneous node is not in this old set.
567 ///////////////////////////////////////////////////////////////////////////////
569 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
570 tcx: TyCtxt<'a, 'tcx, 'tcx>,
571 access_levels: &'a AccessLevels,
573 // set of errors produced by this obsolete visitor
574 old_error_set: NodeSet,
577 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
578 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
579 /// whether the type refers to private types.
580 contains_private: bool,
581 /// whether we've recurred at all (i.e. if we're pointing at the
582 /// first type on which visit_ty was called).
584 // whether that first type is a public path.
585 outer_type_is_public_path: bool,
588 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
589 fn path_is_private_type(&self, path: &hir::Path) -> bool {
590 let did = match path.def {
591 Def::PrimTy(..) | Def::SelfTy(..) => return false,
595 // A path can only be private if:
596 // it's in this crate...
597 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
598 // .. and it corresponds to a private type in the AST (this returns
599 // None for type parameters)
600 match self.tcx.hir.find(node_id) {
601 Some(hir::map::NodeItem(ref item)) => item.vis != hir::Public,
602 Some(_) | None => false,
609 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
610 // FIXME: this would preferably be using `exported_items`, but all
611 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
612 self.access_levels.is_public(trait_id)
615 fn check_ty_param_bound(&mut self,
616 ty_param_bound: &hir::TyParamBound) {
617 if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
618 if self.path_is_private_type(&trait_ref.trait_ref.path) {
619 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
624 fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
625 self.access_levels.is_reachable(*id) || *vis == hir::Public
629 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
630 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
631 NestedVisitorMap::None
634 fn visit_ty(&mut self, ty: &hir::Ty) {
635 if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = ty.node {
636 if self.inner.path_is_private_type(path) {
637 self.contains_private = true;
638 // found what we're looking for so let's stop
643 if let hir::TyPath(_) = ty.node {
644 if self.at_outer_type {
645 self.outer_type_is_public_path = true;
648 self.at_outer_type = false;
649 intravisit::walk_ty(self, ty)
652 // don't want to recurse into [, .. expr]
653 fn visit_expr(&mut self, _: &hir::Expr) {}
656 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
657 /// We want to visit items in the context of their containing
658 /// module and so forth, so supply a crate for doing a deep walk.
659 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
660 NestedVisitorMap::All(&self.tcx.hir)
663 fn visit_item(&mut self, item: &'tcx hir::Item) {
665 // contents of a private mod can be reexported, so we need
666 // to check internals.
667 hir::ItemMod(_) => {}
669 // An `extern {}` doesn't introduce a new privacy
670 // namespace (the contents have their own privacies).
671 hir::ItemForeignMod(_) => {}
673 hir::ItemTrait(.., ref bounds, _) => {
674 if !self.trait_is_public(item.id) {
678 for bound in bounds.iter() {
679 self.check_ty_param_bound(bound)
683 // impls need some special handling to try to offer useful
684 // error messages without (too many) false positives
685 // (i.e. we could just return here to not check them at
686 // all, or some worse estimation of whether an impl is
687 // publicly visible).
688 hir::ItemImpl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
689 // `impl [... for] Private` is never visible.
690 let self_contains_private;
691 // impl [... for] Public<...>, but not `impl [... for]
692 // Vec<Public>` or `(Public,)` etc.
693 let self_is_public_path;
695 // check the properties of the Self type:
697 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
699 contains_private: false,
701 outer_type_is_public_path: false,
703 visitor.visit_ty(&self_);
704 self_contains_private = visitor.contains_private;
705 self_is_public_path = visitor.outer_type_is_public_path;
708 // miscellaneous info about the impl
710 // `true` iff this is `impl Private for ...`.
711 let not_private_trait =
712 trait_ref.as_ref().map_or(true, // no trait counts as public trait
714 let did = tr.path.def.def_id();
716 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
717 self.trait_is_public(node_id)
719 true // external traits must be public
723 // `true` iff this is a trait impl or at least one method is public.
725 // `impl Public { $( fn ...() {} )* }` is not visible.
727 // This is required over just using the methods' privacy
728 // directly because we might have `impl<T: Foo<Private>> ...`,
729 // and we shouldn't warn about the generics if all the methods
730 // are private (because `T` won't be visible externally).
731 let trait_or_some_public_method =
732 trait_ref.is_some() ||
733 impl_item_refs.iter()
734 .any(|impl_item_ref| {
735 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
736 match impl_item.node {
737 hir::ImplItemKind::Const(..) |
738 hir::ImplItemKind::Method(..) => {
739 self.access_levels.is_reachable(impl_item.id)
741 hir::ImplItemKind::Type(_) => false,
745 if !self_contains_private &&
747 trait_or_some_public_method {
749 intravisit::walk_generics(self, g);
753 for impl_item_ref in impl_item_refs {
754 // This is where we choose whether to walk down
755 // further into the impl to check its items. We
756 // should only walk into public items so that we
757 // don't erroneously report errors for private
758 // types in private items.
759 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
760 match impl_item.node {
761 hir::ImplItemKind::Const(..) |
762 hir::ImplItemKind::Method(..)
763 if self.item_is_public(&impl_item.id, &impl_item.vis) =>
765 intravisit::walk_impl_item(self, impl_item)
767 hir::ImplItemKind::Type(..) => {
768 intravisit::walk_impl_item(self, impl_item)
775 // Any private types in a trait impl fall into three
777 // 1. mentioned in the trait definition
778 // 2. mentioned in the type params/generics
779 // 3. mentioned in the associated types of the impl
781 // Those in 1. can only occur if the trait is in
782 // this crate and will've been warned about on the
783 // trait definition (there's no need to warn twice
784 // so we don't check the methods).
786 // Those in 2. are warned via walk_generics and this
788 intravisit::walk_path(self, &tr.path);
790 // Those in 3. are warned with this call.
791 for impl_item_ref in impl_item_refs {
792 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
793 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
799 } else if trait_ref.is_none() && self_is_public_path {
800 // impl Public<Private> { ... }. Any public static
801 // methods will be visible as `Public::foo`.
802 let mut found_pub_static = false;
803 for impl_item_ref in impl_item_refs {
804 if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
805 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
806 match impl_item_ref.kind {
807 hir::AssociatedItemKind::Const => {
808 found_pub_static = true;
809 intravisit::walk_impl_item(self, impl_item);
811 hir::AssociatedItemKind::Method { has_self: false } => {
812 found_pub_static = true;
813 intravisit::walk_impl_item(self, impl_item);
819 if found_pub_static {
820 intravisit::walk_generics(self, g)
826 // `type ... = ...;` can contain private types, because
827 // we're introducing a new name.
828 hir::ItemTy(..) => return,
830 // not at all public, so we don't care
831 _ if !self.item_is_public(&item.id, &item.vis) => {
838 // We've carefully constructed it so that if we're here, then
839 // any `visit_ty`'s will be called on things that are in
840 // public signatures, i.e. things that we're interested in for
842 intravisit::walk_item(self, item);
845 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
846 for ty_param in generics.ty_params.iter() {
847 for bound in ty_param.bounds.iter() {
848 self.check_ty_param_bound(bound)
851 for predicate in &generics.where_clause.predicates {
853 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
854 for bound in bound_pred.bounds.iter() {
855 self.check_ty_param_bound(bound)
858 &hir::WherePredicate::RegionPredicate(_) => {}
859 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
860 self.visit_ty(&eq_pred.rhs_ty);
866 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
867 if self.access_levels.is_reachable(item.id) {
868 intravisit::walk_foreign_item(self, item)
872 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
873 if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = t.node {
874 if self.path_is_private_type(path) {
875 self.old_error_set.insert(t.id);
878 intravisit::walk_ty(self, t)
881 fn visit_variant(&mut self,
882 v: &'tcx hir::Variant,
883 g: &'tcx hir::Generics,
884 item_id: ast::NodeId) {
885 if self.access_levels.is_reachable(v.node.data.id()) {
886 self.in_variant = true;
887 intravisit::walk_variant(self, v, g, item_id);
888 self.in_variant = false;
892 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
893 if s.vis == hir::Public || self.in_variant {
894 intravisit::walk_struct_field(self, s);
898 // we don't need to introspect into these at all: an
899 // expression/block context can't possibly contain exported things.
900 // (Making them no-ops stops us from traversing the whole AST without
901 // having to be super careful about our `walk_...` calls above.)
902 fn visit_block(&mut self, _: &'tcx hir::Block) {}
903 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
906 ///////////////////////////////////////////////////////////////////////////////
907 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
908 /// finds any private components in it.
909 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
910 /// and traits in public interfaces.
911 ///////////////////////////////////////////////////////////////////////////////
913 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
914 tcx: TyCtxt<'a, 'tcx, 'tcx>,
917 /// The visitor checks that each component type is at least this visible
918 required_visibility: ty::Visibility,
919 /// The visibility of the least visible component that has been visited
920 min_visibility: ty::Visibility,
921 has_pub_restricted: bool,
922 has_old_errors: bool,
925 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
926 fn generics(&mut self) -> &mut Self {
927 for def in &self.tcx.item_generics(self.item_def_id).types {
929 self.tcx.item_type(def.def_id).visit_with(self);
935 fn predicates(&mut self) -> &mut Self {
936 self.tcx.item_predicates(self.item_def_id).visit_with(self);
940 fn item_type(&mut self) -> &mut Self {
941 self.tcx.item_type(self.item_def_id).visit_with(self);
945 fn impl_trait_ref(&mut self) -> &mut Self {
946 self.tcx.impl_trait_ref(self.item_def_id).visit_with(self);
951 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
952 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
953 let ty_def_id = match ty.sty {
954 ty::TyAdt(adt, _) => Some(adt.did),
955 ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
956 ty::TyProjection(ref proj) => {
957 if self.required_visibility == ty::Visibility::Invisible {
958 // Conservatively approximate the whole type alias as public without
959 // recursing into its components when determining impl publicity.
960 // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
961 // even if both `Type` and `Trait` are private.
962 // Ideally, associated types should be substituted in the same way as
963 // free type aliases, but this isn't done yet.
967 Some(proj.trait_ref.def_id)
972 if let Some(def_id) = ty_def_id {
973 // Non-local means public (private items can't leave their crate, modulo bugs)
974 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
975 let item = self.tcx.hir.expect_item(node_id);
976 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
978 if !vis.is_at_least(self.min_visibility, self.tcx) {
979 self.min_visibility = vis;
981 if !vis.is_at_least(self.required_visibility, self.tcx) {
982 if self.has_pub_restricted || self.has_old_errors {
983 let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
984 "private type `{}` in public interface", ty);
985 err.span_label(self.span, &format!("can't leak private type"));
988 self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
991 format!("private type `{}` in public \
992 interface (error E0446)", ty));
998 if let ty::TyProjection(ref proj) = ty.sty {
999 // Avoid calling `visit_trait_ref` below on the trait,
1000 // as we have already checked the trait itself above.
1001 proj.trait_ref.super_visit_with(self)
1003 ty.super_visit_with(self)
1007 fn visit_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
1008 // Non-local means public (private items can't leave their crate, modulo bugs)
1009 if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
1010 let item = self.tcx.hir.expect_item(node_id);
1011 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1013 if !vis.is_at_least(self.min_visibility, self.tcx) {
1014 self.min_visibility = vis;
1016 if !vis.is_at_least(self.required_visibility, self.tcx) {
1017 if self.has_pub_restricted || self.has_old_errors {
1018 struct_span_err!(self.tcx.sess, self.span, E0445,
1019 "private trait `{}` in public interface", trait_ref)
1020 .span_label(self.span, &format!(
1021 "private trait can't be public"))
1024 self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
1027 format!("private trait `{}` in public \
1028 interface (error E0445)", trait_ref));
1033 trait_ref.super_visit_with(self)
1037 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1038 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1039 has_pub_restricted: bool,
1040 old_error_set: &'a NodeSet,
1041 inner_visibility: ty::Visibility,
1044 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1045 fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1046 -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1047 let mut has_old_errors = false;
1049 // Slow path taken only if there any errors in the crate.
1050 for &id in self.old_error_set {
1051 // Walk up the nodes until we find `item_id` (or we hit a root).
1055 has_old_errors = true;
1058 let parent = self.tcx.hir.get_parent_node(id);
1070 SearchInterfaceForPrivateItemsVisitor {
1072 item_def_id: self.tcx.hir.local_def_id(item_id),
1073 span: self.tcx.hir.span(item_id),
1074 min_visibility: ty::Visibility::Public,
1075 required_visibility: required_visibility,
1076 has_pub_restricted: self.has_pub_restricted,
1077 has_old_errors: has_old_errors,
1082 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1083 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1084 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
1087 fn visit_item(&mut self, item: &'tcx hir::Item) {
1089 let min = |vis1: ty::Visibility, vis2| {
1090 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1093 let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1096 // Crates are always public
1097 hir::ItemExternCrate(..) => {}
1098 // All nested items are checked by visit_item
1099 hir::ItemMod(..) => {}
1100 // Checked in resolve
1101 hir::ItemUse(..) => {}
1103 hir::ItemGlobalAsm(..) => {}
1104 // Subitems of these items have inherited publicity
1105 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1106 hir::ItemTy(..) => {
1107 self.check(item.id, item_visibility).generics().predicates().item_type();
1109 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1110 self.inner_visibility = item_visibility;
1111 intravisit::walk_item(self, item);
1113 hir::ItemTrait(.., ref trait_item_refs) => {
1114 self.check(item.id, item_visibility).generics().predicates();
1116 for trait_item_ref in trait_item_refs {
1117 let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1118 check.generics().predicates();
1120 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1121 !trait_item_ref.defaultness.has_value() {
1122 // No type to visit.
1128 hir::ItemEnum(ref def, _) => {
1129 self.check(item.id, item_visibility).generics().predicates();
1131 for variant in &def.variants {
1132 for field in variant.node.data.fields() {
1133 self.check(field.id, item_visibility).item_type();
1137 // Subitems of foreign modules have their own publicity
1138 hir::ItemForeignMod(ref foreign_mod) => {
1139 for foreign_item in &foreign_mod.items {
1140 let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1141 self.check(foreign_item.id, vis).generics().predicates().item_type();
1144 // Subitems of structs and unions have their own publicity
1145 hir::ItemStruct(ref struct_def, _) |
1146 hir::ItemUnion(ref struct_def, _) => {
1147 self.check(item.id, item_visibility).generics().predicates();
1149 for field in struct_def.fields() {
1150 let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1151 self.check(field.id, min(item_visibility, field_visibility)).item_type();
1154 // The interface is empty
1155 hir::ItemDefaultImpl(..) => {}
1156 // An inherent impl is public when its type is public
1157 // Subitems of inherent impls have their own publicity
1158 hir::ItemImpl(.., None, _, ref impl_item_refs) => {
1160 self.check(item.id, ty::Visibility::Invisible).item_type().min_visibility;
1161 self.check(item.id, ty_vis).generics().predicates();
1163 for impl_item_ref in impl_item_refs {
1164 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1166 ty::Visibility::from_hir(&impl_item.vis, item.id, tcx);
1167 self.check(impl_item.id, min(impl_item_vis, ty_vis))
1168 .generics().predicates().item_type();
1170 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1171 self.inner_visibility = impl_item_vis;
1172 intravisit::walk_impl_item(self, impl_item);
1175 // A trait impl is public when both its type and its trait are public
1176 // Subitems of trait impls have inherited publicity
1177 hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
1178 let vis = self.check(item.id, ty::Visibility::Invisible)
1179 .item_type().impl_trait_ref().min_visibility;
1180 self.check(item.id, vis).generics().predicates();
1181 for impl_item_ref in impl_item_refs {
1182 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1183 self.check(impl_item.id, vis).generics().predicates().item_type();
1185 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1186 self.inner_visibility = vis;
1187 intravisit::walk_impl_item(self, impl_item);
1193 fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
1194 // handled in `visit_item` above
1197 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1198 if let hir::TyImplTrait(..) = ty.node {
1199 // Check the traits being exposed, as they're separate,
1200 // e.g. `impl Iterator<Item=T>` has two predicates,
1201 // `X: Iterator` and `<X as Iterator>::Item == T`,
1202 // where `X` is the `impl Iterator<Item=T>` itself,
1203 // stored in `item_predicates`, not in the `Ty` itself.
1204 self.check(ty.id, self.inner_visibility).predicates();
1207 intravisit::walk_ty(self, ty);
1210 // Don't recurse into expressions in array sizes or const initializers
1211 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1212 // Don't recurse into patterns in function arguments
1213 fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
1216 pub fn provide(providers: &mut Providers) {
1217 *providers = Providers {
1218 privacy_access_levels,
1223 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Rc<AccessLevels> {
1224 tcx.dep_graph.with_ignore(|| { // FIXME
1225 ty::queries::privacy_access_levels::get(tcx, DUMMY_SP, LOCAL_CRATE)
1229 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1231 -> Rc<AccessLevels> {
1232 assert_eq!(krate, LOCAL_CRATE);
1234 let krate = tcx.hir.krate();
1236 // Use the parent map to check the privacy of everything
1237 let mut visitor = PrivacyVisitor {
1238 curitem: DefId::local(CRATE_DEF_INDEX),
1241 tables: &ty::TypeckTables::empty(),
1243 intravisit::walk_crate(&mut visitor, krate);
1245 tcx.sess.abort_if_errors();
1247 // Build up a set of all exported items in the AST. This is a set of all
1248 // items which are reachable from external crates based on visibility.
1249 let mut visitor = EmbargoVisitor {
1251 access_levels: Default::default(),
1252 prev_level: Some(AccessLevel::Public),
1256 intravisit::walk_crate(&mut visitor, krate);
1257 if visitor.changed {
1258 visitor.changed = false;
1263 visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1266 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1268 access_levels: &visitor.access_levels,
1270 old_error_set: NodeSet(),
1272 intravisit::walk_crate(&mut visitor, krate);
1275 let has_pub_restricted = {
1276 let mut pub_restricted_visitor = PubRestrictedVisitor {
1278 has_pub_restricted: false
1280 intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1281 pub_restricted_visitor.has_pub_restricted
1284 // Check for private types and traits in public interfaces
1285 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1287 has_pub_restricted: has_pub_restricted,
1288 old_error_set: &visitor.old_error_set,
1289 inner_visibility: ty::Visibility::Public,
1291 krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1294 Rc::new(visitor.access_levels)
1297 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }