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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13 html_root_url = "https://doc.rust-lang.org/nightly/")]
16 #![feature(rustc_diagnostic_macros)]
18 #[macro_use] extern crate rustc;
19 #[macro_use] extern crate syntax;
20 extern crate syntax_pos;
22 use rustc::hir::{self, PatKind};
23 use rustc::hir::def::Def;
24 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
25 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
26 use rustc::hir::itemlikevisit::DeepVisitor;
28 use rustc::middle::privacy::{AccessLevel, AccessLevels};
29 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable};
30 use rustc::ty::fold::TypeVisitor;
31 use rustc::ty::maps::Providers;
32 use rustc::util::nodemap::NodeSet;
33 use syntax::ast::{self, CRATE_NODE_ID, Ident};
34 use syntax::symbol::keywords;
38 use std::mem::replace;
43 ////////////////////////////////////////////////////////////////////////////////
44 /// Visitor used to determine if pub(restricted) is used anywhere in the crate.
46 /// This is done so that `private_in_public` warnings can be turned into hard errors
47 /// in crates that have been updated to use pub(restricted).
48 ////////////////////////////////////////////////////////////////////////////////
49 struct PubRestrictedVisitor<'a, 'tcx: 'a> {
50 tcx: TyCtxt<'a, 'tcx, 'tcx>,
51 has_pub_restricted: bool,
54 impl<'a, 'tcx> Visitor<'tcx> for PubRestrictedVisitor<'a, 'tcx> {
55 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
56 NestedVisitorMap::All(&self.tcx.hir)
58 fn visit_vis(&mut self, vis: &'tcx hir::Visibility) {
59 self.has_pub_restricted = self.has_pub_restricted || vis.is_pub_restricted();
63 ////////////////////////////////////////////////////////////////////////////////
64 /// The embargo visitor, used to determine the exports of the ast
65 ////////////////////////////////////////////////////////////////////////////////
67 struct EmbargoVisitor<'a, 'tcx: 'a> {
68 tcx: TyCtxt<'a, 'tcx, 'tcx>,
70 // Accessibility levels for reachable nodes
71 access_levels: AccessLevels,
72 // Previous accessibility level, None means unreachable
73 prev_level: Option<AccessLevel>,
74 // Have something changed in the level map?
78 struct ReachEverythingInTheInterfaceVisitor<'b, 'a: 'b, 'tcx: 'a> {
80 ev: &'b mut EmbargoVisitor<'a, 'tcx>,
83 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
84 fn item_ty_level(&self, item_def_id: DefId) -> Option<AccessLevel> {
85 let ty_def_id = match self.tcx.type_of(item_def_id).sty {
86 ty::TyAdt(adt, _) => adt.did,
87 ty::TyDynamic(ref obj, ..) if obj.principal().is_some() =>
88 obj.principal().unwrap().def_id(),
89 ty::TyProjection(ref proj) => proj.trait_ref(self.tcx).def_id,
90 _ => return Some(AccessLevel::Public)
92 if let Some(node_id) = self.tcx.hir.as_local_node_id(ty_def_id) {
95 Some(AccessLevel::Public)
99 fn impl_trait_level(&self, impl_def_id: DefId) -> Option<AccessLevel> {
100 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_def_id) {
101 if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
102 return self.get(node_id);
105 Some(AccessLevel::Public)
108 fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
109 self.access_levels.map.get(&id).cloned()
112 // Updates node level and returns the updated level
113 fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
114 let old_level = self.get(id);
115 // Accessibility levels can only grow
116 if level > old_level {
117 self.access_levels.map.insert(id, level.unwrap());
125 fn reach<'b>(&'b mut self, item_id: ast::NodeId)
126 -> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
127 ReachEverythingInTheInterfaceVisitor {
128 item_def_id: self.tcx.hir.local_def_id(item_id),
134 impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> {
135 /// We want to visit items in the context of their containing
136 /// module and so forth, so supply a crate for doing a deep walk.
137 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
138 NestedVisitorMap::All(&self.tcx.hir)
141 fn visit_item(&mut self, item: &'tcx hir::Item) {
142 let inherited_item_level = match item.node {
143 // Impls inherit level from their types and traits
144 hir::ItemImpl(..) => {
145 let def_id = self.tcx.hir.local_def_id(item.id);
146 cmp::min(self.item_ty_level(def_id), self.impl_trait_level(def_id))
148 hir::ItemDefaultImpl(..) => {
149 let def_id = self.tcx.hir.local_def_id(item.id);
150 self.impl_trait_level(def_id)
152 // Foreign mods inherit level from parents
153 hir::ItemForeignMod(..) => {
156 // Other `pub` items inherit levels from parents
157 hir::ItemConst(..) | hir::ItemEnum(..) | hir::ItemExternCrate(..) |
158 hir::ItemGlobalAsm(..) | hir::ItemFn(..) | hir::ItemMod(..) |
159 hir::ItemStatic(..) | hir::ItemStruct(..) | hir::ItemTrait(..) |
160 hir::ItemTy(..) | hir::ItemUnion(..) | hir::ItemUse(..) => {
161 if item.vis == hir::Public { self.prev_level } else { None }
165 // Update level of the item itself
166 let item_level = self.update(item.id, inherited_item_level);
168 // Update levels of nested things
170 hir::ItemEnum(ref def, _) => {
171 for variant in &def.variants {
172 let variant_level = self.update(variant.node.data.id(), item_level);
173 for field in variant.node.data.fields() {
174 self.update(field.id, variant_level);
178 hir::ItemImpl(.., None, _, ref impl_item_refs) => {
179 for impl_item_ref in impl_item_refs {
180 if impl_item_ref.vis == hir::Public {
181 self.update(impl_item_ref.id.node_id, item_level);
185 hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
186 for impl_item_ref in impl_item_refs {
187 self.update(impl_item_ref.id.node_id, item_level);
190 hir::ItemTrait(.., ref trait_item_refs) => {
191 for trait_item_ref in trait_item_refs {
192 self.update(trait_item_ref.id.node_id, item_level);
195 hir::ItemStruct(ref def, _) | hir::ItemUnion(ref def, _) => {
196 if !def.is_struct() {
197 self.update(def.id(), item_level);
199 for field in def.fields() {
200 if field.vis == hir::Public {
201 self.update(field.id, item_level);
205 hir::ItemForeignMod(ref foreign_mod) => {
206 for foreign_item in &foreign_mod.items {
207 if foreign_item.vis == hir::Public {
208 self.update(foreign_item.id, item_level);
212 hir::ItemUse(..) | hir::ItemStatic(..) | hir::ItemConst(..) |
213 hir::ItemGlobalAsm(..) | hir::ItemTy(..) | hir::ItemMod(..) |
214 hir::ItemFn(..) | hir::ItemExternCrate(..) | hir::ItemDefaultImpl(..) => {}
217 // Mark all items in interfaces of reachable items as reachable
219 // The interface is empty
220 hir::ItemExternCrate(..) => {}
221 // All nested items are checked by visit_item
222 hir::ItemMod(..) => {}
223 // Reexports are handled in visit_mod
224 hir::ItemUse(..) => {}
225 // The interface is empty
226 hir::ItemDefaultImpl(..) => {}
227 // The interface is empty
228 hir::ItemGlobalAsm(..) => {}
230 hir::ItemConst(..) | hir::ItemStatic(..) |
231 hir::ItemFn(..) | hir::ItemTy(..) => {
232 if item_level.is_some() {
233 self.reach(item.id).generics().predicates().ty();
236 hir::ItemTrait(.., ref trait_item_refs) => {
237 if item_level.is_some() {
238 self.reach(item.id).generics().predicates();
240 for trait_item_ref in trait_item_refs {
241 let mut reach = self.reach(trait_item_ref.id.node_id);
242 reach.generics().predicates();
244 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
245 !trait_item_ref.defaultness.has_value() {
253 // Visit everything except for private impl items
254 hir::ItemImpl(.., ref trait_ref, _, ref impl_item_refs) => {
255 if item_level.is_some() {
256 self.reach(item.id).generics().predicates().impl_trait_ref();
258 for impl_item_ref in impl_item_refs {
259 let id = impl_item_ref.id.node_id;
260 if trait_ref.is_some() || self.get(id).is_some() {
261 self.reach(id).generics().predicates().ty();
267 // Visit everything, but enum variants have their own levels
268 hir::ItemEnum(ref def, _) => {
269 if item_level.is_some() {
270 self.reach(item.id).generics().predicates();
272 for variant in &def.variants {
273 if self.get(variant.node.data.id()).is_some() {
274 for field in variant.node.data.fields() {
275 self.reach(field.id).ty();
277 // Corner case: if the variant is reachable, but its
278 // enum is not, make the enum reachable as well.
279 self.update(item.id, Some(AccessLevel::Reachable));
283 // Visit everything, but foreign items have their own levels
284 hir::ItemForeignMod(ref foreign_mod) => {
285 for foreign_item in &foreign_mod.items {
286 if self.get(foreign_item.id).is_some() {
287 self.reach(foreign_item.id).generics().predicates().ty();
291 // Visit everything except for private fields
292 hir::ItemStruct(ref struct_def, _) |
293 hir::ItemUnion(ref struct_def, _) => {
294 if item_level.is_some() {
295 self.reach(item.id).generics().predicates();
296 for field in struct_def.fields() {
297 if self.get(field.id).is_some() {
298 self.reach(field.id).ty();
305 let orig_level = self.prev_level;
306 self.prev_level = item_level;
308 intravisit::walk_item(self, item);
310 self.prev_level = orig_level;
313 fn visit_block(&mut self, b: &'tcx hir::Block) {
314 let orig_level = replace(&mut self.prev_level, None);
316 // Blocks can have public items, for example impls, but they always
317 // start as completely private regardless of publicity of a function,
318 // constant, type, field, etc. in which this block resides
319 intravisit::walk_block(self, b);
321 self.prev_level = orig_level;
324 fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
325 // This code is here instead of in visit_item so that the
326 // crate module gets processed as well.
327 if self.prev_level.is_some() {
328 let hir_id = self.tcx.hir.node_to_hir_id(id);
329 if let Some(exports) = self.tcx.module_exports(hir_id) {
330 for export in exports.iter() {
331 if let Some(node_id) = self.tcx.hir.as_local_node_id(export.def.def_id()) {
332 self.update(node_id, Some(AccessLevel::Exported));
338 intravisit::walk_mod(self, m, id);
341 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
343 self.update(md.id, Some(AccessLevel::Public));
347 let module_did = ty::DefIdTree::parent(self.tcx, self.tcx.hir.local_def_id(md.id)).unwrap();
348 let mut module_id = self.tcx.hir.as_local_node_id(module_did).unwrap();
349 let level = if md.vis == hir::Public { self.get(module_id) } else { None };
350 let level = self.update(md.id, level);
356 let module = if module_id == ast::CRATE_NODE_ID {
357 &self.tcx.hir.krate().module
358 } else if let hir::ItemMod(ref module) = self.tcx.hir.expect_item(module_id).node {
363 for id in &module.item_ids {
364 self.update(id.id, level);
366 if module_id == ast::CRATE_NODE_ID {
369 module_id = self.tcx.hir.get_parent_node(module_id);
373 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
374 if let hir::TyImplTrait(..) = ty.node {
375 if self.get(ty.id).is_some() {
376 // Reach the (potentially private) type and the API being exposed.
377 self.reach(ty.id).ty().predicates();
381 intravisit::walk_ty(self, ty);
385 impl<'b, 'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
386 fn generics(&mut self) -> &mut Self {
387 for def in &self.ev.tcx.generics_of(self.item_def_id).types {
389 self.ev.tcx.type_of(def.def_id).visit_with(self);
395 fn predicates(&mut self) -> &mut Self {
396 let predicates = self.ev.tcx.predicates_of(self.item_def_id);
397 for predicate in &predicates.predicates {
398 predicate.visit_with(self);
400 &ty::Predicate::Trait(poly_predicate) => {
401 self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
403 &ty::Predicate::Projection(poly_predicate) => {
404 let tcx = self.ev.tcx;
405 self.check_trait_ref(
406 poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
415 fn ty(&mut self) -> &mut Self {
416 let ty = self.ev.tcx.type_of(self.item_def_id);
418 if let ty::TyFnDef(def_id, _) = ty.sty {
419 if def_id == self.item_def_id {
420 self.ev.tcx.fn_sig(def_id).visit_with(self);
426 fn impl_trait_ref(&mut self) -> &mut Self {
427 if let Some(impl_trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
428 self.check_trait_ref(impl_trait_ref);
429 impl_trait_ref.super_visit_with(self);
434 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
435 if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(trait_ref.def_id) {
436 let item = self.ev.tcx.hir.expect_item(node_id);
437 self.ev.update(item.id, Some(AccessLevel::Reachable));
442 impl<'b, 'a, 'tcx> TypeVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
443 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
444 let ty_def_id = match ty.sty {
445 ty::TyAdt(adt, _) => Some(adt.did),
446 ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
447 ty::TyProjection(ref proj) => Some(proj.item_def_id),
448 ty::TyFnDef(def_id, ..) |
449 ty::TyClosure(def_id, ..) |
450 ty::TyAnon(def_id, _) => Some(def_id),
454 if let Some(def_id) = ty_def_id {
455 if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(def_id) {
456 self.ev.update(node_id, Some(AccessLevel::Reachable));
460 ty.super_visit_with(self)
464 //////////////////////////////////////////////////////////////////////////////////////
465 /// Name privacy visitor, checks privacy and reports violations.
466 /// Most of name privacy checks are performed during the main resolution phase,
467 /// or later in type checking when field accesses and associated items are resolved.
468 /// This pass performs remaining checks for fields in struct expressions and patterns.
469 //////////////////////////////////////////////////////////////////////////////////////
471 struct NamePrivacyVisitor<'a, 'tcx: 'a> {
472 tcx: TyCtxt<'a, 'tcx, 'tcx>,
473 tables: &'a ty::TypeckTables<'tcx>,
474 current_item: ast::NodeId,
475 empty_tables: &'a ty::TypeckTables<'tcx>,
478 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
479 // Checks that a field is accessible.
480 fn check_field(&mut self, span: Span, def: &'tcx ty::AdtDef, field: &'tcx ty::FieldDef) {
481 let ident = Ident { ctxt: span.ctxt().modern(), ..keywords::Invalid.ident() };
482 let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
483 if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
484 struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
485 field.name, def.variant_descr(), self.tcx.item_path_str(def.did))
486 .span_label(span, format!("field `{}` is private", field.name))
492 // Set the correct TypeckTables for the given `item_id` (or an empty table if
493 // there is no TypeckTables for the item).
494 fn update_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
495 item_id: ast::NodeId,
496 tables: &mut &'a ty::TypeckTables<'tcx>,
497 empty_tables: &'a ty::TypeckTables<'tcx>)
498 -> &'a ty::TypeckTables<'tcx> {
499 let def_id = tcx.hir.local_def_id(item_id);
501 if tcx.has_typeck_tables(def_id) {
502 replace(tables, tcx.typeck_tables_of(def_id))
504 replace(tables, empty_tables)
508 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
509 /// We want to visit items in the context of their containing
510 /// module and so forth, so supply a crate for doing a deep walk.
511 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
512 NestedVisitorMap::All(&self.tcx.hir)
515 fn visit_nested_body(&mut self, body: hir::BodyId) {
516 let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
517 let body = self.tcx.hir.body(body);
518 self.visit_body(body);
519 self.tables = orig_tables;
522 fn visit_item(&mut self, item: &'tcx hir::Item) {
523 let orig_current_item = replace(&mut self.current_item, item.id);
524 let orig_tables = update_tables(self.tcx, item.id, &mut self.tables, self.empty_tables);
525 intravisit::walk_item(self, item);
526 self.current_item = orig_current_item;
527 self.tables = orig_tables;
530 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
531 let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
532 intravisit::walk_trait_item(self, ti);
533 self.tables = orig_tables;
536 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
537 let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
538 intravisit::walk_impl_item(self, ii);
539 self.tables = orig_tables;
542 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
544 hir::ExprStruct(ref qpath, ref fields, ref base) => {
545 let def = self.tables.qpath_def(qpath, expr.hir_id);
546 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
547 let variant = adt.variant_of_def(def);
548 if let Some(ref base) = *base {
549 // If the expression uses FRU we need to make sure all the unmentioned fields
550 // are checked for privacy (RFC 736). Rather than computing the set of
551 // unmentioned fields, just check them all.
552 for variant_field in &variant.fields {
553 let field = fields.iter().find(|f| f.name.node == variant_field.name);
554 let span = if let Some(f) = field { f.span } else { base.span };
555 self.check_field(span, adt, variant_field);
558 for field in fields {
559 self.check_field(field.span, adt, variant.field_named(field.name.node));
566 intravisit::walk_expr(self, expr);
569 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
571 PatKind::Struct(ref qpath, ref fields, _) => {
572 let def = self.tables.qpath_def(qpath, pat.hir_id);
573 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
574 let variant = adt.variant_of_def(def);
575 for field in fields {
576 self.check_field(field.span, adt, variant.field_named(field.node.name));
582 intravisit::walk_pat(self, pat);
586 ////////////////////////////////////////////////////////////////////////////////////////////
587 /// Type privacy visitor, checks types for privacy and reports violations.
588 /// Both explicitly written types and inferred types of expressions and patters are checked.
589 /// Checks are performed on "semantic" types regardless of names and their hygiene.
590 ////////////////////////////////////////////////////////////////////////////////////////////
592 struct TypePrivacyVisitor<'a, 'tcx: 'a> {
593 tcx: TyCtxt<'a, 'tcx, 'tcx>,
594 tables: &'a ty::TypeckTables<'tcx>,
597 empty_tables: &'a ty::TypeckTables<'tcx>,
600 impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
601 fn def_id_visibility(&self, did: DefId) -> ty::Visibility {
602 match self.tcx.hir.as_local_node_id(did) {
604 let vis = match self.tcx.hir.get(node_id) {
605 hir::map::NodeItem(item) => &item.vis,
606 hir::map::NodeForeignItem(foreign_item) => &foreign_item.vis,
607 hir::map::NodeImplItem(impl_item) => &impl_item.vis,
608 hir::map::NodeTraitItem(..) |
609 hir::map::NodeVariant(..) => {
610 return self.def_id_visibility(self.tcx.hir.get_parent_did(node_id));
612 hir::map::NodeStructCtor(vdata) => {
613 let struct_node_id = self.tcx.hir.get_parent(node_id);
614 let struct_vis = match self.tcx.hir.get(struct_node_id) {
615 hir::map::NodeItem(item) => &item.vis,
616 node => bug!("unexpected node kind: {:?}", node),
619 = ty::Visibility::from_hir(struct_vis, struct_node_id, self.tcx);
620 for field in vdata.fields() {
621 let field_vis = ty::Visibility::from_hir(&field.vis, node_id, self.tcx);
622 if ctor_vis.is_at_least(field_vis, self.tcx) {
623 ctor_vis = field_vis;
628 node => bug!("unexpected node kind: {:?}", node)
630 ty::Visibility::from_hir(vis, node_id, self.tcx)
632 None => self.tcx.sess.cstore.visibility(did),
636 fn item_is_accessible(&self, did: DefId) -> bool {
637 self.def_id_visibility(did).is_accessible_from(self.current_item, self.tcx)
640 // Take node ID of an expression or pattern and check its type for privacy.
641 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
643 if let Some(ty) = self.tables.node_id_to_type_opt(id) {
644 if ty.visit_with(self) {
648 if self.tables.node_substs(id).visit_with(self) {
651 if let Some(adjustments) = self.tables.adjustments().get(id) {
652 for adjustment in adjustments {
653 if adjustment.target.visit_with(self) {
661 fn check_item(&mut self, item_id: ast::NodeId) -> &mut Self {
662 self.current_item = self.tcx.hir.local_def_id(item_id);
663 self.span = self.tcx.hir.span(item_id);
667 // Convenience methods for checking item interfaces
668 fn ty(&mut self) -> &mut Self {
669 self.tcx.type_of(self.current_item).visit_with(self);
673 fn generics(&mut self) -> &mut Self {
674 for def in &self.tcx.generics_of(self.current_item).types {
676 self.tcx.type_of(def.def_id).visit_with(self);
682 fn predicates(&mut self) -> &mut Self {
683 let predicates = self.tcx.predicates_of(self.current_item);
684 for predicate in &predicates.predicates {
685 predicate.visit_with(self);
687 &ty::Predicate::Trait(poly_predicate) => {
688 self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
690 &ty::Predicate::Projection(poly_predicate) => {
692 self.check_trait_ref(
693 poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
702 fn impl_trait_ref(&mut self) -> &mut Self {
703 if let Some(impl_trait_ref) = self.tcx.impl_trait_ref(self.current_item) {
704 self.check_trait_ref(impl_trait_ref);
706 self.tcx.predicates_of(self.current_item).visit_with(self);
710 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
711 if !self.item_is_accessible(trait_ref.def_id) {
712 let msg = format!("trait `{}` is private", trait_ref);
713 self.tcx.sess.span_err(self.span, &msg);
717 trait_ref.super_visit_with(self)
721 impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
722 /// We want to visit items in the context of their containing
723 /// module and so forth, so supply a crate for doing a deep walk.
724 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
725 NestedVisitorMap::All(&self.tcx.hir)
728 fn visit_nested_body(&mut self, body: hir::BodyId) {
729 let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
730 let body = self.tcx.hir.body(body);
731 self.visit_body(body);
732 self.tables = orig_tables;
735 // Check types of expressions
736 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
737 if self.check_expr_pat_type(expr.hir_id, expr.span) {
738 // Do not check nested expressions if the error already happened.
742 hir::ExprAssign(.., ref rhs) | hir::ExprMatch(ref rhs, ..) => {
743 // Do not report duplicate errors for `x = y` and `match x { ... }`.
744 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
748 hir::ExprMethodCall(_, span, _) => {
749 // Method calls have to be checked specially.
750 let def_id = self.tables.type_dependent_defs()[expr.hir_id].def_id();
752 if self.tcx.type_of(def_id).visit_with(self) {
759 intravisit::walk_expr(self, expr);
762 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: ast::NodeId, span: Span) {
763 // Inherent associated constants don't have self type in substs,
764 // we have to check it additionally.
765 if let hir::QPath::TypeRelative(..) = *qpath {
766 let hir_id = self.tcx.hir.node_to_hir_id(id);
767 if let Some(def) = self.tables.type_dependent_defs().get(hir_id).cloned() {
768 if let Some(assoc_item) = self.tcx.opt_associated_item(def.def_id()) {
769 if let ty::ImplContainer(impl_def_id) = assoc_item.container {
770 if self.tcx.type_of(impl_def_id).visit_with(self) {
778 intravisit::walk_qpath(self, qpath, id, span);
781 // Check types of patterns
782 fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
783 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
784 // Do not check nested patterns if the error already happened.
788 intravisit::walk_pat(self, pattern);
791 fn visit_local(&mut self, local: &'tcx hir::Local) {
792 if let Some(ref init) = local.init {
793 if self.check_expr_pat_type(init.hir_id, init.span) {
794 // Do not report duplicate errors for `let x = y`.
799 intravisit::walk_local(self, local);
802 // Check types in item interfaces
803 fn visit_item(&mut self, item: &'tcx hir::Item) {
804 let orig_current_item = self.current_item;
805 let orig_tables = update_tables(self.tcx,
811 hir::ItemExternCrate(..) | hir::ItemMod(..) |
812 hir::ItemUse(..) | hir::ItemGlobalAsm(..) => {}
813 hir::ItemConst(..) | hir::ItemStatic(..) |
814 hir::ItemTy(..) | hir::ItemFn(..) => {
815 self.check_item(item.id).generics().predicates().ty();
817 hir::ItemTrait(.., ref trait_item_refs) => {
818 self.check_item(item.id).generics().predicates();
819 for trait_item_ref in trait_item_refs {
820 let check = self.check_item(trait_item_ref.id.node_id);
821 check.generics().predicates();
822 if trait_item_ref.kind != hir::AssociatedItemKind::Type ||
823 trait_item_ref.defaultness.has_value() {
828 hir::ItemEnum(ref def, _) => {
829 self.check_item(item.id).generics().predicates();
830 for variant in &def.variants {
831 for field in variant.node.data.fields() {
832 self.check_item(field.id).ty();
836 hir::ItemForeignMod(ref foreign_mod) => {
837 for foreign_item in &foreign_mod.items {
838 self.check_item(foreign_item.id).generics().predicates().ty();
841 hir::ItemStruct(ref struct_def, _) |
842 hir::ItemUnion(ref struct_def, _) => {
843 self.check_item(item.id).generics().predicates();
844 for field in struct_def.fields() {
845 self.check_item(field.id).ty();
848 hir::ItemDefaultImpl(..) => {
849 self.check_item(item.id).impl_trait_ref();
851 hir::ItemImpl(.., ref trait_ref, _, ref impl_item_refs) => {
853 let check = self.check_item(item.id);
854 check.ty().generics().predicates();
855 if trait_ref.is_some() {
856 check.impl_trait_ref();
859 for impl_item_ref in impl_item_refs {
860 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
861 self.check_item(impl_item.id).generics().predicates().ty();
866 self.current_item = self.tcx.hir.local_def_id(item.id);
867 intravisit::walk_item(self, item);
868 self.tables = orig_tables;
869 self.current_item = orig_current_item;
872 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
873 let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
874 intravisit::walk_trait_item(self, ti);
875 self.tables = orig_tables;
878 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
879 let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
880 intravisit::walk_impl_item(self, ii);
881 self.tables = orig_tables;
885 impl<'a, 'tcx> TypeVisitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
886 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
888 ty::TyAdt(&ty::AdtDef { did: def_id, .. }, ..) | ty::TyFnDef(def_id, ..) => {
889 if !self.item_is_accessible(def_id) {
890 let msg = format!("type `{}` is private", ty);
891 self.tcx.sess.span_err(self.span, &msg);
894 if let ty::TyFnDef(..) = ty.sty {
895 if self.tcx.fn_sig(def_id).visit_with(self) {
899 // Inherent static methods don't have self type in substs,
900 // we have to check it additionally.
901 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
902 if let ty::ImplContainer(impl_def_id) = assoc_item.container {
903 if self.tcx.type_of(impl_def_id).visit_with(self) {
909 ty::TyDynamic(ref predicates, ..) => {
910 let is_private = predicates.skip_binder().iter().any(|predicate| {
911 let def_id = match *predicate {
912 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref.def_id,
913 ty::ExistentialPredicate::Projection(proj) =>
914 proj.trait_ref(self.tcx).def_id,
915 ty::ExistentialPredicate::AutoTrait(def_id) => def_id,
917 !self.item_is_accessible(def_id)
920 let msg = format!("type `{}` is private", ty);
921 self.tcx.sess.span_err(self.span, &msg);
925 ty::TyProjection(ref proj) => {
927 if self.check_trait_ref(proj.trait_ref(tcx)) {
931 ty::TyAnon(def_id, ..) => {
932 for predicate in &self.tcx.predicates_of(def_id).predicates {
933 let trait_ref = match *predicate {
934 ty::Predicate::Trait(ref poly_trait_predicate) => {
935 Some(poly_trait_predicate.skip_binder().trait_ref)
937 ty::Predicate::Projection(ref poly_projection_predicate) => {
938 if poly_projection_predicate.skip_binder().ty.visit_with(self) {
941 Some(poly_projection_predicate.skip_binder()
942 .projection_ty.trait_ref(self.tcx))
944 ty::Predicate::TypeOutlives(..) => None,
945 _ => bug!("unexpected predicate: {:?}", predicate),
947 if let Some(trait_ref) = trait_ref {
948 if !self.item_is_accessible(trait_ref.def_id) {
949 let msg = format!("trait `{}` is private", trait_ref);
950 self.tcx.sess.span_err(self.span, &msg);
953 // `Self` here is the same `TyAnon`, so skip it to avoid infinite recursion
954 for subst in trait_ref.substs.iter().skip(1) {
955 if subst.visit_with(self) {
965 ty.super_visit_with(self)
969 ///////////////////////////////////////////////////////////////////////////////
970 /// Obsolete visitors for checking for private items in public interfaces.
971 /// These visitors are supposed to be kept in frozen state and produce an
972 /// "old error node set". For backward compatibility the new visitor reports
973 /// warnings instead of hard errors when the erroneous node is not in this old set.
974 ///////////////////////////////////////////////////////////////////////////////
976 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
977 tcx: TyCtxt<'a, 'tcx, 'tcx>,
978 access_levels: &'a AccessLevels,
980 // set of errors produced by this obsolete visitor
981 old_error_set: NodeSet,
984 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
985 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
986 /// whether the type refers to private types.
987 contains_private: bool,
988 /// whether we've recurred at all (i.e. if we're pointing at the
989 /// first type on which visit_ty was called).
991 // whether that first type is a public path.
992 outer_type_is_public_path: bool,
995 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
996 fn path_is_private_type(&self, path: &hir::Path) -> bool {
997 let did = match path.def {
998 Def::PrimTy(..) | Def::SelfTy(..) => return false,
1002 // A path can only be private if:
1003 // it's in this crate...
1004 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
1005 // .. and it corresponds to a private type in the AST (this returns
1006 // None for type parameters)
1007 match self.tcx.hir.find(node_id) {
1008 Some(hir::map::NodeItem(ref item)) => item.vis != hir::Public,
1009 Some(_) | None => false,
1016 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1017 // FIXME: this would preferably be using `exported_items`, but all
1018 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1019 self.access_levels.is_public(trait_id)
1022 fn check_ty_param_bound(&mut self,
1023 ty_param_bound: &hir::TyParamBound) {
1024 if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1025 if self.path_is_private_type(&trait_ref.trait_ref.path) {
1026 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1031 fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
1032 self.access_levels.is_reachable(*id) || *vis == hir::Public
1036 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1037 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1038 NestedVisitorMap::None
1041 fn visit_ty(&mut self, ty: &hir::Ty) {
1042 if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = ty.node {
1043 if self.inner.path_is_private_type(path) {
1044 self.contains_private = true;
1045 // found what we're looking for so let's stop
1050 if let hir::TyPath(_) = ty.node {
1051 if self.at_outer_type {
1052 self.outer_type_is_public_path = true;
1055 self.at_outer_type = false;
1056 intravisit::walk_ty(self, ty)
1059 // don't want to recurse into [, .. expr]
1060 fn visit_expr(&mut self, _: &hir::Expr) {}
1063 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1064 /// We want to visit items in the context of their containing
1065 /// module and so forth, so supply a crate for doing a deep walk.
1066 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1067 NestedVisitorMap::All(&self.tcx.hir)
1070 fn visit_item(&mut self, item: &'tcx hir::Item) {
1072 // contents of a private mod can be reexported, so we need
1073 // to check internals.
1074 hir::ItemMod(_) => {}
1076 // An `extern {}` doesn't introduce a new privacy
1077 // namespace (the contents have their own privacies).
1078 hir::ItemForeignMod(_) => {}
1080 hir::ItemTrait(.., ref bounds, _) => {
1081 if !self.trait_is_public(item.id) {
1085 for bound in bounds.iter() {
1086 self.check_ty_param_bound(bound)
1090 // impls need some special handling to try to offer useful
1091 // error messages without (too many) false positives
1092 // (i.e. we could just return here to not check them at
1093 // all, or some worse estimation of whether an impl is
1094 // publicly visible).
1095 hir::ItemImpl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
1096 // `impl [... for] Private` is never visible.
1097 let self_contains_private;
1098 // impl [... for] Public<...>, but not `impl [... for]
1099 // Vec<Public>` or `(Public,)` etc.
1100 let self_is_public_path;
1102 // check the properties of the Self type:
1104 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1106 contains_private: false,
1107 at_outer_type: true,
1108 outer_type_is_public_path: false,
1110 visitor.visit_ty(&self_);
1111 self_contains_private = visitor.contains_private;
1112 self_is_public_path = visitor.outer_type_is_public_path;
1115 // miscellaneous info about the impl
1117 // `true` iff this is `impl Private for ...`.
1118 let not_private_trait =
1119 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1121 let did = tr.path.def.def_id();
1123 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
1124 self.trait_is_public(node_id)
1126 true // external traits must be public
1130 // `true` iff this is a trait impl or at least one method is public.
1132 // `impl Public { $( fn ...() {} )* }` is not visible.
1134 // This is required over just using the methods' privacy
1135 // directly because we might have `impl<T: Foo<Private>> ...`,
1136 // and we shouldn't warn about the generics if all the methods
1137 // are private (because `T` won't be visible externally).
1138 let trait_or_some_public_method =
1139 trait_ref.is_some() ||
1140 impl_item_refs.iter()
1141 .any(|impl_item_ref| {
1142 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1143 match impl_item.node {
1144 hir::ImplItemKind::Const(..) |
1145 hir::ImplItemKind::Method(..) => {
1146 self.access_levels.is_reachable(impl_item.id)
1148 hir::ImplItemKind::Type(_) => false,
1152 if !self_contains_private &&
1153 not_private_trait &&
1154 trait_or_some_public_method {
1156 intravisit::walk_generics(self, g);
1160 for impl_item_ref in impl_item_refs {
1161 // This is where we choose whether to walk down
1162 // further into the impl to check its items. We
1163 // should only walk into public items so that we
1164 // don't erroneously report errors for private
1165 // types in private items.
1166 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1167 match impl_item.node {
1168 hir::ImplItemKind::Const(..) |
1169 hir::ImplItemKind::Method(..)
1170 if self.item_is_public(&impl_item.id, &impl_item.vis) =>
1172 intravisit::walk_impl_item(self, impl_item)
1174 hir::ImplItemKind::Type(..) => {
1175 intravisit::walk_impl_item(self, impl_item)
1182 // Any private types in a trait impl fall into three
1184 // 1. mentioned in the trait definition
1185 // 2. mentioned in the type params/generics
1186 // 3. mentioned in the associated types of the impl
1188 // Those in 1. can only occur if the trait is in
1189 // this crate and will've been warned about on the
1190 // trait definition (there's no need to warn twice
1191 // so we don't check the methods).
1193 // Those in 2. are warned via walk_generics and this
1195 intravisit::walk_path(self, &tr.path);
1197 // Those in 3. are warned with this call.
1198 for impl_item_ref in impl_item_refs {
1199 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1200 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1206 } else if trait_ref.is_none() && self_is_public_path {
1207 // impl Public<Private> { ... }. Any public static
1208 // methods will be visible as `Public::foo`.
1209 let mut found_pub_static = false;
1210 for impl_item_ref in impl_item_refs {
1211 if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
1212 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1213 match impl_item_ref.kind {
1214 hir::AssociatedItemKind::Const => {
1215 found_pub_static = true;
1216 intravisit::walk_impl_item(self, impl_item);
1218 hir::AssociatedItemKind::Method { has_self: false } => {
1219 found_pub_static = true;
1220 intravisit::walk_impl_item(self, impl_item);
1226 if found_pub_static {
1227 intravisit::walk_generics(self, g)
1233 // `type ... = ...;` can contain private types, because
1234 // we're introducing a new name.
1235 hir::ItemTy(..) => return,
1237 // not at all public, so we don't care
1238 _ if !self.item_is_public(&item.id, &item.vis) => {
1245 // We've carefully constructed it so that if we're here, then
1246 // any `visit_ty`'s will be called on things that are in
1247 // public signatures, i.e. things that we're interested in for
1249 intravisit::walk_item(self, item);
1252 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1253 for ty_param in generics.ty_params.iter() {
1254 for bound in ty_param.bounds.iter() {
1255 self.check_ty_param_bound(bound)
1258 for predicate in &generics.where_clause.predicates {
1260 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1261 for bound in bound_pred.bounds.iter() {
1262 self.check_ty_param_bound(bound)
1265 &hir::WherePredicate::RegionPredicate(_) => {}
1266 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1267 self.visit_ty(&eq_pred.rhs_ty);
1273 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
1274 if self.access_levels.is_reachable(item.id) {
1275 intravisit::walk_foreign_item(self, item)
1279 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1280 if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = t.node {
1281 if self.path_is_private_type(path) {
1282 self.old_error_set.insert(t.id);
1285 intravisit::walk_ty(self, t)
1288 fn visit_variant(&mut self,
1289 v: &'tcx hir::Variant,
1290 g: &'tcx hir::Generics,
1291 item_id: ast::NodeId) {
1292 if self.access_levels.is_reachable(v.node.data.id()) {
1293 self.in_variant = true;
1294 intravisit::walk_variant(self, v, g, item_id);
1295 self.in_variant = false;
1299 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
1300 if s.vis == hir::Public || self.in_variant {
1301 intravisit::walk_struct_field(self, s);
1305 // we don't need to introspect into these at all: an
1306 // expression/block context can't possibly contain exported things.
1307 // (Making them no-ops stops us from traversing the whole AST without
1308 // having to be super careful about our `walk_...` calls above.)
1309 fn visit_block(&mut self, _: &'tcx hir::Block) {}
1310 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1313 ///////////////////////////////////////////////////////////////////////////////
1314 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1315 /// finds any private components in it.
1316 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1317 /// and traits in public interfaces.
1318 ///////////////////////////////////////////////////////////////////////////////
1320 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1321 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1324 /// The visitor checks that each component type is at least this visible
1325 required_visibility: ty::Visibility,
1326 /// The visibility of the least visible component that has been visited
1327 min_visibility: ty::Visibility,
1328 has_pub_restricted: bool,
1329 has_old_errors: bool,
1332 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1333 fn generics(&mut self) -> &mut Self {
1334 for def in &self.tcx.generics_of(self.item_def_id).types {
1335 if def.has_default {
1336 self.tcx.type_of(def.def_id).visit_with(self);
1342 fn predicates(&mut self) -> &mut Self {
1343 let predicates = self.tcx.predicates_of(self.item_def_id);
1344 for predicate in &predicates.predicates {
1345 predicate.visit_with(self);
1347 &ty::Predicate::Trait(poly_predicate) => {
1348 self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
1350 &ty::Predicate::Projection(poly_predicate) => {
1352 self.check_trait_ref(
1353 poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
1362 fn ty(&mut self) -> &mut Self {
1363 let ty = self.tcx.type_of(self.item_def_id);
1364 ty.visit_with(self);
1365 if let ty::TyFnDef(def_id, _) = ty.sty {
1366 if def_id == self.item_def_id {
1367 self.tcx.fn_sig(def_id).visit_with(self);
1373 fn impl_trait_ref(&mut self) -> &mut Self {
1374 if let Some(impl_trait_ref) = self.tcx.impl_trait_ref(self.item_def_id) {
1375 self.check_trait_ref(impl_trait_ref);
1376 impl_trait_ref.super_visit_with(self);
1381 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
1382 // Non-local means public (private items can't leave their crate, modulo bugs)
1383 if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
1384 let item = self.tcx.hir.expect_item(node_id);
1385 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1386 if !vis.is_at_least(self.min_visibility, self.tcx) {
1387 self.min_visibility = vis;
1389 if !vis.is_at_least(self.required_visibility, self.tcx) {
1390 if self.has_pub_restricted || self.has_old_errors {
1391 struct_span_err!(self.tcx.sess, self.span, E0445,
1392 "private trait `{}` in public interface", trait_ref)
1393 .span_label(self.span, format!(
1394 "private trait can't be public"))
1397 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1400 &format!("private trait `{}` in public \
1401 interface (error E0445)", trait_ref));
1408 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1409 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
1410 let ty_def_id = match ty.sty {
1411 ty::TyAdt(adt, _) => Some(adt.did),
1412 ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
1413 ty::TyProjection(ref proj) => {
1414 if self.required_visibility == ty::Visibility::Invisible {
1415 // Conservatively approximate the whole type alias as public without
1416 // recursing into its components when determining impl publicity.
1417 // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
1418 // even if both `Type` and `Trait` are private.
1419 // Ideally, associated types should be substituted in the same way as
1420 // free type aliases, but this isn't done yet.
1423 let trait_ref = proj.trait_ref(self.tcx);
1424 Some(trait_ref.def_id)
1429 if let Some(def_id) = ty_def_id {
1430 // Non-local means public (private items can't leave their crate, modulo bugs)
1431 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
1432 let item = self.tcx.hir.expect_item(node_id);
1433 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1435 if !vis.is_at_least(self.min_visibility, self.tcx) {
1436 self.min_visibility = vis;
1438 if !vis.is_at_least(self.required_visibility, self.tcx) {
1439 if self.has_pub_restricted || self.has_old_errors {
1440 let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
1441 "private type `{}` in public interface", ty);
1442 err.span_label(self.span, "can't leak private type");
1445 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1448 &format!("private type `{}` in public \
1449 interface (error E0446)", ty));
1455 ty.super_visit_with(self)
1459 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1460 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1461 has_pub_restricted: bool,
1462 old_error_set: &'a NodeSet,
1463 inner_visibility: ty::Visibility,
1466 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1467 fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1468 -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1469 let mut has_old_errors = false;
1471 // Slow path taken only if there any errors in the crate.
1472 for &id in self.old_error_set {
1473 // Walk up the nodes until we find `item_id` (or we hit a root).
1477 has_old_errors = true;
1480 let parent = self.tcx.hir.get_parent_node(id);
1492 SearchInterfaceForPrivateItemsVisitor {
1494 item_def_id: self.tcx.hir.local_def_id(item_id),
1495 span: self.tcx.hir.span(item_id),
1496 min_visibility: ty::Visibility::Public,
1497 required_visibility,
1498 has_pub_restricted: self.has_pub_restricted,
1504 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1505 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1506 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
1509 fn visit_item(&mut self, item: &'tcx hir::Item) {
1511 let min = |vis1: ty::Visibility, vis2| {
1512 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1515 let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1518 // Crates are always public
1519 hir::ItemExternCrate(..) => {}
1520 // All nested items are checked by visit_item
1521 hir::ItemMod(..) => {}
1522 // Checked in resolve
1523 hir::ItemUse(..) => {}
1525 hir::ItemGlobalAsm(..) => {}
1526 // Subitems of these items have inherited publicity
1527 hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1528 hir::ItemTy(..) => {
1529 self.check(item.id, item_visibility).generics().predicates().ty();
1531 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1532 self.inner_visibility = item_visibility;
1533 intravisit::walk_item(self, item);
1535 hir::ItemTrait(.., ref trait_item_refs) => {
1536 self.check(item.id, item_visibility).generics().predicates();
1538 for trait_item_ref in trait_item_refs {
1539 let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1540 check.generics().predicates();
1542 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1543 !trait_item_ref.defaultness.has_value() {
1544 // No type to visit.
1550 hir::ItemEnum(ref def, _) => {
1551 self.check(item.id, item_visibility).generics().predicates();
1553 for variant in &def.variants {
1554 for field in variant.node.data.fields() {
1555 self.check(field.id, item_visibility).ty();
1559 // Subitems of foreign modules have their own publicity
1560 hir::ItemForeignMod(ref foreign_mod) => {
1561 for foreign_item in &foreign_mod.items {
1562 let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1563 self.check(foreign_item.id, vis).generics().predicates().ty();
1566 // Subitems of structs and unions have their own publicity
1567 hir::ItemStruct(ref struct_def, _) |
1568 hir::ItemUnion(ref struct_def, _) => {
1569 self.check(item.id, item_visibility).generics().predicates();
1571 for field in struct_def.fields() {
1572 let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1573 self.check(field.id, min(item_visibility, field_visibility)).ty();
1576 // The interface is empty
1577 hir::ItemDefaultImpl(..) => {}
1578 // An inherent impl is public when its type is public
1579 // Subitems of inherent impls have their own publicity
1580 hir::ItemImpl(.., None, _, ref impl_item_refs) => {
1582 self.check(item.id, ty::Visibility::Invisible).ty().min_visibility;
1583 self.check(item.id, ty_vis).generics().predicates();
1585 for impl_item_ref in impl_item_refs {
1586 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1588 ty::Visibility::from_hir(&impl_item.vis, item.id, tcx);
1589 self.check(impl_item.id, min(impl_item_vis, ty_vis))
1590 .generics().predicates().ty();
1592 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1593 self.inner_visibility = impl_item_vis;
1594 intravisit::walk_impl_item(self, impl_item);
1597 // A trait impl is public when both its type and its trait are public
1598 // Subitems of trait impls have inherited publicity
1599 hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
1600 let vis = self.check(item.id, ty::Visibility::Invisible)
1601 .ty().impl_trait_ref().min_visibility;
1602 self.check(item.id, vis).generics().predicates();
1603 for impl_item_ref in impl_item_refs {
1604 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1605 self.check(impl_item.id, vis).generics().predicates().ty();
1607 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1608 self.inner_visibility = vis;
1609 intravisit::walk_impl_item(self, impl_item);
1615 fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
1616 // handled in `visit_item` above
1619 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1620 if let hir::TyImplTrait(..) = ty.node {
1621 // Check the traits being exposed, as they're separate,
1622 // e.g. `impl Iterator<Item=T>` has two predicates,
1623 // `X: Iterator` and `<X as Iterator>::Item == T`,
1624 // where `X` is the `impl Iterator<Item=T>` itself,
1625 // stored in `predicates_of`, not in the `Ty` itself.
1626 self.check(ty.id, self.inner_visibility).predicates();
1629 intravisit::walk_ty(self, ty);
1632 // Don't recurse into expressions in array sizes or const initializers
1633 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1634 // Don't recurse into patterns in function arguments
1635 fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
1638 pub fn provide(providers: &mut Providers) {
1639 *providers = Providers {
1640 privacy_access_levels,
1645 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Rc<AccessLevels> {
1646 tcx.dep_graph.with_ignore(|| { // FIXME
1647 tcx.privacy_access_levels(LOCAL_CRATE)
1651 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1653 -> Rc<AccessLevels> {
1654 assert_eq!(krate, LOCAL_CRATE);
1656 let krate = tcx.hir.krate();
1657 let empty_tables = ty::TypeckTables::empty(None);
1659 // Check privacy of names not checked in previous compilation stages.
1660 let mut visitor = NamePrivacyVisitor {
1662 tables: &empty_tables,
1663 current_item: CRATE_NODE_ID,
1664 empty_tables: &empty_tables,
1666 intravisit::walk_crate(&mut visitor, krate);
1668 // Check privacy of explicitly written types and traits as well as
1669 // inferred types of expressions and patterns.
1670 let mut visitor = TypePrivacyVisitor {
1672 tables: &empty_tables,
1673 current_item: DefId::local(CRATE_DEF_INDEX),
1675 empty_tables: &empty_tables,
1677 intravisit::walk_crate(&mut visitor, krate);
1679 // Build up a set of all exported items in the AST. This is a set of all
1680 // items which are reachable from external crates based on visibility.
1681 let mut visitor = EmbargoVisitor {
1683 access_levels: Default::default(),
1684 prev_level: Some(AccessLevel::Public),
1688 intravisit::walk_crate(&mut visitor, krate);
1689 if visitor.changed {
1690 visitor.changed = false;
1695 visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1698 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1700 access_levels: &visitor.access_levels,
1702 old_error_set: NodeSet(),
1704 intravisit::walk_crate(&mut visitor, krate);
1707 let has_pub_restricted = {
1708 let mut pub_restricted_visitor = PubRestrictedVisitor {
1710 has_pub_restricted: false
1712 intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1713 pub_restricted_visitor.has_pub_restricted
1716 // Check for private types and traits in public interfaces
1717 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1720 old_error_set: &visitor.old_error_set,
1721 inner_visibility: ty::Visibility::Public,
1723 krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1726 Rc::new(visitor.access_levels)
1729 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }