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
164 if item.vis == hir::Public { self.prev_level } else { None }
168 // Update level of the item itself
169 let item_level = self.update(item.id, inherited_item_level);
171 // Update levels of nested things
173 hir::ItemEnum(ref def, _) => {
174 for variant in &def.variants {
175 let variant_level = self.update(variant.node.data.id(), item_level);
176 for field in variant.node.data.fields() {
177 self.update(field.id, variant_level);
181 hir::ItemImpl(.., None, _, ref impl_item_refs) => {
182 for impl_item_ref in impl_item_refs {
183 if impl_item_ref.vis == hir::Public {
184 self.update(impl_item_ref.id.node_id, item_level);
188 hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
189 for impl_item_ref in impl_item_refs {
190 self.update(impl_item_ref.id.node_id, item_level);
193 hir::ItemTrait(.., ref trait_item_refs) => {
194 for trait_item_ref in trait_item_refs {
195 self.update(trait_item_ref.id.node_id, item_level);
198 hir::ItemStruct(ref def, _) | hir::ItemUnion(ref def, _) => {
199 if !def.is_struct() {
200 self.update(def.id(), item_level);
202 for field in def.fields() {
203 if field.vis == hir::Public {
204 self.update(field.id, item_level);
208 hir::ItemForeignMod(ref foreign_mod) => {
209 for foreign_item in &foreign_mod.items {
210 if foreign_item.vis == hir::Public {
211 self.update(foreign_item.id, item_level);
218 // Mark all items in interfaces of reachable items as reachable
220 // The interface is empty
221 hir::ItemExternCrate(..) => {}
222 // All nested items are checked by visit_item
223 hir::ItemMod(..) => {}
224 // Reexports are handled in visit_mod
225 hir::ItemUse(..) => {}
226 // The interface is empty
227 hir::ItemDefaultImpl(..) => {}
229 hir::ItemConst(..) | hir::ItemStatic(..) |
230 hir::ItemFn(..) | hir::ItemTy(..) => {
231 if item_level.is_some() {
232 self.reach(item.id).generics().predicates().item_type();
235 hir::ItemTrait(.., ref trait_item_refs) => {
236 if item_level.is_some() {
237 self.reach(item.id).generics().predicates();
239 for trait_item_ref in trait_item_refs {
240 let mut reach = self.reach(trait_item_ref.id.node_id);
241 reach.generics().predicates();
243 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
244 !trait_item_ref.defaultness.has_value() {
252 // Visit everything except for private impl items
253 hir::ItemImpl(.., ref trait_ref, _, ref impl_item_refs) => {
254 if item_level.is_some() {
255 self.reach(item.id).generics().predicates().impl_trait_ref();
257 for impl_item_ref in impl_item_refs {
258 let id = impl_item_ref.id.node_id;
259 if trait_ref.is_some() || self.get(id).is_some() {
260 self.reach(id).generics().predicates().item_type();
266 // Visit everything, but enum variants have their own levels
267 hir::ItemEnum(ref def, _) => {
268 if item_level.is_some() {
269 self.reach(item.id).generics().predicates();
271 for variant in &def.variants {
272 if self.get(variant.node.data.id()).is_some() {
273 for field in variant.node.data.fields() {
274 self.reach(field.id).item_type();
276 // Corner case: if the variant is reachable, but its
277 // enum is not, make the enum reachable as well.
278 self.update(item.id, Some(AccessLevel::Reachable));
282 // Visit everything, but foreign items have their own levels
283 hir::ItemForeignMod(ref foreign_mod) => {
284 for foreign_item in &foreign_mod.items {
285 if self.get(foreign_item.id).is_some() {
286 self.reach(foreign_item.id).generics().predicates().item_type();
290 // Visit everything except for private fields
291 hir::ItemStruct(ref struct_def, _) |
292 hir::ItemUnion(ref struct_def, _) => {
293 if item_level.is_some() {
294 self.reach(item.id).generics().predicates();
295 for field in struct_def.fields() {
296 if self.get(field.id).is_some() {
297 self.reach(field.id).item_type();
304 let orig_level = self.prev_level;
305 self.prev_level = item_level;
307 intravisit::walk_item(self, item);
309 self.prev_level = orig_level;
312 fn visit_block(&mut self, b: &'tcx hir::Block) {
313 let orig_level = replace(&mut self.prev_level, None);
315 // Blocks can have public items, for example impls, but they always
316 // start as completely private regardless of publicity of a function,
317 // constant, type, field, etc. in which this block resides
318 intravisit::walk_block(self, b);
320 self.prev_level = orig_level;
323 fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
324 // This code is here instead of in visit_item so that the
325 // crate module gets processed as well.
326 if self.prev_level.is_some() {
327 if let Some(exports) = self.tcx.export_map.get(&id) {
328 for export in exports {
329 if let Some(node_id) = self.tcx.hir.as_local_node_id(export.def.def_id()) {
330 self.update(node_id, Some(AccessLevel::Exported));
336 intravisit::walk_mod(self, m, id);
339 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
340 self.update(md.id, Some(AccessLevel::Public));
343 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
344 if let hir::TyImplTrait(..) = ty.node {
345 if self.get(ty.id).is_some() {
346 // Reach the (potentially private) type and the API being exposed.
347 self.reach(ty.id).item_type().predicates();
351 intravisit::walk_ty(self, ty);
355 impl<'b, 'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
356 fn generics(&mut self) -> &mut Self {
357 for def in &self.ev.tcx.item_generics(self.item_def_id).types {
359 self.ev.tcx.item_type(def.def_id).visit_with(self);
365 fn predicates(&mut self) -> &mut Self {
366 self.ev.tcx.item_predicates(self.item_def_id).visit_with(self);
370 fn item_type(&mut self) -> &mut Self {
371 self.ev.tcx.item_type(self.item_def_id).visit_with(self);
375 fn impl_trait_ref(&mut self) -> &mut Self {
376 self.ev.tcx.impl_trait_ref(self.item_def_id).visit_with(self);
381 impl<'b, 'a, 'tcx> TypeVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
382 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
383 let ty_def_id = match ty.sty {
384 ty::TyAdt(adt, _) => Some(adt.did),
385 ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
386 ty::TyProjection(ref proj) => Some(proj.trait_ref.def_id),
387 ty::TyFnDef(def_id, ..) |
388 ty::TyAnon(def_id, _) => Some(def_id),
392 if let Some(def_id) = ty_def_id {
393 if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(def_id) {
394 self.ev.update(node_id, Some(AccessLevel::Reachable));
398 ty.super_visit_with(self)
401 fn visit_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
402 if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(trait_ref.def_id) {
403 let item = self.ev.tcx.hir.expect_item(node_id);
404 self.ev.update(item.id, Some(AccessLevel::Reachable));
407 trait_ref.super_visit_with(self)
411 ////////////////////////////////////////////////////////////////////////////////
412 /// The privacy visitor, where privacy checks take place (violations reported)
413 ////////////////////////////////////////////////////////////////////////////////
415 struct PrivacyVisitor<'a, 'tcx: 'a> {
416 tcx: TyCtxt<'a, 'tcx, 'tcx>,
419 tables: &'a ty::TypeckTables<'tcx>,
422 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
423 fn item_is_accessible(&self, did: DefId) -> bool {
424 match self.tcx.hir.as_local_node_id(did) {
426 ty::Visibility::from_hir(&self.tcx.hir.expect_item(node_id).vis, node_id, self.tcx),
427 None => self.tcx.sess.cstore.visibility(did),
428 }.is_accessible_from(self.curitem, self.tcx)
431 // Checks that a field is in scope.
432 fn check_field(&mut self, span: Span, def: &'tcx ty::AdtDef, field: &'tcx ty::FieldDef) {
433 if !def.is_enum() && !field.vis.is_accessible_from(self.curitem, self.tcx) {
434 struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
435 field.name, def.variant_descr(), self.tcx.item_path_str(def.did))
436 .span_label(span, &format!("field `{}` is private", field.name))
441 // Checks that a method is in scope.
442 fn check_method(&mut self, span: Span, method_def_id: DefId) {
443 match self.tcx.associated_item(method_def_id).container {
444 // Trait methods are always all public. The only controlling factor
445 // is whether the trait itself is accessible or not.
446 ty::TraitContainer(trait_def_id) if !self.item_is_accessible(trait_def_id) => {
447 let msg = format!("source trait `{}` is private",
448 self.tcx.item_path_str(trait_def_id));
449 self.tcx.sess.span_err(span, &msg);
456 impl<'a, 'tcx> Visitor<'tcx> for PrivacyVisitor<'a, 'tcx> {
457 /// We want to visit items in the context of their containing
458 /// module and so forth, so supply a crate for doing a deep walk.
459 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
460 NestedVisitorMap::All(&self.tcx.hir)
463 fn visit_nested_body(&mut self, body: hir::BodyId) {
464 let old_tables = self.tables;
465 self.tables = self.tcx.body_tables(body);
466 let body = self.tcx.hir.body(body);
467 self.visit_body(body);
468 self.tables = old_tables;
471 fn visit_item(&mut self, item: &'tcx hir::Item) {
472 let orig_curitem = replace(&mut self.curitem, self.tcx.hir.local_def_id(item.id));
473 intravisit::walk_item(self, item);
474 self.curitem = orig_curitem;
477 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
479 hir::ExprMethodCall(..) => {
480 let method_call = ty::MethodCall::expr(expr.id);
481 let method = self.tables.method_map[&method_call];
482 self.check_method(expr.span, method.def_id);
484 hir::ExprStruct(ref qpath, ref expr_fields, _) => {
485 let def = self.tables.qpath_def(qpath, expr.id);
486 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
487 let variant = adt.variant_of_def(def);
488 // RFC 736: ensure all unmentioned fields are visible.
489 // Rather than computing the set of unmentioned fields
490 // (i.e. `all_fields - fields`), just check them all,
491 // unless the ADT is a union, then unmentioned fields
494 for expr_field in expr_fields {
495 self.check_field(expr.span, adt, variant.field_named(expr_field.name.node));
498 for field in &variant.fields {
499 let expr_field = expr_fields.iter().find(|f| f.name.node == field.name);
500 let span = if let Some(f) = expr_field { f.span } else { expr.span };
501 self.check_field(span, adt, field);
508 intravisit::walk_expr(self, expr);
511 fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
512 // Foreign functions do not have their patterns mapped in the def_map,
513 // and there's nothing really relevant there anyway, so don't bother
514 // checking privacy. If you can name the type then you can pass it to an
515 // external C function anyway.
516 if self.in_foreign { return }
519 PatKind::Struct(ref qpath, ref fields, _) => {
520 let def = self.tables.qpath_def(qpath, pattern.id);
521 let adt = self.tables.pat_ty(pattern).ty_adt_def().unwrap();
522 let variant = adt.variant_of_def(def);
523 for field in fields {
524 self.check_field(field.span, adt, variant.field_named(field.node.name));
527 PatKind::TupleStruct(_, ref fields, ddpos) => {
528 match self.tables.pat_ty(pattern).sty {
529 // enum fields have no privacy at this time
530 ty::TyAdt(def, _) if !def.is_enum() => {
531 let expected_len = def.struct_variant().fields.len();
532 for (i, field) in fields.iter().enumerate_and_adjust(expected_len, ddpos) {
533 if let PatKind::Wild = field.node {
536 self.check_field(field.span, def, &def.struct_variant().fields[i]);
545 intravisit::walk_pat(self, pattern);
548 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem) {
549 self.in_foreign = true;
550 intravisit::walk_foreign_item(self, fi);
551 self.in_foreign = false;
555 ///////////////////////////////////////////////////////////////////////////////
556 /// Obsolete visitors for checking for private items in public interfaces.
557 /// These visitors are supposed to be kept in frozen state and produce an
558 /// "old error node set". For backward compatibility the new visitor reports
559 /// warnings instead of hard errors when the erroneous node is not in this old set.
560 ///////////////////////////////////////////////////////////////////////////////
562 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
563 tcx: TyCtxt<'a, 'tcx, 'tcx>,
564 access_levels: &'a AccessLevels,
566 // set of errors produced by this obsolete visitor
567 old_error_set: NodeSet,
570 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
571 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
572 /// whether the type refers to private types.
573 contains_private: bool,
574 /// whether we've recurred at all (i.e. if we're pointing at the
575 /// first type on which visit_ty was called).
577 // whether that first type is a public path.
578 outer_type_is_public_path: bool,
581 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
582 fn path_is_private_type(&self, path: &hir::Path) -> bool {
583 let did = match path.def {
584 Def::PrimTy(..) | Def::SelfTy(..) => return false,
588 // A path can only be private if:
589 // it's in this crate...
590 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
591 // .. and it corresponds to a private type in the AST (this returns
592 // None for type parameters)
593 match self.tcx.hir.find(node_id) {
594 Some(hir::map::NodeItem(ref item)) => item.vis != hir::Public,
595 Some(_) | None => false,
602 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
603 // FIXME: this would preferably be using `exported_items`, but all
604 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
605 self.access_levels.is_public(trait_id)
608 fn check_ty_param_bound(&mut self,
609 ty_param_bound: &hir::TyParamBound) {
610 if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
611 if self.path_is_private_type(&trait_ref.trait_ref.path) {
612 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
617 fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
618 self.access_levels.is_reachable(*id) || *vis == hir::Public
622 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
623 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
624 NestedVisitorMap::None
627 fn visit_ty(&mut self, ty: &hir::Ty) {
628 if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = ty.node {
629 if self.inner.path_is_private_type(path) {
630 self.contains_private = true;
631 // found what we're looking for so let's stop
636 if let hir::TyPath(_) = ty.node {
637 if self.at_outer_type {
638 self.outer_type_is_public_path = true;
641 self.at_outer_type = false;
642 intravisit::walk_ty(self, ty)
645 // don't want to recurse into [, .. expr]
646 fn visit_expr(&mut self, _: &hir::Expr) {}
649 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
650 /// We want to visit items in the context of their containing
651 /// module and so forth, so supply a crate for doing a deep walk.
652 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
653 NestedVisitorMap::All(&self.tcx.hir)
656 fn visit_item(&mut self, item: &'tcx hir::Item) {
658 // contents of a private mod can be reexported, so we need
659 // to check internals.
660 hir::ItemMod(_) => {}
662 // An `extern {}` doesn't introduce a new privacy
663 // namespace (the contents have their own privacies).
664 hir::ItemForeignMod(_) => {}
666 hir::ItemTrait(.., ref bounds, _) => {
667 if !self.trait_is_public(item.id) {
671 for bound in bounds.iter() {
672 self.check_ty_param_bound(bound)
676 // impls need some special handling to try to offer useful
677 // error messages without (too many) false positives
678 // (i.e. we could just return here to not check them at
679 // all, or some worse estimation of whether an impl is
680 // publicly visible).
681 hir::ItemImpl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
682 // `impl [... for] Private` is never visible.
683 let self_contains_private;
684 // impl [... for] Public<...>, but not `impl [... for]
685 // Vec<Public>` or `(Public,)` etc.
686 let self_is_public_path;
688 // check the properties of the Self type:
690 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
692 contains_private: false,
694 outer_type_is_public_path: false,
696 visitor.visit_ty(&self_);
697 self_contains_private = visitor.contains_private;
698 self_is_public_path = visitor.outer_type_is_public_path;
701 // miscellaneous info about the impl
703 // `true` iff this is `impl Private for ...`.
704 let not_private_trait =
705 trait_ref.as_ref().map_or(true, // no trait counts as public trait
707 let did = tr.path.def.def_id();
709 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
710 self.trait_is_public(node_id)
712 true // external traits must be public
716 // `true` iff this is a trait impl or at least one method is public.
718 // `impl Public { $( fn ...() {} )* }` is not visible.
720 // This is required over just using the methods' privacy
721 // directly because we might have `impl<T: Foo<Private>> ...`,
722 // and we shouldn't warn about the generics if all the methods
723 // are private (because `T` won't be visible externally).
724 let trait_or_some_public_method =
725 trait_ref.is_some() ||
726 impl_item_refs.iter()
727 .any(|impl_item_ref| {
728 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
729 match impl_item.node {
730 hir::ImplItemKind::Const(..) |
731 hir::ImplItemKind::Method(..) => {
732 self.access_levels.is_reachable(impl_item.id)
734 hir::ImplItemKind::Type(_) => false,
738 if !self_contains_private &&
740 trait_or_some_public_method {
742 intravisit::walk_generics(self, g);
746 for impl_item_ref in impl_item_refs {
747 // This is where we choose whether to walk down
748 // further into the impl to check its items. We
749 // should only walk into public items so that we
750 // don't erroneously report errors for private
751 // types in private items.
752 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
753 match impl_item.node {
754 hir::ImplItemKind::Const(..) |
755 hir::ImplItemKind::Method(..)
756 if self.item_is_public(&impl_item.id, &impl_item.vis) =>
758 intravisit::walk_impl_item(self, impl_item)
760 hir::ImplItemKind::Type(..) => {
761 intravisit::walk_impl_item(self, impl_item)
768 // Any private types in a trait impl fall into three
770 // 1. mentioned in the trait definition
771 // 2. mentioned in the type params/generics
772 // 3. mentioned in the associated types of the impl
774 // Those in 1. can only occur if the trait is in
775 // this crate and will've been warned about on the
776 // trait definition (there's no need to warn twice
777 // so we don't check the methods).
779 // Those in 2. are warned via walk_generics and this
781 intravisit::walk_path(self, &tr.path);
783 // Those in 3. are warned with this call.
784 for impl_item_ref in impl_item_refs {
785 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
786 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
792 } else if trait_ref.is_none() && self_is_public_path {
793 // impl Public<Private> { ... }. Any public static
794 // methods will be visible as `Public::foo`.
795 let mut found_pub_static = false;
796 for impl_item_ref in impl_item_refs {
797 if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
798 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
799 match impl_item_ref.kind {
800 hir::AssociatedItemKind::Const => {
801 found_pub_static = true;
802 intravisit::walk_impl_item(self, impl_item);
804 hir::AssociatedItemKind::Method { has_self: false } => {
805 found_pub_static = true;
806 intravisit::walk_impl_item(self, impl_item);
812 if found_pub_static {
813 intravisit::walk_generics(self, g)
819 // `type ... = ...;` can contain private types, because
820 // we're introducing a new name.
821 hir::ItemTy(..) => return,
823 // not at all public, so we don't care
824 _ if !self.item_is_public(&item.id, &item.vis) => {
831 // We've carefully constructed it so that if we're here, then
832 // any `visit_ty`'s will be called on things that are in
833 // public signatures, i.e. things that we're interested in for
835 intravisit::walk_item(self, item);
838 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
839 for ty_param in generics.ty_params.iter() {
840 for bound in ty_param.bounds.iter() {
841 self.check_ty_param_bound(bound)
844 for predicate in &generics.where_clause.predicates {
846 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
847 for bound in bound_pred.bounds.iter() {
848 self.check_ty_param_bound(bound)
851 &hir::WherePredicate::RegionPredicate(_) => {}
852 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
853 self.visit_ty(&eq_pred.rhs_ty);
859 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
860 if self.access_levels.is_reachable(item.id) {
861 intravisit::walk_foreign_item(self, item)
865 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
866 if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = t.node {
867 if self.path_is_private_type(path) {
868 self.old_error_set.insert(t.id);
871 intravisit::walk_ty(self, t)
874 fn visit_variant(&mut self,
875 v: &'tcx hir::Variant,
876 g: &'tcx hir::Generics,
877 item_id: ast::NodeId) {
878 if self.access_levels.is_reachable(v.node.data.id()) {
879 self.in_variant = true;
880 intravisit::walk_variant(self, v, g, item_id);
881 self.in_variant = false;
885 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
886 if s.vis == hir::Public || self.in_variant {
887 intravisit::walk_struct_field(self, s);
891 // we don't need to introspect into these at all: an
892 // expression/block context can't possibly contain exported things.
893 // (Making them no-ops stops us from traversing the whole AST without
894 // having to be super careful about our `walk_...` calls above.)
895 fn visit_block(&mut self, _: &'tcx hir::Block) {}
896 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
899 ///////////////////////////////////////////////////////////////////////////////
900 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
901 /// finds any private components in it.
902 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
903 /// and traits in public interfaces.
904 ///////////////////////////////////////////////////////////////////////////////
906 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
907 tcx: TyCtxt<'a, 'tcx, 'tcx>,
910 /// The visitor checks that each component type is at least this visible
911 required_visibility: ty::Visibility,
912 /// The visibility of the least visible component that has been visited
913 min_visibility: ty::Visibility,
914 has_pub_restricted: bool,
915 has_old_errors: bool,
918 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
919 fn generics(&mut self) -> &mut Self {
920 for def in &self.tcx.item_generics(self.item_def_id).types {
922 self.tcx.item_type(def.def_id).visit_with(self);
928 fn predicates(&mut self) -> &mut Self {
929 self.tcx.item_predicates(self.item_def_id).visit_with(self);
933 fn item_type(&mut self) -> &mut Self {
934 self.tcx.item_type(self.item_def_id).visit_with(self);
938 fn impl_trait_ref(&mut self) -> &mut Self {
939 self.tcx.impl_trait_ref(self.item_def_id).visit_with(self);
944 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
945 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
946 let ty_def_id = match ty.sty {
947 ty::TyAdt(adt, _) => Some(adt.did),
948 ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
949 ty::TyProjection(ref proj) => {
950 if self.required_visibility == ty::Visibility::Invisible {
951 // Conservatively approximate the whole type alias as public without
952 // recursing into its components when determining impl publicity.
953 // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
954 // even if both `Type` and `Trait` are private.
955 // Ideally, associated types should be substituted in the same way as
956 // free type aliases, but this isn't done yet.
960 Some(proj.trait_ref.def_id)
965 if let Some(def_id) = ty_def_id {
966 // Non-local means public (private items can't leave their crate, modulo bugs)
967 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
968 let item = self.tcx.hir.expect_item(node_id);
969 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
971 if !vis.is_at_least(self.min_visibility, self.tcx) {
972 self.min_visibility = vis;
974 if !vis.is_at_least(self.required_visibility, self.tcx) {
975 if self.has_pub_restricted || self.has_old_errors {
976 let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
977 "private type `{}` in public interface", ty);
978 err.span_label(self.span, &format!("can't leak private type"));
981 self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
984 format!("private type `{}` in public \
985 interface (error E0446)", ty));
991 if let ty::TyProjection(ref proj) = ty.sty {
992 // Avoid calling `visit_trait_ref` below on the trait,
993 // as we have already checked the trait itself above.
994 proj.trait_ref.super_visit_with(self)
996 ty.super_visit_with(self)
1000 fn visit_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
1001 // Non-local means public (private items can't leave their crate, modulo bugs)
1002 if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
1003 let item = self.tcx.hir.expect_item(node_id);
1004 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1006 if !vis.is_at_least(self.min_visibility, self.tcx) {
1007 self.min_visibility = vis;
1009 if !vis.is_at_least(self.required_visibility, self.tcx) {
1010 if self.has_pub_restricted || self.has_old_errors {
1011 struct_span_err!(self.tcx.sess, self.span, E0445,
1012 "private trait `{}` in public interface", trait_ref)
1013 .span_label(self.span, &format!(
1014 "private trait can't be public"))
1017 self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
1020 format!("private trait `{}` in public \
1021 interface (error E0445)", trait_ref));
1026 trait_ref.super_visit_with(self)
1030 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1031 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1032 has_pub_restricted: bool,
1033 old_error_set: &'a NodeSet,
1034 inner_visibility: ty::Visibility,
1037 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1038 fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1039 -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1040 let mut has_old_errors = false;
1042 // Slow path taken only if there any errors in the crate.
1043 for &id in self.old_error_set {
1044 // Walk up the nodes until we find `item_id` (or we hit a root).
1048 has_old_errors = true;
1051 let parent = self.tcx.hir.get_parent_node(id);
1063 SearchInterfaceForPrivateItemsVisitor {
1065 item_def_id: self.tcx.hir.local_def_id(item_id),
1066 span: self.tcx.hir.span(item_id),
1067 min_visibility: ty::Visibility::Public,
1068 required_visibility: required_visibility,
1069 has_pub_restricted: self.has_pub_restricted,
1070 has_old_errors: has_old_errors,
1075 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1076 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1077 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
1080 fn visit_item(&mut self, item: &'tcx hir::Item) {
1082 let min = |vis1: ty::Visibility, vis2| {
1083 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1086 let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1089 // Crates are always public
1090 hir::ItemExternCrate(..) => {}
1091 // All nested items are checked by visit_item
1092 hir::ItemMod(..) => {}
1093 // Checked in resolve
1094 hir::ItemUse(..) => {}
1095 // Subitems of these items have inherited publicity
1096 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1097 hir::ItemTy(..) => {
1098 self.check(item.id, item_visibility).generics().predicates().item_type();
1100 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1101 self.inner_visibility = item_visibility;
1102 intravisit::walk_item(self, item);
1104 hir::ItemTrait(.., ref trait_item_refs) => {
1105 self.check(item.id, item_visibility).generics().predicates();
1107 for trait_item_ref in trait_item_refs {
1108 let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1109 check.generics().predicates();
1111 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1112 !trait_item_ref.defaultness.has_value() {
1113 // No type to visit.
1119 hir::ItemEnum(ref def, _) => {
1120 self.check(item.id, item_visibility).generics().predicates();
1122 for variant in &def.variants {
1123 for field in variant.node.data.fields() {
1124 self.check(field.id, item_visibility).item_type();
1128 // Subitems of foreign modules have their own publicity
1129 hir::ItemForeignMod(ref foreign_mod) => {
1130 for foreign_item in &foreign_mod.items {
1131 let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1132 self.check(foreign_item.id, vis).generics().predicates().item_type();
1135 // Subitems of structs and unions have their own publicity
1136 hir::ItemStruct(ref struct_def, _) |
1137 hir::ItemUnion(ref struct_def, _) => {
1138 self.check(item.id, item_visibility).generics().predicates();
1140 for field in struct_def.fields() {
1141 let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1142 self.check(field.id, min(item_visibility, field_visibility)).item_type();
1145 // The interface is empty
1146 hir::ItemDefaultImpl(..) => {}
1147 // An inherent impl is public when its type is public
1148 // Subitems of inherent impls have their own publicity
1149 hir::ItemImpl(.., None, _, ref impl_item_refs) => {
1151 self.check(item.id, ty::Visibility::Invisible).item_type().min_visibility;
1152 self.check(item.id, ty_vis).generics().predicates();
1154 for impl_item_ref in impl_item_refs {
1155 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1157 ty::Visibility::from_hir(&impl_item.vis, item.id, tcx);
1158 self.check(impl_item.id, min(impl_item_vis, ty_vis))
1159 .generics().predicates().item_type();
1161 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1162 self.inner_visibility = impl_item_vis;
1163 intravisit::walk_impl_item(self, impl_item);
1166 // A trait impl is public when both its type and its trait are public
1167 // Subitems of trait impls have inherited publicity
1168 hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
1169 let vis = self.check(item.id, ty::Visibility::Invisible)
1170 .item_type().impl_trait_ref().min_visibility;
1171 self.check(item.id, vis).generics().predicates();
1172 for impl_item_ref in impl_item_refs {
1173 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1174 self.check(impl_item.id, vis).generics().predicates().item_type();
1176 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1177 self.inner_visibility = vis;
1178 intravisit::walk_impl_item(self, impl_item);
1184 fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
1185 // handled in `visit_item` above
1188 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1189 if let hir::TyImplTrait(..) = ty.node {
1190 // Check the traits being exposed, as they're separate,
1191 // e.g. `impl Iterator<Item=T>` has two predicates,
1192 // `X: Iterator` and `<X as Iterator>::Item == T`,
1193 // where `X` is the `impl Iterator<Item=T>` itself,
1194 // stored in `item_predicates`, not in the `Ty` itself.
1195 self.check(ty.id, self.inner_visibility).predicates();
1198 intravisit::walk_ty(self, ty);
1201 // Don't recurse into expressions in array sizes or const initializers
1202 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1203 // Don't recurse into patterns in function arguments
1204 fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
1207 pub fn provide(providers: &mut Providers) {
1208 *providers = Providers {
1209 privacy_access_levels,
1214 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Rc<AccessLevels> {
1215 tcx.dep_graph.with_ignore(|| { // FIXME
1216 ty::queries::privacy_access_levels::get(tcx, DUMMY_SP, LOCAL_CRATE)
1220 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1222 -> Rc<AccessLevels> {
1223 assert_eq!(krate, LOCAL_CRATE);
1225 let krate = tcx.hir.krate();
1227 // Use the parent map to check the privacy of everything
1228 let mut visitor = PrivacyVisitor {
1229 curitem: DefId::local(CRATE_DEF_INDEX),
1232 tables: &ty::TypeckTables::empty(),
1234 intravisit::walk_crate(&mut visitor, krate);
1236 tcx.sess.abort_if_errors();
1238 // Build up a set of all exported items in the AST. This is a set of all
1239 // items which are reachable from external crates based on visibility.
1240 let mut visitor = EmbargoVisitor {
1242 access_levels: Default::default(),
1243 prev_level: Some(AccessLevel::Public),
1247 intravisit::walk_crate(&mut visitor, krate);
1248 if visitor.changed {
1249 visitor.changed = false;
1254 visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1257 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1259 access_levels: &visitor.access_levels,
1261 old_error_set: NodeSet(),
1263 intravisit::walk_crate(&mut visitor, krate);
1266 let has_pub_restricted = {
1267 let mut pub_restricted_visitor = PubRestrictedVisitor {
1269 has_pub_restricted: false
1271 intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1272 pub_restricted_visitor.has_pub_restricted
1275 // Check for private types and traits in public interfaces
1276 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1278 has_pub_restricted: has_pub_restricted,
1279 old_error_set: &visitor.old_error_set,
1280 inner_visibility: ty::Visibility::Public,
1282 krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1285 Rc::new(visitor.access_levels)
1288 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }