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 #![recursion_limit="256"]
20 #[macro_use] extern crate rustc;
21 #[macro_use] extern crate syntax;
22 extern crate rustc_typeck;
23 extern crate syntax_pos;
24 extern crate rustc_data_structures;
26 use rustc::hir::{self, PatKind};
28 use rustc::hir::def::Def;
29 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
30 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
31 use rustc::hir::itemlikevisit::DeepVisitor;
33 use rustc::middle::privacy::{AccessLevel, AccessLevels};
34 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable, GenericParamDefKind};
35 use rustc::ty::fold::TypeVisitor;
36 use rustc::ty::query::Providers;
37 use rustc::ty::subst::UnpackedKind;
38 use rustc::util::nodemap::NodeSet;
39 use syntax::ast::{self, CRATE_NODE_ID, Ident};
40 use syntax::symbol::keywords;
44 use std::mem::replace;
45 use rustc_data_structures::fx::FxHashSet;
46 use rustc_data_structures::sync::Lrc;
50 ////////////////////////////////////////////////////////////////////////////////
51 /// Visitor used to determine if pub(restricted) is used anywhere in the crate.
53 /// This is done so that `private_in_public` warnings can be turned into hard errors
54 /// in crates that have been updated to use pub(restricted).
55 ////////////////////////////////////////////////////////////////////////////////
56 struct PubRestrictedVisitor<'a, 'tcx: 'a> {
57 tcx: TyCtxt<'a, 'tcx, 'tcx>,
58 has_pub_restricted: bool,
61 impl<'a, 'tcx> Visitor<'tcx> for PubRestrictedVisitor<'a, 'tcx> {
62 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
63 NestedVisitorMap::All(&self.tcx.hir())
65 fn visit_vis(&mut self, vis: &'tcx hir::Visibility) {
66 self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted();
70 ////////////////////////////////////////////////////////////////////////////////
71 /// The embargo visitor, used to determine the exports of the ast
72 ////////////////////////////////////////////////////////////////////////////////
74 struct EmbargoVisitor<'a, 'tcx: 'a> {
75 tcx: TyCtxt<'a, 'tcx, 'tcx>,
77 // Accessibility levels for reachable nodes
78 access_levels: AccessLevels,
79 // Previous accessibility level, None means unreachable
80 prev_level: Option<AccessLevel>,
81 // Have something changed in the level map?
85 struct ReachEverythingInTheInterfaceVisitor<'b, 'a: 'b, 'tcx: 'a> {
86 access_level: Option<AccessLevel>,
88 ev: &'b mut EmbargoVisitor<'a, 'tcx>,
91 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
92 fn item_ty_level(&self, item_def_id: DefId) -> Option<AccessLevel> {
93 let ty_def_id = match self.tcx.type_of(item_def_id).sty {
94 ty::Adt(adt, _) => adt.did,
95 ty::Foreign(did) => did,
96 ty::Dynamic(ref obj, ..) => obj.principal().def_id(),
97 ty::Projection(ref proj) => proj.trait_ref(self.tcx).def_id,
98 _ => return Some(AccessLevel::Public)
100 if let Some(node_id) = self.tcx.hir().as_local_node_id(ty_def_id) {
103 Some(AccessLevel::Public)
107 fn impl_trait_level(&self, impl_def_id: DefId) -> Option<AccessLevel> {
108 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_def_id) {
109 if let Some(node_id) = self.tcx.hir().as_local_node_id(trait_ref.def_id) {
110 return self.get(node_id);
113 Some(AccessLevel::Public)
116 fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
117 self.access_levels.map.get(&id).cloned()
120 // Updates node level and returns the updated level
121 fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
122 let old_level = self.get(id);
123 // Accessibility levels can only grow
124 if level > old_level {
125 self.access_levels.map.insert(id, level.unwrap());
133 fn reach<'b>(&'b mut self, item_id: ast::NodeId)
134 -> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
135 ReachEverythingInTheInterfaceVisitor {
136 access_level: self.prev_level.map(|l| l.min(AccessLevel::Reachable)),
137 item_def_id: self.tcx.hir().local_def_id(item_id),
143 impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> {
144 /// We want to visit items in the context of their containing
145 /// module and so forth, so supply a crate for doing a deep walk.
146 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
147 NestedVisitorMap::All(&self.tcx.hir())
150 fn visit_item(&mut self, item: &'tcx hir::Item) {
151 let inherited_item_level = match item.node {
152 // Impls inherit level from their types and traits
153 hir::ItemKind::Impl(..) => {
154 let def_id = self.tcx.hir().local_def_id(item.id);
155 cmp::min(self.item_ty_level(def_id), self.impl_trait_level(def_id))
157 // Foreign mods inherit level from parents
158 hir::ItemKind::ForeignMod(..) => {
161 // Other `pub` items inherit levels from parents
162 hir::ItemKind::Const(..) | hir::ItemKind::Enum(..) | hir::ItemKind::ExternCrate(..) |
163 hir::ItemKind::GlobalAsm(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) |
164 hir::ItemKind::Static(..) | hir::ItemKind::Struct(..) |
165 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) |
166 hir::ItemKind::Existential(..) |
167 hir::ItemKind::Ty(..) | hir::ItemKind::Union(..) | hir::ItemKind::Use(..) => {
168 if item.vis.node.is_pub() { self.prev_level } else { None }
172 // Update level of the item itself
173 let item_level = self.update(item.id, inherited_item_level);
175 // Update levels of nested things
177 hir::ItemKind::Enum(ref def, _) => {
178 for variant in &def.variants {
179 let variant_level = self.update(variant.node.data.id(), item_level);
180 for field in variant.node.data.fields() {
181 self.update(field.id, variant_level);
185 hir::ItemKind::Impl(.., None, _, ref impl_item_refs) => {
186 for impl_item_ref in impl_item_refs {
187 if impl_item_ref.vis.node.is_pub() {
188 self.update(impl_item_ref.id.node_id, item_level);
192 hir::ItemKind::Impl(.., Some(_), _, ref impl_item_refs) => {
193 for impl_item_ref in impl_item_refs {
194 self.update(impl_item_ref.id.node_id, item_level);
197 hir::ItemKind::Trait(.., ref trait_item_refs) => {
198 for trait_item_ref in trait_item_refs {
199 self.update(trait_item_ref.id.node_id, item_level);
202 hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
203 if !def.is_struct() {
204 self.update(def.id(), item_level);
206 for field in def.fields() {
207 if field.vis.node.is_pub() {
208 self.update(field.id, item_level);
212 hir::ItemKind::ForeignMod(ref foreign_mod) => {
213 for foreign_item in &foreign_mod.items {
214 if foreign_item.vis.node.is_pub() {
215 self.update(foreign_item.id, item_level);
219 // Impl trait return types mark their parent function.
220 // It (and its children) are revisited if the change applies.
221 hir::ItemKind::Existential(ref ty_data) => {
222 if let Some(impl_trait_fn) = ty_data.impl_trait_fn {
223 if let Some(node_id) = self.tcx.hir().as_local_node_id(impl_trait_fn) {
224 self.update(node_id, Some(AccessLevel::ReachableFromImplTrait));
228 hir::ItemKind::Use(..) |
229 hir::ItemKind::Static(..) |
230 hir::ItemKind::Const(..) |
231 hir::ItemKind::GlobalAsm(..) |
232 hir::ItemKind::Ty(..) |
233 hir::ItemKind::Mod(..) |
234 hir::ItemKind::TraitAlias(..) |
235 hir::ItemKind::Fn(..) |
236 hir::ItemKind::ExternCrate(..) => {}
239 // Store this node's access level here to propagate the correct
240 // reachability level through interfaces and children.
241 let orig_level = replace(&mut self.prev_level, item_level);
243 // Mark all items in interfaces of reachable items as reachable
245 // The interface is empty
246 hir::ItemKind::ExternCrate(..) => {}
247 // All nested items are checked by visit_item
248 hir::ItemKind::Mod(..) => {}
249 // Re-exports are handled in visit_mod
250 hir::ItemKind::Use(..) => {}
251 // The interface is empty
252 hir::ItemKind::GlobalAsm(..) => {}
253 hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {
254 if item_level.is_some() {
255 // Reach the (potentially private) type and the API being exposed
256 self.reach(item.id).ty().predicates();
260 hir::ItemKind::Const(..) | hir::ItemKind::Static(..) |
261 hir::ItemKind::Existential(..) |
262 hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) => {
263 if item_level.is_some() {
264 self.reach(item.id).generics().predicates().ty();
267 hir::ItemKind::Trait(.., ref trait_item_refs) => {
268 if item_level.is_some() {
269 self.reach(item.id).generics().predicates();
271 for trait_item_ref in trait_item_refs {
272 let mut reach = self.reach(trait_item_ref.id.node_id);
273 reach.generics().predicates();
275 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
276 !trait_item_ref.defaultness.has_value() {
284 hir::ItemKind::TraitAlias(..) => {
285 if item_level.is_some() {
286 self.reach(item.id).generics().predicates();
289 // Visit everything except for private impl items
290 hir::ItemKind::Impl(.., ref trait_ref, _, ref impl_item_refs) => {
291 if item_level.is_some() {
292 self.reach(item.id).generics().predicates().impl_trait_ref();
294 for impl_item_ref in impl_item_refs {
295 let id = impl_item_ref.id.node_id;
296 if trait_ref.is_some() || self.get(id).is_some() {
297 self.reach(id).generics().predicates().ty();
303 // Visit everything, but enum variants have their own levels
304 hir::ItemKind::Enum(ref def, _) => {
305 if item_level.is_some() {
306 self.reach(item.id).generics().predicates();
308 for variant in &def.variants {
309 if self.get(variant.node.data.id()).is_some() {
310 for field in variant.node.data.fields() {
311 self.reach(field.id).ty();
313 // Corner case: if the variant is reachable, but its
314 // enum is not, make the enum reachable as well.
315 self.update(item.id, Some(AccessLevel::Reachable));
319 // Visit everything, but foreign items have their own levels
320 hir::ItemKind::ForeignMod(ref foreign_mod) => {
321 for foreign_item in &foreign_mod.items {
322 if self.get(foreign_item.id).is_some() {
323 self.reach(foreign_item.id).generics().predicates().ty();
327 // Visit everything except for private fields
328 hir::ItemKind::Struct(ref struct_def, _) |
329 hir::ItemKind::Union(ref struct_def, _) => {
330 if item_level.is_some() {
331 self.reach(item.id).generics().predicates();
332 for field in struct_def.fields() {
333 if self.get(field.id).is_some() {
334 self.reach(field.id).ty();
341 intravisit::walk_item(self, item);
343 self.prev_level = orig_level;
346 fn visit_block(&mut self, b: &'tcx hir::Block) {
347 let orig_level = replace(&mut self.prev_level, None);
349 // Blocks can have public items, for example impls, but they always
350 // start as completely private regardless of publicity of a function,
351 // constant, type, field, etc. in which this block resides
352 intravisit::walk_block(self, b);
354 self.prev_level = orig_level;
357 fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
358 // This code is here instead of in visit_item so that the
359 // crate module gets processed as well.
360 if self.prev_level.is_some() {
361 let def_id = self.tcx.hir().local_def_id(id);
362 if let Some(exports) = self.tcx.module_exports(def_id) {
363 for export in exports.iter() {
364 if export.vis == ty::Visibility::Public {
365 if let Some(def_id) = export.def.opt_def_id() {
366 if let Some(node_id) = self.tcx.hir().as_local_node_id(def_id) {
367 self.update(node_id, Some(AccessLevel::Exported));
375 intravisit::walk_mod(self, m, id);
378 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
380 self.update(md.id, Some(AccessLevel::Public));
384 let module_did = ty::DefIdTree::parent(
386 self.tcx.hir().local_def_id(md.id)
388 let mut module_id = self.tcx.hir().as_local_node_id(module_did).unwrap();
389 let level = if md.vis.node.is_pub() { self.get(module_id) } else { None };
390 let level = self.update(md.id, level);
396 let module = if module_id == ast::CRATE_NODE_ID {
397 &self.tcx.hir().krate().module
398 } else if let hir::ItemKind::Mod(ref module) =
399 self.tcx.hir().expect_item(module_id).node {
404 for id in &module.item_ids {
405 self.update(id.id, level);
407 let def_id = self.tcx.hir().local_def_id(module_id);
408 if let Some(exports) = self.tcx.module_exports(def_id) {
409 for export in exports.iter() {
410 if let Some(node_id) = self.tcx.hir().as_local_node_id(export.def.def_id()) {
411 self.update(node_id, level);
416 if module_id == ast::CRATE_NODE_ID {
419 module_id = self.tcx.hir().get_parent_node(module_id);
424 impl<'b, 'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
425 fn generics(&mut self) -> &mut Self {
426 for param in &self.ev.tcx.generics_of(self.item_def_id).params {
428 GenericParamDefKind::Type { has_default, .. } => {
430 self.ev.tcx.type_of(param.def_id).visit_with(self);
433 GenericParamDefKind::Lifetime => {}
439 fn predicates(&mut self) -> &mut Self {
440 let predicates = self.ev.tcx.predicates_of(self.item_def_id);
441 for (predicate, _) in &predicates.predicates {
442 predicate.visit_with(self);
444 &ty::Predicate::Trait(poly_predicate) => {
445 self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
447 &ty::Predicate::Projection(poly_predicate) => {
448 let tcx = self.ev.tcx;
449 self.check_trait_ref(
450 poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
459 fn ty(&mut self) -> &mut Self {
460 let ty = self.ev.tcx.type_of(self.item_def_id);
462 if let ty::FnDef(def_id, _) = ty.sty {
463 if def_id == self.item_def_id {
464 self.ev.tcx.fn_sig(def_id).visit_with(self);
470 fn impl_trait_ref(&mut self) -> &mut Self {
471 if let Some(impl_trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
472 self.check_trait_ref(impl_trait_ref);
473 impl_trait_ref.super_visit_with(self);
478 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
479 if let Some(node_id) = self.ev.tcx.hir().as_local_node_id(trait_ref.def_id) {
480 let item = self.ev.tcx.hir().expect_item(node_id);
481 self.ev.update(item.id, self.access_level);
486 impl<'b, 'a, 'tcx> TypeVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
487 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
488 let ty_def_id = match ty.sty {
489 ty::Adt(adt, _) => Some(adt.did),
490 ty::Foreign(did) => Some(did),
491 ty::Dynamic(ref obj, ..) => Some(obj.principal().def_id()),
492 ty::Projection(ref proj) => Some(proj.item_def_id),
493 ty::FnDef(def_id, ..) |
494 ty::Closure(def_id, ..) |
495 ty::Generator(def_id, ..) |
496 ty::Opaque(def_id, _) => Some(def_id),
500 if let Some(def_id) = ty_def_id {
501 if let Some(node_id) = self.ev.tcx.hir().as_local_node_id(def_id) {
502 self.ev.update(node_id, self.access_level);
506 ty.super_visit_with(self)
510 //////////////////////////////////////////////////////////////////////////////////////
511 /// Name privacy visitor, checks privacy and reports violations.
512 /// Most of name privacy checks are performed during the main resolution phase,
513 /// or later in type checking when field accesses and associated items are resolved.
514 /// This pass performs remaining checks for fields in struct expressions and patterns.
515 //////////////////////////////////////////////////////////////////////////////////////
517 struct NamePrivacyVisitor<'a, 'tcx: 'a> {
518 tcx: TyCtxt<'a, 'tcx, 'tcx>,
519 tables: &'a ty::TypeckTables<'tcx>,
520 current_item: ast::NodeId,
521 empty_tables: &'a ty::TypeckTables<'tcx>,
524 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
525 // Checks that a field in a struct constructor (expression or pattern) is accessible.
526 fn check_field(&mut self,
527 use_ctxt: Span, // Syntax context of the field name at the use site
528 span: Span, // Span of the field pattern, e.g. `x: 0`
529 def: &'tcx ty::AdtDef, // Definition of the struct or enum
530 field: &'tcx ty::FieldDef) { // Definition of the field
531 let ident = Ident::new(keywords::Invalid.name(), use_ctxt);
532 let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
533 if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
534 struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
535 field.ident, def.variant_descr(), self.tcx.item_path_str(def.did))
536 .span_label(span, format!("field `{}` is private", field.ident))
542 // Set the correct TypeckTables for the given `item_id` (or an empty table if
543 // there is no TypeckTables for the item).
544 fn update_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
545 item_id: ast::NodeId,
546 tables: &mut &'a ty::TypeckTables<'tcx>,
547 empty_tables: &'a ty::TypeckTables<'tcx>)
548 -> &'a ty::TypeckTables<'tcx> {
549 let def_id = tcx.hir().local_def_id(item_id);
551 if tcx.has_typeck_tables(def_id) {
552 replace(tables, tcx.typeck_tables_of(def_id))
554 replace(tables, empty_tables)
558 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
559 /// We want to visit items in the context of their containing
560 /// module and so forth, so supply a crate for doing a deep walk.
561 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
562 NestedVisitorMap::All(&self.tcx.hir())
565 fn visit_nested_body(&mut self, body: hir::BodyId) {
566 let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
567 let body = self.tcx.hir().body(body);
568 self.visit_body(body);
569 self.tables = orig_tables;
572 fn visit_item(&mut self, item: &'tcx hir::Item) {
573 let orig_current_item = replace(&mut self.current_item, item.id);
574 let orig_tables = update_tables(self.tcx, item.id, &mut self.tables, self.empty_tables);
575 intravisit::walk_item(self, item);
576 self.current_item = orig_current_item;
577 self.tables = orig_tables;
580 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
581 let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
582 intravisit::walk_trait_item(self, ti);
583 self.tables = orig_tables;
586 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
587 let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
588 intravisit::walk_impl_item(self, ii);
589 self.tables = orig_tables;
592 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
594 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
595 let def = self.tables.qpath_def(qpath, expr.hir_id);
596 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
597 let variant = adt.variant_of_def(def);
598 if let Some(ref base) = *base {
599 // If the expression uses FRU we need to make sure all the unmentioned fields
600 // are checked for privacy (RFC 736). Rather than computing the set of
601 // unmentioned fields, just check them all.
602 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
603 let field = fields.iter().find(|f| {
604 self.tcx.field_index(f.id, self.tables) == vf_index
606 let (use_ctxt, span) = match field {
607 Some(field) => (field.ident.span, field.span),
608 None => (base.span, base.span),
610 self.check_field(use_ctxt, span, adt, variant_field);
613 for field in fields {
614 let use_ctxt = field.ident.span;
615 let index = self.tcx.field_index(field.id, self.tables);
616 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
623 intravisit::walk_expr(self, expr);
626 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
628 PatKind::Struct(ref qpath, ref fields, _) => {
629 let def = self.tables.qpath_def(qpath, pat.hir_id);
630 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
631 let variant = adt.variant_of_def(def);
632 for field in fields {
633 let use_ctxt = field.node.ident.span;
634 let index = self.tcx.field_index(field.node.id, self.tables);
635 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
641 intravisit::walk_pat(self, pat);
645 ////////////////////////////////////////////////////////////////////////////////////////////
646 /// Type privacy visitor, checks types for privacy and reports violations.
647 /// Both explicitly written types and inferred types of expressions and patters are checked.
648 /// Checks are performed on "semantic" types regardless of names and their hygiene.
649 ////////////////////////////////////////////////////////////////////////////////////////////
651 struct TypePrivacyVisitor<'a, 'tcx: 'a> {
652 tcx: TyCtxt<'a, 'tcx, 'tcx>,
653 tables: &'a ty::TypeckTables<'tcx>,
657 empty_tables: &'a ty::TypeckTables<'tcx>,
658 visited_opaque_tys: FxHashSet<DefId>
661 impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
662 fn def_id_visibility(&self, did: DefId) -> ty::Visibility {
663 match self.tcx.hir().as_local_node_id(did) {
665 let vis = match self.tcx.hir().get(node_id) {
666 Node::Item(item) => &item.vis,
667 Node::ForeignItem(foreign_item) => &foreign_item.vis,
668 Node::ImplItem(impl_item) => &impl_item.vis,
669 Node::TraitItem(..) |
670 Node::Variant(..) => {
671 return self.def_id_visibility(self.tcx.hir().get_parent_did(node_id));
673 Node::StructCtor(vdata) => {
674 let struct_node_id = self.tcx.hir().get_parent(node_id);
675 let struct_vis = match self.tcx.hir().get(struct_node_id) {
676 Node::Item(item) => &item.vis,
677 node => bug!("unexpected node kind: {:?}", node),
680 = ty::Visibility::from_hir(struct_vis, struct_node_id, self.tcx);
681 for field in vdata.fields() {
682 let field_vis = ty::Visibility::from_hir(&field.vis, node_id, self.tcx);
683 if ctor_vis.is_at_least(field_vis, self.tcx) {
684 ctor_vis = field_vis;
688 // If the structure is marked as non_exhaustive then lower the
689 // visibility to within the crate.
690 let struct_def_id = self.tcx.hir().get_parent_did(node_id);
691 let adt_def = self.tcx.adt_def(struct_def_id);
692 if adt_def.non_enum_variant().is_field_list_non_exhaustive()
693 && ctor_vis == ty::Visibility::Public
695 ctor_vis = ty::Visibility::Restricted(
696 DefId::local(CRATE_DEF_INDEX));
701 node => bug!("unexpected node kind: {:?}", node)
703 ty::Visibility::from_hir(vis, node_id, self.tcx)
705 None => self.tcx.visibility(did),
709 fn item_is_accessible(&self, did: DefId) -> bool {
710 self.def_id_visibility(did).is_accessible_from(self.current_item, self.tcx)
713 // Take node ID of an expression or pattern and check its type for privacy.
714 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
716 if self.tables.node_id_to_type(id).visit_with(self) {
719 if self.tables.node_substs(id).visit_with(self) {
722 if let Some(adjustments) = self.tables.adjustments().get(id) {
723 for adjustment in adjustments {
724 if adjustment.target.visit_with(self) {
732 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
733 if !self.item_is_accessible(trait_ref.def_id) {
734 let msg = format!("trait `{}` is private", trait_ref);
735 self.tcx.sess.span_err(self.span, &msg);
739 trait_ref.super_visit_with(self)
743 impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
744 /// We want to visit items in the context of their containing
745 /// module and so forth, so supply a crate for doing a deep walk.
746 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
747 NestedVisitorMap::All(&self.tcx.hir())
750 fn visit_nested_body(&mut self, body: hir::BodyId) {
751 let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
752 let orig_in_body = replace(&mut self.in_body, true);
753 let body = self.tcx.hir().body(body);
754 self.visit_body(body);
755 self.tables = orig_tables;
756 self.in_body = orig_in_body;
759 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty) {
760 self.span = hir_ty.span;
763 if self.tables.node_id_to_type(hir_ty.hir_id).visit_with(self) {
767 // Types in signatures.
768 // FIXME: This is very ineffective. Ideally each HIR type should be converted
769 // into a semantic type only once and the result should be cached somehow.
770 if rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty).visit_with(self) {
775 intravisit::walk_ty(self, hir_ty);
778 fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef) {
779 self.span = trait_ref.path.span;
781 // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
782 // The traits' privacy in bodies is already checked as a part of trait object types.
783 let (principal, projections) =
784 rustc_typeck::hir_trait_to_predicates(self.tcx, trait_ref);
785 if self.check_trait_ref(*principal.skip_binder()) {
788 for (poly_predicate, _) in projections {
790 if self.check_trait_ref(poly_predicate.skip_binder().projection_ty.trait_ref(tcx)) {
796 intravisit::walk_trait_ref(self, trait_ref);
799 // Check types of expressions
800 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
801 if self.check_expr_pat_type(expr.hir_id, expr.span) {
802 // Do not check nested expressions if the error already happened.
806 hir::ExprKind::Assign(.., ref rhs) | hir::ExprKind::Match(ref rhs, ..) => {
807 // Do not report duplicate errors for `x = y` and `match x { ... }`.
808 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
812 hir::ExprKind::MethodCall(_, span, _) => {
813 // Method calls have to be checked specially.
815 if let Some(def) = self.tables.type_dependent_defs().get(expr.hir_id) {
816 let def_id = def.def_id();
817 if self.tcx.type_of(def_id).visit_with(self) {
821 self.tcx.sess.delay_span_bug(expr.span,
822 "no type-dependent def for method call");
828 intravisit::walk_expr(self, expr);
831 // Prohibit access to associated items with insufficient nominal visibility.
833 // Additionally, until better reachability analysis for macros 2.0 is available,
834 // we prohibit access to private statics from other crates, this allows to give
835 // more code internal visibility at link time. (Access to private functions
836 // is already prohibited by type privacy for function types.)
837 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: hir::HirId, span: Span) {
838 let def = match *qpath {
839 hir::QPath::Resolved(_, ref path) => match path.def {
840 Def::Method(..) | Def::AssociatedConst(..) |
841 Def::AssociatedTy(..) | Def::Static(..) => Some(path.def),
844 hir::QPath::TypeRelative(..) => {
845 self.tables.type_dependent_defs().get(id).cloned()
848 if let Some(def) = def {
849 let def_id = def.def_id();
850 let is_local_static = if let Def::Static(..) = def { def_id.is_local() } else { false };
851 if !self.item_is_accessible(def_id) && !is_local_static {
852 let name = match *qpath {
853 hir::QPath::Resolved(_, ref path) => path.to_string(),
854 hir::QPath::TypeRelative(_, ref segment) => segment.ident.to_string(),
856 let msg = format!("{} `{}` is private", def.kind_name(), name);
857 self.tcx.sess.span_err(span, &msg);
862 intravisit::walk_qpath(self, qpath, id, span);
865 // Check types of patterns
866 fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
867 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
868 // Do not check nested patterns if the error already happened.
872 intravisit::walk_pat(self, pattern);
875 fn visit_local(&mut self, local: &'tcx hir::Local) {
876 if let Some(ref init) = local.init {
877 if self.check_expr_pat_type(init.hir_id, init.span) {
878 // Do not report duplicate errors for `let x = y`.
883 intravisit::walk_local(self, local);
886 // Check types in item interfaces
887 fn visit_item(&mut self, item: &'tcx hir::Item) {
888 let orig_current_item = self.current_item;
889 let orig_tables = update_tables(self.tcx,
893 let orig_in_body = replace(&mut self.in_body, false);
894 self.current_item = self.tcx.hir().local_def_id(item.id);
895 intravisit::walk_item(self, item);
896 self.tables = orig_tables;
897 self.in_body = orig_in_body;
898 self.current_item = orig_current_item;
901 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
902 let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
903 intravisit::walk_trait_item(self, ti);
904 self.tables = orig_tables;
907 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
908 let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
909 intravisit::walk_impl_item(self, ii);
910 self.tables = orig_tables;
914 impl<'a, 'tcx> TypeVisitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
915 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
917 ty::Adt(&ty::AdtDef { did: def_id, .. }, ..) |
918 ty::FnDef(def_id, ..) |
919 ty::Foreign(def_id) => {
920 if !self.item_is_accessible(def_id) {
921 let msg = format!("type `{}` is private", ty);
922 self.tcx.sess.span_err(self.span, &msg);
925 if let ty::FnDef(..) = ty.sty {
926 if self.tcx.fn_sig(def_id).visit_with(self) {
930 // Inherent static methods don't have self type in substs,
931 // we have to check it additionally.
932 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
933 if let ty::ImplContainer(impl_def_id) = assoc_item.container {
934 if self.tcx.type_of(impl_def_id).visit_with(self) {
940 ty::Dynamic(ref predicates, ..) => {
941 let is_private = predicates.skip_binder().iter().any(|predicate| {
942 let def_id = match *predicate {
943 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref.def_id,
944 ty::ExistentialPredicate::Projection(proj) =>
945 proj.trait_ref(self.tcx).def_id,
946 ty::ExistentialPredicate::AutoTrait(def_id) => def_id,
948 !self.item_is_accessible(def_id)
951 let msg = format!("type `{}` is private", ty);
952 self.tcx.sess.span_err(self.span, &msg);
956 ty::Projection(ref proj) => {
958 if self.check_trait_ref(proj.trait_ref(tcx)) {
962 ty::Opaque(def_id, ..) => {
963 for (predicate, _) in &self.tcx.predicates_of(def_id).predicates {
964 let trait_ref = match *predicate {
965 ty::Predicate::Trait(ref poly_trait_predicate) => {
966 Some(poly_trait_predicate.skip_binder().trait_ref)
968 ty::Predicate::Projection(ref poly_projection_predicate) => {
969 if poly_projection_predicate.skip_binder().ty.visit_with(self) {
972 Some(poly_projection_predicate.skip_binder()
973 .projection_ty.trait_ref(self.tcx))
975 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => None,
976 _ => bug!("unexpected predicate: {:?}", predicate),
978 if let Some(trait_ref) = trait_ref {
979 if !self.item_is_accessible(trait_ref.def_id) {
980 let msg = format!("trait `{}` is private", trait_ref);
981 self.tcx.sess.span_err(self.span, &msg);
984 for subst in trait_ref.substs.iter() {
985 // Skip repeated `Opaque`s to avoid infinite recursion.
986 if let UnpackedKind::Type(ty) = subst.unpack() {
987 if let ty::Opaque(def_id, ..) = ty.sty {
988 if !self.visited_opaque_tys.insert(def_id) {
993 if subst.visit_with(self) {
1003 ty.super_visit_with(self)
1007 ///////////////////////////////////////////////////////////////////////////////
1008 /// Obsolete visitors for checking for private items in public interfaces.
1009 /// These visitors are supposed to be kept in frozen state and produce an
1010 /// "old error node set". For backward compatibility the new visitor reports
1011 /// warnings instead of hard errors when the erroneous node is not in this old set.
1012 ///////////////////////////////////////////////////////////////////////////////
1014 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1015 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1016 access_levels: &'a AccessLevels,
1018 // set of errors produced by this obsolete visitor
1019 old_error_set: NodeSet,
1022 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1023 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1024 /// whether the type refers to private types.
1025 contains_private: bool,
1026 /// whether we've recurred at all (i.e. if we're pointing at the
1027 /// first type on which visit_ty was called).
1028 at_outer_type: bool,
1029 // whether that first type is a public path.
1030 outer_type_is_public_path: bool,
1033 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1034 fn path_is_private_type(&self, path: &hir::Path) -> bool {
1035 let did = match path.def {
1036 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => return false,
1037 def => def.def_id(),
1040 // A path can only be private if:
1041 // it's in this crate...
1042 if let Some(node_id) = self.tcx.hir().as_local_node_id(did) {
1043 // .. and it corresponds to a private type in the AST (this returns
1044 // None for type parameters)
1045 match self.tcx.hir().find(node_id) {
1046 Some(Node::Item(ref item)) => !item.vis.node.is_pub(),
1047 Some(_) | None => false,
1054 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1055 // FIXME: this would preferably be using `exported_items`, but all
1056 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1057 self.access_levels.is_public(trait_id)
1060 fn check_generic_bound(&mut self, bound: &hir::GenericBound) {
1061 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1062 if self.path_is_private_type(&trait_ref.trait_ref.path) {
1063 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1068 fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
1069 self.access_levels.is_reachable(*id) || vis.node.is_pub()
1073 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1074 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1075 NestedVisitorMap::None
1078 fn visit_ty(&mut self, ty: &hir::Ty) {
1079 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = ty.node {
1080 if self.inner.path_is_private_type(path) {
1081 self.contains_private = true;
1082 // found what we're looking for so let's stop
1087 if let hir::TyKind::Path(_) = ty.node {
1088 if self.at_outer_type {
1089 self.outer_type_is_public_path = true;
1092 self.at_outer_type = false;
1093 intravisit::walk_ty(self, ty)
1096 // don't want to recurse into [, .. expr]
1097 fn visit_expr(&mut self, _: &hir::Expr) {}
1100 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1101 /// We want to visit items in the context of their containing
1102 /// module and so forth, so supply a crate for doing a deep walk.
1103 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1104 NestedVisitorMap::All(&self.tcx.hir())
1107 fn visit_item(&mut self, item: &'tcx hir::Item) {
1109 // contents of a private mod can be re-exported, so we need
1110 // to check internals.
1111 hir::ItemKind::Mod(_) => {}
1113 // An `extern {}` doesn't introduce a new privacy
1114 // namespace (the contents have their own privacies).
1115 hir::ItemKind::ForeignMod(_) => {}
1117 hir::ItemKind::Trait(.., ref bounds, _) => {
1118 if !self.trait_is_public(item.id) {
1122 for bound in bounds.iter() {
1123 self.check_generic_bound(bound)
1127 // impls need some special handling to try to offer useful
1128 // error messages without (too many) false positives
1129 // (i.e. we could just return here to not check them at
1130 // all, or some worse estimation of whether an impl is
1131 // publicly visible).
1132 hir::ItemKind::Impl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
1133 // `impl [... for] Private` is never visible.
1134 let self_contains_private;
1135 // impl [... for] Public<...>, but not `impl [... for]
1136 // Vec<Public>` or `(Public,)` etc.
1137 let self_is_public_path;
1139 // check the properties of the Self type:
1141 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1143 contains_private: false,
1144 at_outer_type: true,
1145 outer_type_is_public_path: false,
1147 visitor.visit_ty(&self_);
1148 self_contains_private = visitor.contains_private;
1149 self_is_public_path = visitor.outer_type_is_public_path;
1152 // miscellaneous info about the impl
1154 // `true` iff this is `impl Private for ...`.
1155 let not_private_trait =
1156 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1158 let did = tr.path.def.def_id();
1160 if let Some(node_id) = self.tcx.hir().as_local_node_id(did) {
1161 self.trait_is_public(node_id)
1163 true // external traits must be public
1167 // `true` iff this is a trait impl or at least one method is public.
1169 // `impl Public { $( fn ...() {} )* }` is not visible.
1171 // This is required over just using the methods' privacy
1172 // directly because we might have `impl<T: Foo<Private>> ...`,
1173 // and we shouldn't warn about the generics if all the methods
1174 // are private (because `T` won't be visible externally).
1175 let trait_or_some_public_method =
1176 trait_ref.is_some() ||
1177 impl_item_refs.iter()
1178 .any(|impl_item_ref| {
1179 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1180 match impl_item.node {
1181 hir::ImplItemKind::Const(..) |
1182 hir::ImplItemKind::Method(..) => {
1183 self.access_levels.is_reachable(impl_item.id)
1185 hir::ImplItemKind::Existential(..) |
1186 hir::ImplItemKind::Type(_) => false,
1190 if !self_contains_private &&
1191 not_private_trait &&
1192 trait_or_some_public_method {
1194 intravisit::walk_generics(self, g);
1198 for impl_item_ref in impl_item_refs {
1199 // This is where we choose whether to walk down
1200 // further into the impl to check its items. We
1201 // should only walk into public items so that we
1202 // don't erroneously report errors for private
1203 // types in private items.
1204 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1205 match impl_item.node {
1206 hir::ImplItemKind::Const(..) |
1207 hir::ImplItemKind::Method(..)
1208 if self.item_is_public(&impl_item.id, &impl_item.vis) =>
1210 intravisit::walk_impl_item(self, impl_item)
1212 hir::ImplItemKind::Type(..) => {
1213 intravisit::walk_impl_item(self, impl_item)
1220 // Any private types in a trait impl fall into three
1222 // 1. mentioned in the trait definition
1223 // 2. mentioned in the type params/generics
1224 // 3. mentioned in the associated types of the impl
1226 // Those in 1. can only occur if the trait is in
1227 // this crate and will've been warned about on the
1228 // trait definition (there's no need to warn twice
1229 // so we don't check the methods).
1231 // Those in 2. are warned via walk_generics and this
1233 intravisit::walk_path(self, &tr.path);
1235 // Those in 3. are warned with this call.
1236 for impl_item_ref in impl_item_refs {
1237 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1238 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1244 } else if trait_ref.is_none() && self_is_public_path {
1245 // impl Public<Private> { ... }. Any public static
1246 // methods will be visible as `Public::foo`.
1247 let mut found_pub_static = false;
1248 for impl_item_ref in impl_item_refs {
1249 if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
1250 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1251 match impl_item_ref.kind {
1252 hir::AssociatedItemKind::Const => {
1253 found_pub_static = true;
1254 intravisit::walk_impl_item(self, impl_item);
1256 hir::AssociatedItemKind::Method { has_self: false } => {
1257 found_pub_static = true;
1258 intravisit::walk_impl_item(self, impl_item);
1264 if found_pub_static {
1265 intravisit::walk_generics(self, g)
1271 // `type ... = ...;` can contain private types, because
1272 // we're introducing a new name.
1273 hir::ItemKind::Ty(..) => return,
1275 // not at all public, so we don't care
1276 _ if !self.item_is_public(&item.id, &item.vis) => {
1283 // We've carefully constructed it so that if we're here, then
1284 // any `visit_ty`'s will be called on things that are in
1285 // public signatures, i.e. things that we're interested in for
1287 intravisit::walk_item(self, item);
1290 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1291 for param in &generics.params {
1292 for bound in ¶m.bounds {
1293 self.check_generic_bound(bound);
1296 for predicate in &generics.where_clause.predicates {
1298 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1299 for bound in bound_pred.bounds.iter() {
1300 self.check_generic_bound(bound)
1303 &hir::WherePredicate::RegionPredicate(_) => {}
1304 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1305 self.visit_ty(&eq_pred.rhs_ty);
1311 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
1312 if self.access_levels.is_reachable(item.id) {
1313 intravisit::walk_foreign_item(self, item)
1317 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1318 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = t.node {
1319 if self.path_is_private_type(path) {
1320 self.old_error_set.insert(t.id);
1323 intravisit::walk_ty(self, t)
1326 fn visit_variant(&mut self,
1327 v: &'tcx hir::Variant,
1328 g: &'tcx hir::Generics,
1329 item_id: ast::NodeId) {
1330 if self.access_levels.is_reachable(v.node.data.id()) {
1331 self.in_variant = true;
1332 intravisit::walk_variant(self, v, g, item_id);
1333 self.in_variant = false;
1337 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
1338 if s.vis.node.is_pub() || self.in_variant {
1339 intravisit::walk_struct_field(self, s);
1343 // we don't need to introspect into these at all: an
1344 // expression/block context can't possibly contain exported things.
1345 // (Making them no-ops stops us from traversing the whole AST without
1346 // having to be super careful about our `walk_...` calls above.)
1347 fn visit_block(&mut self, _: &'tcx hir::Block) {}
1348 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1351 ///////////////////////////////////////////////////////////////////////////////
1352 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1353 /// finds any private components in it.
1354 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1355 /// and traits in public interfaces.
1356 ///////////////////////////////////////////////////////////////////////////////
1358 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1359 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1362 /// The visitor checks that each component type is at least this visible
1363 required_visibility: ty::Visibility,
1364 /// The visibility of the least visible component that has been visited
1365 min_visibility: ty::Visibility,
1366 has_pub_restricted: bool,
1367 has_old_errors: bool,
1371 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1372 fn generics(&mut self) -> &mut Self {
1373 for param in &self.tcx.generics_of(self.item_def_id).params {
1375 GenericParamDefKind::Type { has_default, .. } => {
1377 self.tcx.type_of(param.def_id).visit_with(self);
1380 GenericParamDefKind::Lifetime => {}
1386 fn predicates(&mut self) -> &mut Self {
1387 // NB: We use `explicit_predicates_of` and not `predicates_of`
1388 // because we don't want to report privacy errors due to where
1389 // clauses that the compiler inferred. We only want to
1390 // consider the ones that the user wrote. This is important
1391 // for the inferred outlives rules; see
1392 // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1393 let predicates = self.tcx.explicit_predicates_of(self.item_def_id);
1394 for (predicate, _) in &predicates.predicates {
1395 predicate.visit_with(self);
1397 &ty::Predicate::Trait(poly_predicate) => {
1398 self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
1400 &ty::Predicate::Projection(poly_predicate) => {
1402 self.check_trait_ref(
1403 poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
1412 fn ty(&mut self) -> &mut Self {
1413 let ty = self.tcx.type_of(self.item_def_id);
1414 ty.visit_with(self);
1415 if let ty::FnDef(def_id, _) = ty.sty {
1416 if def_id == self.item_def_id {
1417 self.tcx.fn_sig(def_id).visit_with(self);
1423 fn impl_trait_ref(&mut self) -> &mut Self {
1424 if let Some(impl_trait_ref) = self.tcx.impl_trait_ref(self.item_def_id) {
1425 self.check_trait_ref(impl_trait_ref);
1426 impl_trait_ref.super_visit_with(self);
1431 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
1432 // Non-local means public (private items can't leave their crate, modulo bugs)
1433 if let Some(node_id) = self.tcx.hir().as_local_node_id(trait_ref.def_id) {
1434 let item = self.tcx.hir().expect_item(node_id);
1435 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1436 if !vis.is_at_least(self.min_visibility, self.tcx) {
1437 self.min_visibility = vis;
1439 if !vis.is_at_least(self.required_visibility, self.tcx) {
1440 if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1441 struct_span_err!(self.tcx.sess, self.span, E0445,
1442 "private trait `{}` in public interface", trait_ref)
1443 .span_label(self.span, format!(
1444 "can't leak private trait"))
1447 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1450 &format!("private trait `{}` in public \
1451 interface (error E0445)", trait_ref));
1458 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1459 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
1460 let ty_def_id = match ty.sty {
1461 ty::Adt(adt, _) => Some(adt.did),
1462 ty::Foreign(did) => Some(did),
1463 ty::Dynamic(ref obj, ..) => Some(obj.principal().def_id()),
1464 ty::Projection(ref proj) => {
1465 if self.required_visibility == ty::Visibility::Invisible {
1466 // Conservatively approximate the whole type alias as public without
1467 // recursing into its components when determining impl publicity.
1468 // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
1469 // even if both `Type` and `Trait` are private.
1470 // Ideally, associated types should be substituted in the same way as
1471 // free type aliases, but this isn't done yet.
1474 let trait_ref = proj.trait_ref(self.tcx);
1475 Some(trait_ref.def_id)
1480 if let Some(def_id) = ty_def_id {
1481 // Non-local means public (private items can't leave their crate, modulo bugs)
1482 if let Some(node_id) = self.tcx.hir().as_local_node_id(def_id) {
1483 let hir_vis = match self.tcx.hir().find(node_id) {
1484 Some(Node::Item(item)) => &item.vis,
1485 Some(Node::ForeignItem(item)) => &item.vis,
1486 _ => bug!("expected item of foreign item"),
1489 let vis = ty::Visibility::from_hir(hir_vis, node_id, self.tcx);
1491 if !vis.is_at_least(self.min_visibility, self.tcx) {
1492 self.min_visibility = vis;
1494 if !vis.is_at_least(self.required_visibility, self.tcx) {
1495 let vis_adj = match hir_vis.node {
1496 hir::VisibilityKind::Crate(_) => "crate-visible",
1497 hir::VisibilityKind::Restricted { .. } => "restricted",
1501 if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1502 let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
1503 "{} type `{}` in public interface", vis_adj, ty);
1504 err.span_label(self.span, format!("can't leak {} type", vis_adj));
1505 err.span_label(hir_vis.span, format!("`{}` declared as {}", ty, vis_adj));
1508 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1511 &format!("{} type `{}` in public \
1512 interface (error E0446)", vis_adj, ty));
1518 ty.super_visit_with(self)
1522 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1523 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1524 has_pub_restricted: bool,
1525 old_error_set: &'a NodeSet,
1526 inner_visibility: ty::Visibility,
1529 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1530 fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1531 -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1532 let mut has_old_errors = false;
1534 // Slow path taken only if there any errors in the crate.
1535 for &id in self.old_error_set {
1536 // Walk up the nodes until we find `item_id` (or we hit a root).
1540 has_old_errors = true;
1543 let parent = self.tcx.hir().get_parent_node(id);
1555 SearchInterfaceForPrivateItemsVisitor {
1557 item_def_id: self.tcx.hir().local_def_id(item_id),
1558 span: self.tcx.hir().span(item_id),
1559 min_visibility: ty::Visibility::Public,
1560 required_visibility,
1561 has_pub_restricted: self.has_pub_restricted,
1568 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1569 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1570 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1573 fn visit_item(&mut self, item: &'tcx hir::Item) {
1575 let min = |vis1: ty::Visibility, vis2| {
1576 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1579 let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1582 // Crates are always public
1583 hir::ItemKind::ExternCrate(..) => {}
1584 // All nested items are checked by visit_item
1585 hir::ItemKind::Mod(..) => {}
1586 // Checked in resolve
1587 hir::ItemKind::Use(..) => {}
1589 hir::ItemKind::GlobalAsm(..) => {}
1590 hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {
1591 // Check the traits being exposed, as they're separate,
1592 // e.g. `impl Iterator<Item=T>` has two predicates,
1593 // `X: Iterator` and `<X as Iterator>::Item == T`,
1594 // where `X` is the `impl Iterator<Item=T>` itself,
1595 // stored in `predicates_of`, not in the `Ty` itself.
1597 self.check(item.id, item_visibility).predicates();
1599 // Subitems of these items have inherited publicity
1600 hir::ItemKind::Const(..) | hir::ItemKind::Static(..) | hir::ItemKind::Fn(..) |
1601 hir::ItemKind::Existential(..) |
1602 hir::ItemKind::Ty(..) => {
1603 self.check(item.id, item_visibility).generics().predicates().ty();
1605 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1606 self.inner_visibility = item_visibility;
1607 intravisit::walk_item(self, item);
1609 hir::ItemKind::Trait(.., ref trait_item_refs) => {
1610 self.check(item.id, item_visibility).generics().predicates();
1612 for trait_item_ref in trait_item_refs {
1613 let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1614 check.in_assoc_ty = trait_item_ref.kind == hir::AssociatedItemKind::Type;
1615 check.generics().predicates();
1617 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1618 !trait_item_ref.defaultness.has_value() {
1619 // No type to visit.
1625 hir::ItemKind::TraitAlias(..) => {
1626 self.check(item.id, item_visibility).generics().predicates();
1628 hir::ItemKind::Enum(ref def, _) => {
1629 self.check(item.id, item_visibility).generics().predicates();
1631 for variant in &def.variants {
1632 for field in variant.node.data.fields() {
1633 self.check(field.id, item_visibility).ty();
1637 // Subitems of foreign modules have their own publicity
1638 hir::ItemKind::ForeignMod(ref foreign_mod) => {
1639 for foreign_item in &foreign_mod.items {
1640 let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1641 self.check(foreign_item.id, vis).generics().predicates().ty();
1644 // Subitems of structs and unions have their own publicity
1645 hir::ItemKind::Struct(ref struct_def, _) |
1646 hir::ItemKind::Union(ref struct_def, _) => {
1647 self.check(item.id, item_visibility).generics().predicates();
1649 for field in struct_def.fields() {
1650 let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1651 self.check(field.id, min(item_visibility, field_visibility)).ty();
1654 // An inherent impl is public when its type is public
1655 // Subitems of inherent impls have their own publicity
1656 hir::ItemKind::Impl(.., None, _, ref impl_item_refs) => {
1658 self.check(item.id, ty::Visibility::Invisible).ty().min_visibility;
1659 self.check(item.id, ty_vis).generics().predicates();
1661 for impl_item_ref in impl_item_refs {
1662 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1663 let impl_item_vis = ty::Visibility::from_hir(&impl_item.vis, item.id, tcx);
1664 let mut check = self.check(impl_item.id, min(impl_item_vis, ty_vis));
1665 check.in_assoc_ty = impl_item_ref.kind == hir::AssociatedItemKind::Type;
1666 check.generics().predicates().ty();
1668 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1669 self.inner_visibility = impl_item_vis;
1670 intravisit::walk_impl_item(self, impl_item);
1673 // A trait impl is public when both its type and its trait are public
1674 // Subitems of trait impls have inherited publicity
1675 hir::ItemKind::Impl(.., Some(_), _, ref impl_item_refs) => {
1676 let vis = self.check(item.id, ty::Visibility::Invisible)
1677 .ty().impl_trait_ref().min_visibility;
1678 self.check(item.id, vis).generics().predicates();
1679 for impl_item_ref in impl_item_refs {
1680 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1681 let mut check = self.check(impl_item.id, vis);
1682 check.in_assoc_ty = impl_item_ref.kind == hir::AssociatedItemKind::Type;
1683 check.generics().predicates().ty();
1685 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1686 self.inner_visibility = vis;
1687 intravisit::walk_impl_item(self, impl_item);
1693 fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
1694 // handled in `visit_item` above
1697 // Don't recurse into expressions in array sizes or const initializers
1698 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1699 // Don't recurse into patterns in function arguments
1700 fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
1703 pub fn provide(providers: &mut Providers) {
1704 *providers = Providers {
1705 privacy_access_levels,
1710 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Lrc<AccessLevels> {
1711 tcx.privacy_access_levels(LOCAL_CRATE)
1714 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1716 -> Lrc<AccessLevels> {
1717 assert_eq!(krate, LOCAL_CRATE);
1719 let krate = tcx.hir().krate();
1720 let empty_tables = ty::TypeckTables::empty(None);
1722 // Check privacy of names not checked in previous compilation stages.
1723 let mut visitor = NamePrivacyVisitor {
1725 tables: &empty_tables,
1726 current_item: CRATE_NODE_ID,
1727 empty_tables: &empty_tables,
1729 intravisit::walk_crate(&mut visitor, krate);
1731 // Check privacy of explicitly written types and traits as well as
1732 // inferred types of expressions and patterns.
1733 let mut visitor = TypePrivacyVisitor {
1735 tables: &empty_tables,
1736 current_item: DefId::local(CRATE_DEF_INDEX),
1739 empty_tables: &empty_tables,
1740 visited_opaque_tys: FxHashSet::default()
1742 intravisit::walk_crate(&mut visitor, krate);
1744 // Build up a set of all exported items in the AST. This is a set of all
1745 // items which are reachable from external crates based on visibility.
1746 let mut visitor = EmbargoVisitor {
1748 access_levels: Default::default(),
1749 prev_level: Some(AccessLevel::Public),
1753 intravisit::walk_crate(&mut visitor, krate);
1754 if visitor.changed {
1755 visitor.changed = false;
1760 visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1763 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1765 access_levels: &visitor.access_levels,
1767 old_error_set: Default::default(),
1769 intravisit::walk_crate(&mut visitor, krate);
1772 let has_pub_restricted = {
1773 let mut pub_restricted_visitor = PubRestrictedVisitor {
1775 has_pub_restricted: false
1777 intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1778 pub_restricted_visitor.has_pub_restricted
1781 // Check for private types and traits in public interfaces
1782 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1785 old_error_set: &visitor.old_error_set,
1786 inner_visibility: ty::Visibility::Public,
1788 krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1791 Lrc::new(visitor.access_levels)
1794 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }