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(self.tcx, self.tcx.hir.local_def_id(md.id)).unwrap();
385 let mut module_id = self.tcx.hir.as_local_node_id(module_did).unwrap();
386 let level = if md.vis.node.is_pub() { self.get(module_id) } else { None };
387 let level = self.update(md.id, level);
393 let module = if module_id == ast::CRATE_NODE_ID {
394 &self.tcx.hir.krate().module
395 } else if let hir::ItemKind::Mod(ref module) = self.tcx.hir.expect_item(module_id).node
401 for id in &module.item_ids {
402 self.update(id.id, level);
404 let def_id = self.tcx.hir.local_def_id(module_id);
405 if let Some(exports) = self.tcx.module_exports(def_id) {
406 for export in exports.iter() {
407 if let Some(node_id) = self.tcx.hir.as_local_node_id(export.def.def_id()) {
408 self.update(node_id, level);
413 if module_id == ast::CRATE_NODE_ID {
416 module_id = self.tcx.hir.get_parent_node(module_id);
421 impl<'b, 'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
422 fn generics(&mut self) -> &mut Self {
423 for param in &self.ev.tcx.generics_of(self.item_def_id).params {
425 GenericParamDefKind::Type { has_default, .. } => {
427 self.ev.tcx.type_of(param.def_id).visit_with(self);
430 GenericParamDefKind::Lifetime => {}
436 fn predicates(&mut self) -> &mut Self {
437 let predicates = self.ev.tcx.predicates_of(self.item_def_id);
438 for (predicate, _) in &predicates.predicates {
439 predicate.visit_with(self);
441 &ty::Predicate::Trait(poly_predicate) => {
442 self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
444 &ty::Predicate::Projection(poly_predicate) => {
445 let tcx = self.ev.tcx;
446 self.check_trait_ref(
447 poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
456 fn ty(&mut self) -> &mut Self {
457 let ty = self.ev.tcx.type_of(self.item_def_id);
459 if let ty::FnDef(def_id, _) = ty.sty {
460 if def_id == self.item_def_id {
461 self.ev.tcx.fn_sig(def_id).visit_with(self);
467 fn impl_trait_ref(&mut self) -> &mut Self {
468 if let Some(impl_trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
469 self.check_trait_ref(impl_trait_ref);
470 impl_trait_ref.super_visit_with(self);
475 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
476 if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(trait_ref.def_id) {
477 let item = self.ev.tcx.hir.expect_item(node_id);
478 self.ev.update(item.id, self.access_level);
483 impl<'b, 'a, 'tcx> TypeVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
484 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
485 let ty_def_id = match ty.sty {
486 ty::Adt(adt, _) => Some(adt.did),
487 ty::Foreign(did) => Some(did),
488 ty::Dynamic(ref obj, ..) => Some(obj.principal().def_id()),
489 ty::Projection(ref proj) => Some(proj.item_def_id),
490 ty::FnDef(def_id, ..) |
491 ty::Closure(def_id, ..) |
492 ty::Generator(def_id, ..) |
493 ty::Opaque(def_id, _) => Some(def_id),
497 if let Some(def_id) = ty_def_id {
498 if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(def_id) {
499 self.ev.update(node_id, self.access_level);
503 ty.super_visit_with(self)
507 //////////////////////////////////////////////////////////////////////////////////////
508 /// Name privacy visitor, checks privacy and reports violations.
509 /// Most of name privacy checks are performed during the main resolution phase,
510 /// or later in type checking when field accesses and associated items are resolved.
511 /// This pass performs remaining checks for fields in struct expressions and patterns.
512 //////////////////////////////////////////////////////////////////////////////////////
514 struct NamePrivacyVisitor<'a, 'tcx: 'a> {
515 tcx: TyCtxt<'a, 'tcx, 'tcx>,
516 tables: &'a ty::TypeckTables<'tcx>,
517 current_item: ast::NodeId,
518 empty_tables: &'a ty::TypeckTables<'tcx>,
521 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
522 // Checks that a field in a struct constructor (expression or pattern) is accessible.
523 fn check_field(&mut self,
524 use_ctxt: Span, // Syntax context of the field name at the use site
525 span: Span, // Span of the field pattern, e.g. `x: 0`
526 def: &'tcx ty::AdtDef, // Definition of the struct or enum
527 field: &'tcx ty::FieldDef) { // Definition of the field
528 let ident = Ident::new(keywords::Invalid.name(), use_ctxt);
529 let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
530 if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
531 struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
532 field.ident, def.variant_descr(), self.tcx.item_path_str(def.did))
533 .span_label(span, format!("field `{}` is private", field.ident))
539 // Set the correct TypeckTables for the given `item_id` (or an empty table if
540 // there is no TypeckTables for the item).
541 fn update_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
542 item_id: ast::NodeId,
543 tables: &mut &'a ty::TypeckTables<'tcx>,
544 empty_tables: &'a ty::TypeckTables<'tcx>)
545 -> &'a ty::TypeckTables<'tcx> {
546 let def_id = tcx.hir.local_def_id(item_id);
548 if tcx.has_typeck_tables(def_id) {
549 replace(tables, tcx.typeck_tables_of(def_id))
551 replace(tables, empty_tables)
555 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
556 /// We want to visit items in the context of their containing
557 /// module and so forth, so supply a crate for doing a deep walk.
558 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
559 NestedVisitorMap::All(&self.tcx.hir)
562 fn visit_nested_body(&mut self, body: hir::BodyId) {
563 let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
564 let body = self.tcx.hir.body(body);
565 self.visit_body(body);
566 self.tables = orig_tables;
569 fn visit_item(&mut self, item: &'tcx hir::Item) {
570 let orig_current_item = replace(&mut self.current_item, item.id);
571 let orig_tables = update_tables(self.tcx, item.id, &mut self.tables, self.empty_tables);
572 intravisit::walk_item(self, item);
573 self.current_item = orig_current_item;
574 self.tables = orig_tables;
577 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
578 let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
579 intravisit::walk_trait_item(self, ti);
580 self.tables = orig_tables;
583 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
584 let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
585 intravisit::walk_impl_item(self, ii);
586 self.tables = orig_tables;
589 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
591 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
592 let def = self.tables.qpath_def(qpath, expr.hir_id);
593 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
594 let variant = adt.variant_of_def(def);
595 if let Some(ref base) = *base {
596 // If the expression uses FRU we need to make sure all the unmentioned fields
597 // are checked for privacy (RFC 736). Rather than computing the set of
598 // unmentioned fields, just check them all.
599 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
600 let field = fields.iter().find(|f| {
601 self.tcx.field_index(f.id, self.tables) == vf_index
603 let (use_ctxt, span) = match field {
604 Some(field) => (field.ident.span, field.span),
605 None => (base.span, base.span),
607 self.check_field(use_ctxt, span, adt, variant_field);
610 for field in fields {
611 let use_ctxt = field.ident.span;
612 let index = self.tcx.field_index(field.id, self.tables);
613 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
620 intravisit::walk_expr(self, expr);
623 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
625 PatKind::Struct(ref qpath, ref fields, _) => {
626 let def = self.tables.qpath_def(qpath, pat.hir_id);
627 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
628 let variant = adt.variant_of_def(def);
629 for field in fields {
630 let use_ctxt = field.node.ident.span;
631 let index = self.tcx.field_index(field.node.id, self.tables);
632 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
638 intravisit::walk_pat(self, pat);
642 ////////////////////////////////////////////////////////////////////////////////////////////
643 /// Type privacy visitor, checks types for privacy and reports violations.
644 /// Both explicitly written types and inferred types of expressions and patters are checked.
645 /// Checks are performed on "semantic" types regardless of names and their hygiene.
646 ////////////////////////////////////////////////////////////////////////////////////////////
648 struct TypePrivacyVisitor<'a, 'tcx: 'a> {
649 tcx: TyCtxt<'a, 'tcx, 'tcx>,
650 tables: &'a ty::TypeckTables<'tcx>,
654 empty_tables: &'a ty::TypeckTables<'tcx>,
655 visited_opaque_tys: FxHashSet<DefId>
658 impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
659 fn def_id_visibility(&self, did: DefId) -> ty::Visibility {
660 match self.tcx.hir.as_local_node_id(did) {
662 let vis = match self.tcx.hir.get(node_id) {
663 Node::Item(item) => &item.vis,
664 Node::ForeignItem(foreign_item) => &foreign_item.vis,
665 Node::ImplItem(impl_item) => &impl_item.vis,
666 Node::TraitItem(..) |
667 Node::Variant(..) => {
668 return self.def_id_visibility(self.tcx.hir.get_parent_did(node_id));
670 Node::StructCtor(vdata) => {
671 let struct_node_id = self.tcx.hir.get_parent(node_id);
672 let struct_vis = match self.tcx.hir.get(struct_node_id) {
673 Node::Item(item) => &item.vis,
674 node => bug!("unexpected node kind: {:?}", node),
677 = ty::Visibility::from_hir(struct_vis, struct_node_id, self.tcx);
678 for field in vdata.fields() {
679 let field_vis = ty::Visibility::from_hir(&field.vis, node_id, self.tcx);
680 if ctor_vis.is_at_least(field_vis, self.tcx) {
681 ctor_vis = field_vis;
685 // If the structure is marked as non_exhaustive then lower the
686 // visibility to within the crate.
687 let struct_def_id = self.tcx.hir.get_parent_did(node_id);
688 let adt_def = self.tcx.adt_def(struct_def_id);
689 if adt_def.non_enum_variant().is_field_list_non_exhaustive()
690 && ctor_vis == ty::Visibility::Public
692 ctor_vis = ty::Visibility::Restricted(
693 DefId::local(CRATE_DEF_INDEX));
698 node => bug!("unexpected node kind: {:?}", node)
700 ty::Visibility::from_hir(vis, node_id, self.tcx)
702 None => self.tcx.visibility(did),
706 fn item_is_accessible(&self, did: DefId) -> bool {
707 self.def_id_visibility(did).is_accessible_from(self.current_item, self.tcx)
710 // Take node ID of an expression or pattern and check its type for privacy.
711 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
713 if self.tables.node_id_to_type(id).visit_with(self) {
716 if self.tables.node_substs(id).visit_with(self) {
719 if let Some(adjustments) = self.tables.adjustments().get(id) {
720 for adjustment in adjustments {
721 if adjustment.target.visit_with(self) {
729 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
730 if !self.item_is_accessible(trait_ref.def_id) {
731 let msg = format!("trait `{}` is private", trait_ref);
732 self.tcx.sess.span_err(self.span, &msg);
736 trait_ref.super_visit_with(self)
740 impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
741 /// We want to visit items in the context of their containing
742 /// module and so forth, so supply a crate for doing a deep walk.
743 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
744 NestedVisitorMap::All(&self.tcx.hir)
747 fn visit_nested_body(&mut self, body: hir::BodyId) {
748 let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
749 let orig_in_body = replace(&mut self.in_body, true);
750 let body = self.tcx.hir.body(body);
751 self.visit_body(body);
752 self.tables = orig_tables;
753 self.in_body = orig_in_body;
756 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty) {
757 self.span = hir_ty.span;
760 if self.tables.node_id_to_type(hir_ty.hir_id).visit_with(self) {
764 // Types in signatures.
765 // FIXME: This is very ineffective. Ideally each HIR type should be converted
766 // into a semantic type only once and the result should be cached somehow.
767 if rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty).visit_with(self) {
772 intravisit::walk_ty(self, hir_ty);
775 fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef) {
776 self.span = trait_ref.path.span;
778 // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
779 // The traits' privacy in bodies is already checked as a part of trait object types.
780 let (principal, projections) =
781 rustc_typeck::hir_trait_to_predicates(self.tcx, trait_ref);
782 if self.check_trait_ref(*principal.skip_binder()) {
785 for (poly_predicate, _) in projections {
787 if self.check_trait_ref(poly_predicate.skip_binder().projection_ty.trait_ref(tcx)) {
793 intravisit::walk_trait_ref(self, trait_ref);
796 // Check types of expressions
797 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
798 if self.check_expr_pat_type(expr.hir_id, expr.span) {
799 // Do not check nested expressions if the error already happened.
803 hir::ExprKind::Assign(.., ref rhs) | hir::ExprKind::Match(ref rhs, ..) => {
804 // Do not report duplicate errors for `x = y` and `match x { ... }`.
805 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
809 hir::ExprKind::MethodCall(_, span, _) => {
810 // Method calls have to be checked specially.
812 if let Some(def) = self.tables.type_dependent_defs().get(expr.hir_id) {
813 let def_id = def.def_id();
814 if self.tcx.type_of(def_id).visit_with(self) {
818 self.tcx.sess.delay_span_bug(expr.span,
819 "no type-dependent def for method call");
825 intravisit::walk_expr(self, expr);
828 // Prohibit access to associated items with insufficient nominal visibility.
830 // Additionally, until better reachability analysis for macros 2.0 is available,
831 // we prohibit access to private statics from other crates, this allows to give
832 // more code internal visibility at link time. (Access to private functions
833 // is already prohibited by type privacy for function types.)
834 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: hir::HirId, span: Span) {
835 let def = match *qpath {
836 hir::QPath::Resolved(_, ref path) => match path.def {
837 Def::Method(..) | Def::AssociatedConst(..) |
838 Def::AssociatedTy(..) | Def::Static(..) => Some(path.def),
841 hir::QPath::TypeRelative(..) => {
842 self.tables.type_dependent_defs().get(id).cloned()
845 if let Some(def) = def {
846 let def_id = def.def_id();
847 let is_local_static = if let Def::Static(..) = def { def_id.is_local() } else { false };
848 if !self.item_is_accessible(def_id) && !is_local_static {
849 let name = match *qpath {
850 hir::QPath::Resolved(_, ref path) => path.to_string(),
851 hir::QPath::TypeRelative(_, ref segment) => segment.ident.to_string(),
853 let msg = format!("{} `{}` is private", def.kind_name(), name);
854 self.tcx.sess.span_err(span, &msg);
859 intravisit::walk_qpath(self, qpath, id, span);
862 // Check types of patterns
863 fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
864 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
865 // Do not check nested patterns if the error already happened.
869 intravisit::walk_pat(self, pattern);
872 fn visit_local(&mut self, local: &'tcx hir::Local) {
873 if let Some(ref init) = local.init {
874 if self.check_expr_pat_type(init.hir_id, init.span) {
875 // Do not report duplicate errors for `let x = y`.
880 intravisit::walk_local(self, local);
883 // Check types in item interfaces
884 fn visit_item(&mut self, item: &'tcx hir::Item) {
885 let orig_current_item = self.current_item;
886 let orig_tables = update_tables(self.tcx,
890 let orig_in_body = replace(&mut self.in_body, false);
891 self.current_item = self.tcx.hir.local_def_id(item.id);
892 intravisit::walk_item(self, item);
893 self.tables = orig_tables;
894 self.in_body = orig_in_body;
895 self.current_item = orig_current_item;
898 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
899 let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
900 intravisit::walk_trait_item(self, ti);
901 self.tables = orig_tables;
904 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
905 let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
906 intravisit::walk_impl_item(self, ii);
907 self.tables = orig_tables;
911 impl<'a, 'tcx> TypeVisitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
912 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
914 ty::Adt(&ty::AdtDef { did: def_id, .. }, ..) |
915 ty::FnDef(def_id, ..) |
916 ty::Foreign(def_id) => {
917 if !self.item_is_accessible(def_id) {
918 let msg = format!("type `{}` is private", ty);
919 self.tcx.sess.span_err(self.span, &msg);
922 if let ty::FnDef(..) = ty.sty {
923 if self.tcx.fn_sig(def_id).visit_with(self) {
927 // Inherent static methods don't have self type in substs,
928 // we have to check it additionally.
929 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
930 if let ty::ImplContainer(impl_def_id) = assoc_item.container {
931 if self.tcx.type_of(impl_def_id).visit_with(self) {
937 ty::Dynamic(ref predicates, ..) => {
938 let is_private = predicates.skip_binder().iter().any(|predicate| {
939 let def_id = match *predicate {
940 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref.def_id,
941 ty::ExistentialPredicate::Projection(proj) =>
942 proj.trait_ref(self.tcx).def_id,
943 ty::ExistentialPredicate::AutoTrait(def_id) => def_id,
945 !self.item_is_accessible(def_id)
948 let msg = format!("type `{}` is private", ty);
949 self.tcx.sess.span_err(self.span, &msg);
953 ty::Projection(ref proj) => {
955 if self.check_trait_ref(proj.trait_ref(tcx)) {
959 ty::Opaque(def_id, ..) => {
960 for (predicate, _) in &self.tcx.predicates_of(def_id).predicates {
961 let trait_ref = match *predicate {
962 ty::Predicate::Trait(ref poly_trait_predicate) => {
963 Some(poly_trait_predicate.skip_binder().trait_ref)
965 ty::Predicate::Projection(ref poly_projection_predicate) => {
966 if poly_projection_predicate.skip_binder().ty.visit_with(self) {
969 Some(poly_projection_predicate.skip_binder()
970 .projection_ty.trait_ref(self.tcx))
972 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => None,
973 _ => bug!("unexpected predicate: {:?}", predicate),
975 if let Some(trait_ref) = trait_ref {
976 if !self.item_is_accessible(trait_ref.def_id) {
977 let msg = format!("trait `{}` is private", trait_ref);
978 self.tcx.sess.span_err(self.span, &msg);
981 for subst in trait_ref.substs.iter() {
982 // Skip repeated `Opaque`s to avoid infinite recursion.
983 if let UnpackedKind::Type(ty) = subst.unpack() {
984 if let ty::Opaque(def_id, ..) = ty.sty {
985 if !self.visited_opaque_tys.insert(def_id) {
990 if subst.visit_with(self) {
1000 ty.super_visit_with(self)
1004 ///////////////////////////////////////////////////////////////////////////////
1005 /// Obsolete visitors for checking for private items in public interfaces.
1006 /// These visitors are supposed to be kept in frozen state and produce an
1007 /// "old error node set". For backward compatibility the new visitor reports
1008 /// warnings instead of hard errors when the erroneous node is not in this old set.
1009 ///////////////////////////////////////////////////////////////////////////////
1011 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1012 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1013 access_levels: &'a AccessLevels,
1015 // set of errors produced by this obsolete visitor
1016 old_error_set: NodeSet,
1019 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1020 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1021 /// whether the type refers to private types.
1022 contains_private: bool,
1023 /// whether we've recurred at all (i.e. if we're pointing at the
1024 /// first type on which visit_ty was called).
1025 at_outer_type: bool,
1026 // whether that first type is a public path.
1027 outer_type_is_public_path: bool,
1030 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1031 fn path_is_private_type(&self, path: &hir::Path) -> bool {
1032 let did = match path.def {
1033 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => return false,
1034 def => def.def_id(),
1037 // A path can only be private if:
1038 // it's in this crate...
1039 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
1040 // .. and it corresponds to a private type in the AST (this returns
1041 // None for type parameters)
1042 match self.tcx.hir.find(node_id) {
1043 Some(Node::Item(ref item)) => !item.vis.node.is_pub(),
1044 Some(_) | None => false,
1051 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1052 // FIXME: this would preferably be using `exported_items`, but all
1053 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1054 self.access_levels.is_public(trait_id)
1057 fn check_generic_bound(&mut self, bound: &hir::GenericBound) {
1058 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1059 if self.path_is_private_type(&trait_ref.trait_ref.path) {
1060 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1065 fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
1066 self.access_levels.is_reachable(*id) || vis.node.is_pub()
1070 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1071 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1072 NestedVisitorMap::None
1075 fn visit_ty(&mut self, ty: &hir::Ty) {
1076 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = ty.node {
1077 if self.inner.path_is_private_type(path) {
1078 self.contains_private = true;
1079 // found what we're looking for so let's stop
1084 if let hir::TyKind::Path(_) = ty.node {
1085 if self.at_outer_type {
1086 self.outer_type_is_public_path = true;
1089 self.at_outer_type = false;
1090 intravisit::walk_ty(self, ty)
1093 // don't want to recurse into [, .. expr]
1094 fn visit_expr(&mut self, _: &hir::Expr) {}
1097 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1098 /// We want to visit items in the context of their containing
1099 /// module and so forth, so supply a crate for doing a deep walk.
1100 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1101 NestedVisitorMap::All(&self.tcx.hir)
1104 fn visit_item(&mut self, item: &'tcx hir::Item) {
1106 // contents of a private mod can be re-exported, so we need
1107 // to check internals.
1108 hir::ItemKind::Mod(_) => {}
1110 // An `extern {}` doesn't introduce a new privacy
1111 // namespace (the contents have their own privacies).
1112 hir::ItemKind::ForeignMod(_) => {}
1114 hir::ItemKind::Trait(.., ref bounds, _) => {
1115 if !self.trait_is_public(item.id) {
1119 for bound in bounds.iter() {
1120 self.check_generic_bound(bound)
1124 // impls need some special handling to try to offer useful
1125 // error messages without (too many) false positives
1126 // (i.e. we could just return here to not check them at
1127 // all, or some worse estimation of whether an impl is
1128 // publicly visible).
1129 hir::ItemKind::Impl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
1130 // `impl [... for] Private` is never visible.
1131 let self_contains_private;
1132 // impl [... for] Public<...>, but not `impl [... for]
1133 // Vec<Public>` or `(Public,)` etc.
1134 let self_is_public_path;
1136 // check the properties of the Self type:
1138 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1140 contains_private: false,
1141 at_outer_type: true,
1142 outer_type_is_public_path: false,
1144 visitor.visit_ty(&self_);
1145 self_contains_private = visitor.contains_private;
1146 self_is_public_path = visitor.outer_type_is_public_path;
1149 // miscellaneous info about the impl
1151 // `true` iff this is `impl Private for ...`.
1152 let not_private_trait =
1153 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1155 let did = tr.path.def.def_id();
1157 if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
1158 self.trait_is_public(node_id)
1160 true // external traits must be public
1164 // `true` iff this is a trait impl or at least one method is public.
1166 // `impl Public { $( fn ...() {} )* }` is not visible.
1168 // This is required over just using the methods' privacy
1169 // directly because we might have `impl<T: Foo<Private>> ...`,
1170 // and we shouldn't warn about the generics if all the methods
1171 // are private (because `T` won't be visible externally).
1172 let trait_or_some_public_method =
1173 trait_ref.is_some() ||
1174 impl_item_refs.iter()
1175 .any(|impl_item_ref| {
1176 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1177 match impl_item.node {
1178 hir::ImplItemKind::Const(..) |
1179 hir::ImplItemKind::Method(..) => {
1180 self.access_levels.is_reachable(impl_item.id)
1182 hir::ImplItemKind::Existential(..) |
1183 hir::ImplItemKind::Type(_) => false,
1187 if !self_contains_private &&
1188 not_private_trait &&
1189 trait_or_some_public_method {
1191 intravisit::walk_generics(self, g);
1195 for impl_item_ref in impl_item_refs {
1196 // This is where we choose whether to walk down
1197 // further into the impl to check its items. We
1198 // should only walk into public items so that we
1199 // don't erroneously report errors for private
1200 // types in private items.
1201 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1202 match impl_item.node {
1203 hir::ImplItemKind::Const(..) |
1204 hir::ImplItemKind::Method(..)
1205 if self.item_is_public(&impl_item.id, &impl_item.vis) =>
1207 intravisit::walk_impl_item(self, impl_item)
1209 hir::ImplItemKind::Type(..) => {
1210 intravisit::walk_impl_item(self, impl_item)
1217 // Any private types in a trait impl fall into three
1219 // 1. mentioned in the trait definition
1220 // 2. mentioned in the type params/generics
1221 // 3. mentioned in the associated types of the impl
1223 // Those in 1. can only occur if the trait is in
1224 // this crate and will've been warned about on the
1225 // trait definition (there's no need to warn twice
1226 // so we don't check the methods).
1228 // Those in 2. are warned via walk_generics and this
1230 intravisit::walk_path(self, &tr.path);
1232 // Those in 3. are warned with this call.
1233 for impl_item_ref in impl_item_refs {
1234 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1235 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1241 } else if trait_ref.is_none() && self_is_public_path {
1242 // impl Public<Private> { ... }. Any public static
1243 // methods will be visible as `Public::foo`.
1244 let mut found_pub_static = false;
1245 for impl_item_ref in impl_item_refs {
1246 if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
1247 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1248 match impl_item_ref.kind {
1249 hir::AssociatedItemKind::Const => {
1250 found_pub_static = true;
1251 intravisit::walk_impl_item(self, impl_item);
1253 hir::AssociatedItemKind::Method { has_self: false } => {
1254 found_pub_static = true;
1255 intravisit::walk_impl_item(self, impl_item);
1261 if found_pub_static {
1262 intravisit::walk_generics(self, g)
1268 // `type ... = ...;` can contain private types, because
1269 // we're introducing a new name.
1270 hir::ItemKind::Ty(..) => return,
1272 // not at all public, so we don't care
1273 _ if !self.item_is_public(&item.id, &item.vis) => {
1280 // We've carefully constructed it so that if we're here, then
1281 // any `visit_ty`'s will be called on things that are in
1282 // public signatures, i.e. things that we're interested in for
1284 intravisit::walk_item(self, item);
1287 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1288 for param in &generics.params {
1289 for bound in ¶m.bounds {
1290 self.check_generic_bound(bound);
1293 for predicate in &generics.where_clause.predicates {
1295 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1296 for bound in bound_pred.bounds.iter() {
1297 self.check_generic_bound(bound)
1300 &hir::WherePredicate::RegionPredicate(_) => {}
1301 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1302 self.visit_ty(&eq_pred.rhs_ty);
1308 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
1309 if self.access_levels.is_reachable(item.id) {
1310 intravisit::walk_foreign_item(self, item)
1314 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1315 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = t.node {
1316 if self.path_is_private_type(path) {
1317 self.old_error_set.insert(t.id);
1320 intravisit::walk_ty(self, t)
1323 fn visit_variant(&mut self,
1324 v: &'tcx hir::Variant,
1325 g: &'tcx hir::Generics,
1326 item_id: ast::NodeId) {
1327 if self.access_levels.is_reachable(v.node.data.id()) {
1328 self.in_variant = true;
1329 intravisit::walk_variant(self, v, g, item_id);
1330 self.in_variant = false;
1334 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
1335 if s.vis.node.is_pub() || self.in_variant {
1336 intravisit::walk_struct_field(self, s);
1340 // we don't need to introspect into these at all: an
1341 // expression/block context can't possibly contain exported things.
1342 // (Making them no-ops stops us from traversing the whole AST without
1343 // having to be super careful about our `walk_...` calls above.)
1344 fn visit_block(&mut self, _: &'tcx hir::Block) {}
1345 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1348 ///////////////////////////////////////////////////////////////////////////////
1349 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1350 /// finds any private components in it.
1351 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1352 /// and traits in public interfaces.
1353 ///////////////////////////////////////////////////////////////////////////////
1355 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1356 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1359 /// The visitor checks that each component type is at least this visible
1360 required_visibility: ty::Visibility,
1361 /// The visibility of the least visible component that has been visited
1362 min_visibility: ty::Visibility,
1363 has_pub_restricted: bool,
1364 has_old_errors: bool,
1368 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1369 fn generics(&mut self) -> &mut Self {
1370 for param in &self.tcx.generics_of(self.item_def_id).params {
1372 GenericParamDefKind::Type { has_default, .. } => {
1374 self.tcx.type_of(param.def_id).visit_with(self);
1377 GenericParamDefKind::Lifetime => {}
1383 fn predicates(&mut self) -> &mut Self {
1384 // NB: We use `explicit_predicates_of` and not `predicates_of`
1385 // because we don't want to report privacy errors due to where
1386 // clauses that the compiler inferred. We only want to
1387 // consider the ones that the user wrote. This is important
1388 // for the inferred outlives rules; see
1389 // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1390 let predicates = self.tcx.explicit_predicates_of(self.item_def_id);
1391 for (predicate, _) in &predicates.predicates {
1392 predicate.visit_with(self);
1394 &ty::Predicate::Trait(poly_predicate) => {
1395 self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
1397 &ty::Predicate::Projection(poly_predicate) => {
1399 self.check_trait_ref(
1400 poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
1409 fn ty(&mut self) -> &mut Self {
1410 let ty = self.tcx.type_of(self.item_def_id);
1411 ty.visit_with(self);
1412 if let ty::FnDef(def_id, _) = ty.sty {
1413 if def_id == self.item_def_id {
1414 self.tcx.fn_sig(def_id).visit_with(self);
1420 fn impl_trait_ref(&mut self) -> &mut Self {
1421 if let Some(impl_trait_ref) = self.tcx.impl_trait_ref(self.item_def_id) {
1422 self.check_trait_ref(impl_trait_ref);
1423 impl_trait_ref.super_visit_with(self);
1428 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
1429 // Non-local means public (private items can't leave their crate, modulo bugs)
1430 if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
1431 let item = self.tcx.hir.expect_item(node_id);
1432 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1433 if !vis.is_at_least(self.min_visibility, self.tcx) {
1434 self.min_visibility = vis;
1436 if !vis.is_at_least(self.required_visibility, self.tcx) {
1437 if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1438 struct_span_err!(self.tcx.sess, self.span, E0445,
1439 "private trait `{}` in public interface", trait_ref)
1440 .span_label(self.span, format!(
1441 "can't leak private trait"))
1444 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1447 &format!("private trait `{}` in public \
1448 interface (error E0445)", trait_ref));
1455 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1456 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
1457 let ty_def_id = match ty.sty {
1458 ty::Adt(adt, _) => Some(adt.did),
1459 ty::Foreign(did) => Some(did),
1460 ty::Dynamic(ref obj, ..) => Some(obj.principal().def_id()),
1461 ty::Projection(ref proj) => {
1462 if self.required_visibility == ty::Visibility::Invisible {
1463 // Conservatively approximate the whole type alias as public without
1464 // recursing into its components when determining impl publicity.
1465 // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
1466 // even if both `Type` and `Trait` are private.
1467 // Ideally, associated types should be substituted in the same way as
1468 // free type aliases, but this isn't done yet.
1471 let trait_ref = proj.trait_ref(self.tcx);
1472 Some(trait_ref.def_id)
1477 if let Some(def_id) = ty_def_id {
1478 // Non-local means public (private items can't leave their crate, modulo bugs)
1479 if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
1480 let hir_vis = match self.tcx.hir.find(node_id) {
1481 Some(Node::Item(item)) => &item.vis,
1482 Some(Node::ForeignItem(item)) => &item.vis,
1483 _ => bug!("expected item of foreign item"),
1486 let vis = ty::Visibility::from_hir(hir_vis, node_id, self.tcx);
1488 if !vis.is_at_least(self.min_visibility, self.tcx) {
1489 self.min_visibility = vis;
1491 if !vis.is_at_least(self.required_visibility, self.tcx) {
1492 let vis_adj = match hir_vis.node {
1493 hir::VisibilityKind::Crate(_) => "crate-visible",
1494 hir::VisibilityKind::Restricted { .. } => "restricted",
1498 if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1499 let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
1500 "{} type `{}` in public interface", vis_adj, ty);
1501 err.span_label(self.span, format!("can't leak {} type", vis_adj));
1502 err.span_label(hir_vis.span, format!("`{}` declared as {}", ty, vis_adj));
1505 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1508 &format!("{} type `{}` in public \
1509 interface (error E0446)", vis_adj, ty));
1515 ty.super_visit_with(self)
1519 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1520 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1521 has_pub_restricted: bool,
1522 old_error_set: &'a NodeSet,
1523 inner_visibility: ty::Visibility,
1526 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1527 fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1528 -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1529 let mut has_old_errors = false;
1531 // Slow path taken only if there any errors in the crate.
1532 for &id in self.old_error_set {
1533 // Walk up the nodes until we find `item_id` (or we hit a root).
1537 has_old_errors = true;
1540 let parent = self.tcx.hir.get_parent_node(id);
1552 SearchInterfaceForPrivateItemsVisitor {
1554 item_def_id: self.tcx.hir.local_def_id(item_id),
1555 span: self.tcx.hir.span(item_id),
1556 min_visibility: ty::Visibility::Public,
1557 required_visibility,
1558 has_pub_restricted: self.has_pub_restricted,
1565 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1566 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1567 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
1570 fn visit_item(&mut self, item: &'tcx hir::Item) {
1572 let min = |vis1: ty::Visibility, vis2| {
1573 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1576 let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1579 // Crates are always public
1580 hir::ItemKind::ExternCrate(..) => {}
1581 // All nested items are checked by visit_item
1582 hir::ItemKind::Mod(..) => {}
1583 // Checked in resolve
1584 hir::ItemKind::Use(..) => {}
1586 hir::ItemKind::GlobalAsm(..) => {}
1587 hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {
1588 // Check the traits being exposed, as they're separate,
1589 // e.g. `impl Iterator<Item=T>` has two predicates,
1590 // `X: Iterator` and `<X as Iterator>::Item == T`,
1591 // where `X` is the `impl Iterator<Item=T>` itself,
1592 // stored in `predicates_of`, not in the `Ty` itself.
1594 self.check(item.id, item_visibility).predicates();
1596 // Subitems of these items have inherited publicity
1597 hir::ItemKind::Const(..) | hir::ItemKind::Static(..) | hir::ItemKind::Fn(..) |
1598 hir::ItemKind::Existential(..) |
1599 hir::ItemKind::Ty(..) => {
1600 self.check(item.id, item_visibility).generics().predicates().ty();
1602 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1603 self.inner_visibility = item_visibility;
1604 intravisit::walk_item(self, item);
1606 hir::ItemKind::Trait(.., ref trait_item_refs) => {
1607 self.check(item.id, item_visibility).generics().predicates();
1609 for trait_item_ref in trait_item_refs {
1610 let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1611 check.in_assoc_ty = trait_item_ref.kind == hir::AssociatedItemKind::Type;
1612 check.generics().predicates();
1614 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1615 !trait_item_ref.defaultness.has_value() {
1616 // No type to visit.
1622 hir::ItemKind::TraitAlias(..) => {
1623 self.check(item.id, item_visibility).generics().predicates();
1625 hir::ItemKind::Enum(ref def, _) => {
1626 self.check(item.id, item_visibility).generics().predicates();
1628 for variant in &def.variants {
1629 for field in variant.node.data.fields() {
1630 self.check(field.id, item_visibility).ty();
1634 // Subitems of foreign modules have their own publicity
1635 hir::ItemKind::ForeignMod(ref foreign_mod) => {
1636 for foreign_item in &foreign_mod.items {
1637 let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1638 self.check(foreign_item.id, vis).generics().predicates().ty();
1641 // Subitems of structs and unions have their own publicity
1642 hir::ItemKind::Struct(ref struct_def, _) |
1643 hir::ItemKind::Union(ref struct_def, _) => {
1644 self.check(item.id, item_visibility).generics().predicates();
1646 for field in struct_def.fields() {
1647 let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1648 self.check(field.id, min(item_visibility, field_visibility)).ty();
1651 // An inherent impl is public when its type is public
1652 // Subitems of inherent impls have their own publicity
1653 hir::ItemKind::Impl(.., None, _, ref impl_item_refs) => {
1655 self.check(item.id, ty::Visibility::Invisible).ty().min_visibility;
1656 self.check(item.id, ty_vis).generics().predicates();
1658 for impl_item_ref in impl_item_refs {
1659 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1660 let impl_item_vis = ty::Visibility::from_hir(&impl_item.vis, item.id, tcx);
1661 let mut check = self.check(impl_item.id, min(impl_item_vis, ty_vis));
1662 check.in_assoc_ty = impl_item_ref.kind == hir::AssociatedItemKind::Type;
1663 check.generics().predicates().ty();
1665 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1666 self.inner_visibility = impl_item_vis;
1667 intravisit::walk_impl_item(self, impl_item);
1670 // A trait impl is public when both its type and its trait are public
1671 // Subitems of trait impls have inherited publicity
1672 hir::ItemKind::Impl(.., Some(_), _, ref impl_item_refs) => {
1673 let vis = self.check(item.id, ty::Visibility::Invisible)
1674 .ty().impl_trait_ref().min_visibility;
1675 self.check(item.id, vis).generics().predicates();
1676 for impl_item_ref in impl_item_refs {
1677 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1678 let mut check = self.check(impl_item.id, vis);
1679 check.in_assoc_ty = impl_item_ref.kind == hir::AssociatedItemKind::Type;
1680 check.generics().predicates().ty();
1682 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1683 self.inner_visibility = vis;
1684 intravisit::walk_impl_item(self, impl_item);
1690 fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
1691 // handled in `visit_item` above
1694 // Don't recurse into expressions in array sizes or const initializers
1695 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1696 // Don't recurse into patterns in function arguments
1697 fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
1700 pub fn provide(providers: &mut Providers) {
1701 *providers = Providers {
1702 privacy_access_levels,
1707 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Lrc<AccessLevels> {
1708 tcx.privacy_access_levels(LOCAL_CRATE)
1711 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1713 -> Lrc<AccessLevels> {
1714 assert_eq!(krate, LOCAL_CRATE);
1716 let krate = tcx.hir.krate();
1717 let empty_tables = ty::TypeckTables::empty(None);
1719 // Check privacy of names not checked in previous compilation stages.
1720 let mut visitor = NamePrivacyVisitor {
1722 tables: &empty_tables,
1723 current_item: CRATE_NODE_ID,
1724 empty_tables: &empty_tables,
1726 intravisit::walk_crate(&mut visitor, krate);
1728 // Check privacy of explicitly written types and traits as well as
1729 // inferred types of expressions and patterns.
1730 let mut visitor = TypePrivacyVisitor {
1732 tables: &empty_tables,
1733 current_item: DefId::local(CRATE_DEF_INDEX),
1736 empty_tables: &empty_tables,
1737 visited_opaque_tys: FxHashSet::default()
1739 intravisit::walk_crate(&mut visitor, krate);
1741 // Build up a set of all exported items in the AST. This is a set of all
1742 // items which are reachable from external crates based on visibility.
1743 let mut visitor = EmbargoVisitor {
1745 access_levels: Default::default(),
1746 prev_level: Some(AccessLevel::Public),
1750 intravisit::walk_crate(&mut visitor, krate);
1751 if visitor.changed {
1752 visitor.changed = false;
1757 visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1760 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1762 access_levels: &visitor.access_levels,
1764 old_error_set: Default::default(),
1766 intravisit::walk_crate(&mut visitor, krate);
1769 let has_pub_restricted = {
1770 let mut pub_restricted_visitor = PubRestrictedVisitor {
1772 has_pub_restricted: false
1774 intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1775 pub_restricted_visitor.has_pub_restricted
1778 // Check for private types and traits in public interfaces
1779 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1782 old_error_set: &visitor.old_error_set,
1783 inner_visibility: ty::Visibility::Public,
1785 krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1788 Lrc::new(visitor.access_levels)
1791 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }