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, Node, PatKind};
27 use rustc::hir::def::Def;
28 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
29 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
30 use rustc::hir::itemlikevisit::DeepVisitor;
32 use rustc::middle::privacy::{AccessLevel, AccessLevels};
33 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable, GenericParamDefKind};
34 use rustc::ty::fold::TypeVisitor;
35 use rustc::ty::query::Providers;
36 use rustc::ty::subst::UnpackedKind;
37 use rustc::util::nodemap::NodeSet;
38 use rustc_data_structures::fx::FxHashSet;
39 use rustc_data_structures::sync::Lrc;
40 use syntax::ast::{self, CRATE_NODE_ID, Ident};
41 use syntax::symbol::keywords;
45 use std::mem::replace;
49 ////////////////////////////////////////////////////////////////////////////////
50 /// Visitor used to determine if pub(restricted) is used anywhere in the crate.
52 /// This is done so that `private_in_public` warnings can be turned into hard errors
53 /// in crates that have been updated to use pub(restricted).
54 ////////////////////////////////////////////////////////////////////////////////
55 struct PubRestrictedVisitor<'a, 'tcx: 'a> {
56 tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 has_pub_restricted: bool,
60 impl<'a, 'tcx> Visitor<'tcx> for PubRestrictedVisitor<'a, 'tcx> {
61 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
62 NestedVisitorMap::All(&self.tcx.hir())
64 fn visit_vis(&mut self, vis: &'tcx hir::Visibility) {
65 self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted();
69 ////////////////////////////////////////////////////////////////////////////////
70 /// The embargo visitor, used to determine the exports of the ast
71 ////////////////////////////////////////////////////////////////////////////////
73 struct EmbargoVisitor<'a, 'tcx: 'a> {
74 tcx: TyCtxt<'a, 'tcx, 'tcx>,
76 // Accessibility levels for reachable nodes.
77 access_levels: AccessLevels,
78 // Previous accessibility level; `None` means unreachable.
79 prev_level: Option<AccessLevel>,
80 // Has something changed in the level map?
84 struct ReachEverythingInTheInterfaceVisitor<'b, 'a: 'b, 'tcx: 'a> {
85 access_level: Option<AccessLevel>,
87 ev: &'b mut EmbargoVisitor<'a, 'tcx>,
90 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
91 fn item_ty_level(&self, item_def_id: DefId) -> Option<AccessLevel> {
92 let ty_def_id = match self.tcx.type_of(item_def_id).sty {
93 ty::Adt(adt, _) => adt.did,
94 ty::Foreign(did) => did,
95 ty::Dynamic(ref obj, ..) => obj.principal().def_id(),
96 ty::Projection(ref proj) => proj.trait_ref(self.tcx).def_id,
97 _ => return Some(AccessLevel::Public)
99 if let Some(node_id) = self.tcx.hir().as_local_node_id(ty_def_id) {
102 Some(AccessLevel::Public)
106 fn impl_trait_level(&self, impl_def_id: DefId) -> Option<AccessLevel> {
107 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_def_id) {
108 if let Some(node_id) = self.tcx.hir().as_local_node_id(trait_ref.def_id) {
109 return self.get(node_id);
112 Some(AccessLevel::Public)
115 fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
116 self.access_levels.map.get(&id).cloned()
119 // Updates node level and returns the updated level.
120 fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
121 let old_level = self.get(id);
122 // Accessibility levels can only grow.
123 if level > old_level {
124 self.access_levels.map.insert(id, level.unwrap());
132 fn reach<'b>(&'b mut self, item_id: ast::NodeId)
133 -> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
134 ReachEverythingInTheInterfaceVisitor {
135 access_level: self.prev_level.map(|l| l.min(AccessLevel::Reachable)),
136 item_def_id: self.tcx.hir().local_def_id(item_id),
142 impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> {
143 /// We want to visit items in the context of their containing
144 /// module and so forth, so supply a crate for doing a deep walk.
145 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
146 NestedVisitorMap::All(&self.tcx.hir())
149 fn visit_item(&mut self, item: &'tcx hir::Item) {
150 let inherited_item_level = match item.node {
151 // Impls inherit level from their types and traits.
152 hir::ItemKind::Impl(..) => {
153 let def_id = self.tcx.hir().local_def_id(item.id);
154 cmp::min(self.item_ty_level(def_id), self.impl_trait_level(def_id))
156 // Foreign modules inherit level from parents.
157 hir::ItemKind::ForeignMod(..) => {
160 // Other `pub` items inherit levels from parents.
161 hir::ItemKind::Const(..) | hir::ItemKind::Enum(..) | hir::ItemKind::ExternCrate(..) |
162 hir::ItemKind::GlobalAsm(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) |
163 hir::ItemKind::Static(..) | hir::ItemKind::Struct(..) |
164 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) |
165 hir::ItemKind::Existential(..) |
166 hir::ItemKind::Ty(..) | hir::ItemKind::Union(..) | hir::ItemKind::Use(..) => {
167 if item.vis.node.is_pub() { self.prev_level } else { None }
171 // Update level of the item itself.
172 let item_level = self.update(item.id, inherited_item_level);
174 // Update levels of nested things.
176 hir::ItemKind::Enum(ref def, _) => {
177 for variant in &def.variants {
178 let variant_level = self.update(variant.node.data.id(), item_level);
179 for field in variant.node.data.fields() {
180 self.update(field.id, variant_level);
184 hir::ItemKind::Impl(.., None, _, ref impl_item_refs) => {
185 for impl_item_ref in impl_item_refs {
186 if impl_item_ref.vis.node.is_pub() {
187 self.update(impl_item_ref.id.node_id, item_level);
191 hir::ItemKind::Impl(.., Some(_), _, ref impl_item_refs) => {
192 for impl_item_ref in impl_item_refs {
193 self.update(impl_item_ref.id.node_id, item_level);
196 hir::ItemKind::Trait(.., ref trait_item_refs) => {
197 for trait_item_ref in trait_item_refs {
198 self.update(trait_item_ref.id.node_id, item_level);
201 hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
202 if !def.is_struct() {
203 self.update(def.id(), item_level);
205 for field in def.fields() {
206 if field.vis.node.is_pub() {
207 self.update(field.id, item_level);
211 hir::ItemKind::ForeignMod(ref foreign_mod) => {
212 for foreign_item in &foreign_mod.items {
213 if foreign_item.vis.node.is_pub() {
214 self.update(foreign_item.id, item_level);
218 // Impl trait return types mark their parent function.
219 // It (and its children) are revisited if the change applies.
220 hir::ItemKind::Existential(ref ty_data) => {
221 if let Some(impl_trait_fn) = ty_data.impl_trait_fn {
222 if let Some(node_id) = self.tcx.hir().as_local_node_id(impl_trait_fn) {
223 self.update(node_id, Some(AccessLevel::ReachableFromImplTrait));
227 hir::ItemKind::Use(..) |
228 hir::ItemKind::Static(..) |
229 hir::ItemKind::Const(..) |
230 hir::ItemKind::GlobalAsm(..) |
231 hir::ItemKind::Ty(..) |
232 hir::ItemKind::Mod(..) |
233 hir::ItemKind::TraitAlias(..) |
234 hir::ItemKind::Fn(..) |
235 hir::ItemKind::ExternCrate(..) => {}
238 // Store this node's access level here to propagate the correct
239 // reachability level through interfaces and children.
240 let orig_level = replace(&mut self.prev_level, item_level);
242 // Mark all items in interfaces of reachable items as reachable.
244 // The interface is empty.
245 hir::ItemKind::ExternCrate(..) => {}
246 // All nested items are checked by `visit_item`.
247 hir::ItemKind::Mod(..) => {}
248 // Re-exports are handled in `visit_mod`.
249 hir::ItemKind::Use(..) => {}
250 // The interface is empty.
251 hir::ItemKind::GlobalAsm(..) => {}
252 hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {
253 if item_level.is_some() {
254 // Reach the (potentially private) type and the API being exposed.
255 self.reach(item.id).ty().predicates();
259 hir::ItemKind::Const(..) | hir::ItemKind::Static(..) |
260 hir::ItemKind::Existential(..) |
261 hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) => {
262 if item_level.is_some() {
263 self.reach(item.id).generics().predicates().ty();
266 hir::ItemKind::Trait(.., ref trait_item_refs) => {
267 if item_level.is_some() {
268 self.reach(item.id).generics().predicates();
270 for trait_item_ref in trait_item_refs {
271 let mut reach = self.reach(trait_item_ref.id.node_id);
272 reach.generics().predicates();
274 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
275 !trait_item_ref.defaultness.has_value() {
283 hir::ItemKind::TraitAlias(..) => {
284 if item_level.is_some() {
285 self.reach(item.id).generics().predicates();
288 // Visit everything except for private impl items.
289 hir::ItemKind::Impl(.., ref trait_ref, _, ref impl_item_refs) => {
290 if item_level.is_some() {
291 self.reach(item.id).generics().predicates().impl_trait_ref();
293 for impl_item_ref in impl_item_refs {
294 let id = impl_item_ref.id.node_id;
295 if trait_ref.is_some() || self.get(id).is_some() {
296 self.reach(id).generics().predicates().ty();
302 // Visit everything, but enum variants have their own levels.
303 hir::ItemKind::Enum(ref def, _) => {
304 if item_level.is_some() {
305 self.reach(item.id).generics().predicates();
307 for variant in &def.variants {
308 if self.get(variant.node.data.id()).is_some() {
309 for field in variant.node.data.fields() {
310 self.reach(field.id).ty();
312 // Corner case: if the variant is reachable, but its
313 // enum is not, make the enum reachable as well.
314 self.update(item.id, Some(AccessLevel::Reachable));
318 // Visit everything, but foreign items have their own levels.
319 hir::ItemKind::ForeignMod(ref foreign_mod) => {
320 for foreign_item in &foreign_mod.items {
321 if self.get(foreign_item.id).is_some() {
322 self.reach(foreign_item.id).generics().predicates().ty();
326 // Visit everything except for private fields.
327 hir::ItemKind::Struct(ref struct_def, _) |
328 hir::ItemKind::Union(ref struct_def, _) => {
329 if item_level.is_some() {
330 self.reach(item.id).generics().predicates();
331 for field in struct_def.fields() {
332 if self.get(field.id).is_some() {
333 self.reach(field.id).ty();
340 intravisit::walk_item(self, item);
342 self.prev_level = orig_level;
345 fn visit_block(&mut self, b: &'tcx hir::Block) {
346 let orig_level = replace(&mut self.prev_level, None);
348 // Blocks can have public items, for example impls, but they always
349 // start as completely private regardless of publicity of a function,
350 // constant, type, field, etc., in which this block resides.
351 intravisit::walk_block(self, b);
353 self.prev_level = orig_level;
356 fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
357 // This code is here instead of in visit_item so that the
358 // crate module gets processed as well.
359 if self.prev_level.is_some() {
360 let def_id = self.tcx.hir().local_def_id(id);
361 if let Some(exports) = self.tcx.module_exports(def_id) {
362 for export in exports.iter() {
363 if export.vis == ty::Visibility::Public {
364 if let Some(def_id) = export.def.opt_def_id() {
365 if let Some(node_id) = self.tcx.hir().as_local_node_id(def_id) {
366 self.update(node_id, Some(AccessLevel::Exported));
374 intravisit::walk_mod(self, m, id);
377 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
379 self.update(md.id, Some(AccessLevel::Public));
383 let module_did = ty::DefIdTree::parent(
385 self.tcx.hir().local_def_id(md.id)
387 let mut module_id = self.tcx.hir().as_local_node_id(module_did).unwrap();
388 let level = if md.vis.node.is_pub() { self.get(module_id) } else { None };
389 let level = self.update(md.id, level);
395 let module = if module_id == ast::CRATE_NODE_ID {
396 &self.tcx.hir().krate().module
397 } else if let hir::ItemKind::Mod(ref module) =
398 self.tcx.hir().expect_item(module_id).node {
403 for id in &module.item_ids {
404 self.update(id.id, level);
406 let def_id = self.tcx.hir().local_def_id(module_id);
407 if let Some(exports) = self.tcx.module_exports(def_id) {
408 for export in exports.iter() {
409 if let Some(node_id) = self.tcx.hir().as_local_node_id(export.def.def_id()) {
410 self.update(node_id, level);
415 if module_id == ast::CRATE_NODE_ID {
418 module_id = self.tcx.hir().get_parent_node(module_id);
423 impl<'b, 'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
424 fn generics(&mut self) -> &mut Self {
425 for param in &self.ev.tcx.generics_of(self.item_def_id).params {
427 GenericParamDefKind::Type { has_default, .. } => {
429 self.ev.tcx.type_of(param.def_id).visit_with(self);
432 GenericParamDefKind::Lifetime => {}
438 fn predicates(&mut self) -> &mut Self {
439 let predicates = self.ev.tcx.predicates_of(self.item_def_id);
440 for (predicate, _) in &predicates.predicates {
441 predicate.visit_with(self);
443 &ty::Predicate::Trait(poly_predicate) => {
444 self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
446 &ty::Predicate::Projection(poly_predicate) => {
447 let tcx = self.ev.tcx;
448 self.check_trait_ref(
449 poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
458 fn ty(&mut self) -> &mut Self {
459 let ty = self.ev.tcx.type_of(self.item_def_id);
461 if let ty::FnDef(def_id, _) = ty.sty {
462 if def_id == self.item_def_id {
463 self.ev.tcx.fn_sig(def_id).visit_with(self);
469 fn impl_trait_ref(&mut self) -> &mut Self {
470 if let Some(impl_trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
471 self.check_trait_ref(impl_trait_ref);
472 impl_trait_ref.super_visit_with(self);
477 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
478 if let Some(node_id) = self.ev.tcx.hir().as_local_node_id(trait_ref.def_id) {
479 let item = self.ev.tcx.hir().expect_item(node_id);
480 self.ev.update(item.id, self.access_level);
485 impl<'b, 'a, 'tcx> TypeVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
486 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
487 let ty_def_id = match ty.sty {
488 ty::Adt(adt, _) => Some(adt.did),
489 ty::Foreign(did) => Some(did),
490 ty::Dynamic(ref obj, ..) => Some(obj.principal().def_id()),
491 ty::Projection(ref proj) => Some(proj.item_def_id),
492 ty::FnDef(def_id, ..) |
493 ty::Closure(def_id, ..) |
494 ty::Generator(def_id, ..) |
495 ty::Opaque(def_id, _) => Some(def_id),
499 if let Some(def_id) = ty_def_id {
500 if let Some(node_id) = self.ev.tcx.hir().as_local_node_id(def_id) {
501 self.ev.update(node_id, self.access_level);
505 ty.super_visit_with(self)
509 //////////////////////////////////////////////////////////////////////////////////////
510 /// Name privacy visitor, checks privacy and reports violations.
511 /// Most of name privacy checks are performed during the main resolution phase,
512 /// or later in type checking when field accesses and associated items are resolved.
513 /// This pass performs remaining checks for fields in struct expressions and patterns.
514 //////////////////////////////////////////////////////////////////////////////////////
516 struct NamePrivacyVisitor<'a, 'tcx: 'a> {
517 tcx: TyCtxt<'a, 'tcx, 'tcx>,
518 tables: &'a ty::TypeckTables<'tcx>,
519 current_item: ast::NodeId,
520 empty_tables: &'a ty::TypeckTables<'tcx>,
523 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
524 // Checks that a field in a struct constructor (expression or pattern) is accessible.
525 fn check_field(&mut self,
526 use_ctxt: Span, // syntax context of the field name at the use site
527 span: Span, // span of the field pattern, e.g., `x: 0`
528 def: &'tcx ty::AdtDef, // definition of the struct or enum
529 field: &'tcx ty::FieldDef) { // definition of the field
530 let ident = Ident::new(keywords::Invalid.name(), use_ctxt);
531 let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
532 if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
533 struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
534 field.ident, def.variant_descr(), self.tcx.item_path_str(def.did))
535 .span_label(span, format!("field `{}` is private", field.ident))
541 // Set the correct `TypeckTables` for the given `item_id` (or an empty table if
542 // there is no `TypeckTables` for the item).
543 fn update_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
544 item_id: ast::NodeId,
545 tables: &mut &'a ty::TypeckTables<'tcx>,
546 empty_tables: &'a ty::TypeckTables<'tcx>)
547 -> &'a ty::TypeckTables<'tcx> {
548 let def_id = tcx.hir().local_def_id(item_id);
550 if tcx.has_typeck_tables(def_id) {
551 replace(tables, tcx.typeck_tables_of(def_id))
553 replace(tables, empty_tables)
557 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
558 /// We want to visit items in the context of their containing
559 /// module and so forth, so supply a crate for doing a deep walk.
560 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
561 NestedVisitorMap::All(&self.tcx.hir())
564 fn visit_nested_body(&mut self, body: hir::BodyId) {
565 let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
566 let body = self.tcx.hir().body(body);
567 self.visit_body(body);
568 self.tables = orig_tables;
571 fn visit_item(&mut self, item: &'tcx hir::Item) {
572 let orig_current_item = replace(&mut self.current_item, item.id);
573 let orig_tables = update_tables(self.tcx, item.id, &mut self.tables, self.empty_tables);
574 intravisit::walk_item(self, item);
575 self.current_item = orig_current_item;
576 self.tables = orig_tables;
579 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
580 let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
581 intravisit::walk_trait_item(self, ti);
582 self.tables = orig_tables;
585 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
586 let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
587 intravisit::walk_impl_item(self, ii);
588 self.tables = orig_tables;
591 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
593 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
594 let def = self.tables.qpath_def(qpath, expr.hir_id);
595 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
596 let variant = adt.variant_of_def(def);
597 if let Some(ref base) = *base {
598 // If the expression uses FRU we need to make sure all the unmentioned fields
599 // are checked for privacy (RFC 736). Rather than computing the set of
600 // unmentioned fields, just check them all.
601 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
602 let field = fields.iter().find(|f| {
603 self.tcx.field_index(f.id, self.tables) == vf_index
605 let (use_ctxt, span) = match field {
606 Some(field) => (field.ident.span, field.span),
607 None => (base.span, base.span),
609 self.check_field(use_ctxt, span, adt, variant_field);
612 for field in fields {
613 let use_ctxt = field.ident.span;
614 let index = self.tcx.field_index(field.id, self.tables);
615 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
622 intravisit::walk_expr(self, expr);
625 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
627 PatKind::Struct(ref qpath, ref fields, _) => {
628 let def = self.tables.qpath_def(qpath, pat.hir_id);
629 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
630 let variant = adt.variant_of_def(def);
631 for field in fields {
632 let use_ctxt = field.node.ident.span;
633 let index = self.tcx.field_index(field.node.id, self.tables);
634 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
640 intravisit::walk_pat(self, pat);
644 ////////////////////////////////////////////////////////////////////////////////////////////
645 /// Type privacy visitor, checks types for privacy and reports violations.
646 /// Both explicitly written types and inferred types of expressions and patters are checked.
647 /// Checks are performed on "semantic" types regardless of names and their hygiene.
648 ////////////////////////////////////////////////////////////////////////////////////////////
650 struct TypePrivacyVisitor<'a, 'tcx: 'a> {
651 tcx: TyCtxt<'a, 'tcx, 'tcx>,
652 tables: &'a ty::TypeckTables<'tcx>,
656 empty_tables: &'a ty::TypeckTables<'tcx>,
657 visited_opaque_tys: FxHashSet<DefId>
660 impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
661 fn def_id_visibility(&self, did: DefId) -> ty::Visibility {
662 match self.tcx.hir().as_local_node_id(did) {
664 let vis = match self.tcx.hir().get(node_id) {
665 Node::Item(item) => &item.vis,
666 Node::ForeignItem(foreign_item) => &foreign_item.vis,
667 Node::ImplItem(impl_item) => &impl_item.vis,
668 Node::TraitItem(..) |
669 Node::Variant(..) => {
670 return self.def_id_visibility(self.tcx.hir().get_parent_did(node_id));
672 Node::StructCtor(vdata) => {
673 let struct_node_id = self.tcx.hir().get_parent(node_id);
674 let struct_vis = match self.tcx.hir().get(struct_node_id) {
675 Node::Item(item) => &item.vis,
676 node => bug!("unexpected node kind: {:?}", node),
679 = ty::Visibility::from_hir(struct_vis, struct_node_id, self.tcx);
680 for field in vdata.fields() {
681 let field_vis = ty::Visibility::from_hir(&field.vis, node_id, self.tcx);
682 if ctor_vis.is_at_least(field_vis, self.tcx) {
683 ctor_vis = field_vis;
687 // If the structure is marked as non_exhaustive then lower the
688 // visibility to within the crate.
689 let struct_def_id = self.tcx.hir().get_parent_did(node_id);
690 let adt_def = self.tcx.adt_def(struct_def_id);
691 if adt_def.non_enum_variant().is_field_list_non_exhaustive()
692 && ctor_vis == ty::Visibility::Public
694 ctor_vis = ty::Visibility::Restricted(
695 DefId::local(CRATE_DEF_INDEX));
700 node => bug!("unexpected node kind: {:?}", node)
702 ty::Visibility::from_hir(vis, node_id, self.tcx)
704 None => self.tcx.visibility(did),
708 fn item_is_accessible(&self, did: DefId) -> bool {
709 self.def_id_visibility(did).is_accessible_from(self.current_item, self.tcx)
712 // Take node-id of an expression or pattern and check its type for privacy.
713 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
715 if self.tables.node_id_to_type(id).visit_with(self) {
718 if self.tables.node_substs(id).visit_with(self) {
721 if let Some(adjustments) = self.tables.adjustments().get(id) {
722 for adjustment in adjustments {
723 if adjustment.target.visit_with(self) {
731 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
732 if !self.item_is_accessible(trait_ref.def_id) {
733 let msg = format!("trait `{}` is private", trait_ref);
734 self.tcx.sess.span_err(self.span, &msg);
738 trait_ref.super_visit_with(self)
742 impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
743 /// We want to visit items in the context of their containing
744 /// module and so forth, so supply a crate for doing a deep walk.
745 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
746 NestedVisitorMap::All(&self.tcx.hir())
749 fn visit_nested_body(&mut self, body: hir::BodyId) {
750 let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
751 let orig_in_body = replace(&mut self.in_body, true);
752 let body = self.tcx.hir().body(body);
753 self.visit_body(body);
754 self.tables = orig_tables;
755 self.in_body = orig_in_body;
758 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty) {
759 self.span = hir_ty.span;
762 if self.tables.node_id_to_type(hir_ty.hir_id).visit_with(self) {
766 // Types in signatures.
767 // FIXME: This is very ineffective. Ideally each HIR type should be converted
768 // into a semantic type only once and the result should be cached somehow.
769 if rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty).visit_with(self) {
774 intravisit::walk_ty(self, hir_ty);
777 fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef) {
778 self.span = trait_ref.path.span;
780 // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
781 // The traits' privacy in bodies is already checked as a part of trait object types.
782 let (principal, projections) =
783 rustc_typeck::hir_trait_to_predicates(self.tcx, trait_ref);
784 if self.check_trait_ref(*principal.skip_binder()) {
787 for (poly_predicate, _) in projections {
789 if self.check_trait_ref(poly_predicate.skip_binder().projection_ty.trait_ref(tcx)) {
795 intravisit::walk_trait_ref(self, trait_ref);
798 // Check types of expressions
799 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
800 if self.check_expr_pat_type(expr.hir_id, expr.span) {
801 // Do not check nested expressions if the error already happened.
805 hir::ExprKind::Assign(.., ref rhs) | hir::ExprKind::Match(ref rhs, ..) => {
806 // Do not report duplicate errors for `x = y` and `match x { ... }`.
807 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
811 hir::ExprKind::MethodCall(_, span, _) => {
812 // Method calls have to be checked specially.
814 if let Some(def) = self.tables.type_dependent_defs().get(expr.hir_id) {
815 let def_id = def.def_id();
816 if self.tcx.type_of(def_id).visit_with(self) {
820 self.tcx.sess.delay_span_bug(expr.span,
821 "no type-dependent def for method call");
827 intravisit::walk_expr(self, expr);
830 // Prohibit access to associated items with insufficient nominal visibility.
832 // Additionally, until better reachability analysis for macros 2.0 is available,
833 // we prohibit access to private statics from other crates, this allows to give
834 // more code internal visibility at link time. (Access to private functions
835 // is already prohibited by type privacy for function types.)
836 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: hir::HirId, span: Span) {
837 let def = match *qpath {
838 hir::QPath::Resolved(_, ref path) => match path.def {
839 Def::Method(..) | Def::AssociatedConst(..) |
840 Def::AssociatedTy(..) | Def::Static(..) => Some(path.def),
843 hir::QPath::TypeRelative(..) => {
844 self.tables.type_dependent_defs().get(id).cloned()
847 if let Some(def) = def {
848 let def_id = def.def_id();
849 let is_local_static = if let Def::Static(..) = def { def_id.is_local() } else { false };
850 if !self.item_is_accessible(def_id) && !is_local_static {
851 let name = match *qpath {
852 hir::QPath::Resolved(_, ref path) => path.to_string(),
853 hir::QPath::TypeRelative(_, ref segment) => segment.ident.to_string(),
855 let msg = format!("{} `{}` is private", def.kind_name(), name);
856 self.tcx.sess.span_err(span, &msg);
861 intravisit::walk_qpath(self, qpath, id, span);
864 // Check types of patterns.
865 fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
866 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
867 // Do not check nested patterns if the error already happened.
871 intravisit::walk_pat(self, pattern);
874 fn visit_local(&mut self, local: &'tcx hir::Local) {
875 if let Some(ref init) = local.init {
876 if self.check_expr_pat_type(init.hir_id, init.span) {
877 // Do not report duplicate errors for `let x = y`.
882 intravisit::walk_local(self, local);
885 // Check types in item interfaces.
886 fn visit_item(&mut self, item: &'tcx hir::Item) {
887 let orig_current_item = self.current_item;
888 let orig_tables = update_tables(self.tcx,
892 let orig_in_body = replace(&mut self.in_body, false);
893 self.current_item = self.tcx.hir().local_def_id(item.id);
894 intravisit::walk_item(self, item);
895 self.tables = orig_tables;
896 self.in_body = orig_in_body;
897 self.current_item = orig_current_item;
900 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
901 let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
902 intravisit::walk_trait_item(self, ti);
903 self.tables = orig_tables;
906 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
907 let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
908 intravisit::walk_impl_item(self, ii);
909 self.tables = orig_tables;
913 impl<'a, 'tcx> TypeVisitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
914 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
916 ty::Adt(&ty::AdtDef { did: def_id, .. }, ..) |
917 ty::FnDef(def_id, ..) |
918 ty::Foreign(def_id) => {
919 if !self.item_is_accessible(def_id) {
920 let msg = format!("type `{}` is private", ty);
921 self.tcx.sess.span_err(self.span, &msg);
924 if let ty::FnDef(..) = ty.sty {
925 if self.tcx.fn_sig(def_id).visit_with(self) {
929 // Inherent static methods don't have self type in substs,
930 // we have to check it additionally.
931 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
932 if let ty::ImplContainer(impl_def_id) = assoc_item.container {
933 if self.tcx.type_of(impl_def_id).visit_with(self) {
939 ty::Dynamic(ref predicates, ..) => {
940 let is_private = predicates.skip_binder().iter().any(|predicate| {
941 let def_id = match *predicate {
942 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref.def_id,
943 ty::ExistentialPredicate::Projection(proj) =>
944 proj.trait_ref(self.tcx).def_id,
945 ty::ExistentialPredicate::AutoTrait(def_id) => def_id,
947 !self.item_is_accessible(def_id)
950 let msg = format!("type `{}` is private", ty);
951 self.tcx.sess.span_err(self.span, &msg);
955 ty::Projection(ref proj) => {
957 if self.check_trait_ref(proj.trait_ref(tcx)) {
961 ty::Opaque(def_id, ..) => {
962 for (predicate, _) in &self.tcx.predicates_of(def_id).predicates {
963 let trait_ref = match *predicate {
964 ty::Predicate::Trait(ref poly_trait_predicate) => {
965 Some(poly_trait_predicate.skip_binder().trait_ref)
967 ty::Predicate::Projection(ref poly_projection_predicate) => {
968 if poly_projection_predicate.skip_binder().ty.visit_with(self) {
971 Some(poly_projection_predicate.skip_binder()
972 .projection_ty.trait_ref(self.tcx))
974 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => None,
975 _ => bug!("unexpected predicate: {:?}", predicate),
977 if let Some(trait_ref) = trait_ref {
978 if !self.item_is_accessible(trait_ref.def_id) {
979 let msg = format!("trait `{}` is private", trait_ref);
980 self.tcx.sess.span_err(self.span, &msg);
983 for subst in trait_ref.substs.iter() {
984 // Skip repeated `Opaque`s to avoid infinite recursion.
985 if let UnpackedKind::Type(ty) = subst.unpack() {
986 if let ty::Opaque(def_id, ..) = ty.sty {
987 if !self.visited_opaque_tys.insert(def_id) {
992 if subst.visit_with(self) {
1002 ty.super_visit_with(self)
1006 ///////////////////////////////////////////////////////////////////////////////
1007 /// Obsolete visitors for checking for private items in public interfaces.
1008 /// These visitors are supposed to be kept in frozen state and produce an
1009 /// "old error node set". For backward compatibility the new visitor reports
1010 /// warnings instead of hard errors when the erroneous node is not in this old set.
1011 ///////////////////////////////////////////////////////////////////////////////
1013 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1014 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1015 access_levels: &'a AccessLevels,
1017 // Set of errors produced by this obsolete visitor.
1018 old_error_set: NodeSet,
1021 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1022 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1023 /// Whether the type refers to private types.
1024 contains_private: bool,
1025 /// Whether we've recurred at all (i.e., if we're pointing at the
1026 /// first type on which `visit_ty` was called).
1027 at_outer_type: bool,
1028 /// Whether that first type is a public path.
1029 outer_type_is_public_path: bool,
1032 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1033 fn path_is_private_type(&self, path: &hir::Path) -> bool {
1034 let did = match path.def {
1035 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => return false,
1036 def => def.def_id(),
1039 // A path can only be private if:
1040 // it's in this crate...
1041 if let Some(node_id) = self.tcx.hir().as_local_node_id(did) {
1042 // .. and it corresponds to a private type in the AST (this returns
1043 // `None` for type parameters).
1044 match self.tcx.hir().find(node_id) {
1045 Some(Node::Item(ref item)) => !item.vis.node.is_pub(),
1046 Some(_) | None => false,
1053 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1054 // FIXME: this would preferably be using `exported_items`, but all
1055 // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1056 self.access_levels.is_public(trait_id)
1059 fn check_generic_bound(&mut self, bound: &hir::GenericBound) {
1060 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1061 if self.path_is_private_type(&trait_ref.trait_ref.path) {
1062 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1067 fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
1068 self.access_levels.is_reachable(*id) || vis.node.is_pub()
1072 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1073 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1074 NestedVisitorMap::None
1077 fn visit_ty(&mut self, ty: &hir::Ty) {
1078 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = ty.node {
1079 if self.inner.path_is_private_type(path) {
1080 self.contains_private = true;
1081 // Found what we're looking for, so let's stop working.
1085 if let hir::TyKind::Path(_) = ty.node {
1086 if self.at_outer_type {
1087 self.outer_type_is_public_path = true;
1090 self.at_outer_type = false;
1091 intravisit::walk_ty(self, ty)
1094 // Don't want to recurse into `[, .. expr]`.
1095 fn visit_expr(&mut self, _: &hir::Expr) {}
1098 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1099 /// We want to visit items in the context of their containing
1100 /// module and so forth, so supply a crate for doing a deep walk.
1101 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1102 NestedVisitorMap::All(&self.tcx.hir())
1105 fn visit_item(&mut self, item: &'tcx hir::Item) {
1107 // Contents of a private mod can be re-exported, so we need
1108 // to check internals.
1109 hir::ItemKind::Mod(_) => {}
1111 // An `extern {}` doesn't introduce a new privacy
1112 // namespace (the contents have their own privacies).
1113 hir::ItemKind::ForeignMod(_) => {}
1115 hir::ItemKind::Trait(.., ref bounds, _) => {
1116 if !self.trait_is_public(item.id) {
1120 for bound in bounds.iter() {
1121 self.check_generic_bound(bound)
1125 // Impls need some special handling to try to offer useful
1126 // error messages without (too many) false positives
1127 // (i.e., we could just return here to not check them at
1128 // all, or some worse estimation of whether an impl is
1129 // publicly visible).
1130 hir::ItemKind::Impl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
1131 // `impl [... for] Private` is never visible.
1132 let self_contains_private;
1133 // `impl [... for] Public<...>`, but not `impl [... for]
1134 // Vec<Public>` or `(Public,)`, etc.
1135 let self_is_public_path;
1137 // Check the properties of the `Self` type:
1139 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1141 contains_private: false,
1142 at_outer_type: true,
1143 outer_type_is_public_path: false,
1145 visitor.visit_ty(&self_);
1146 self_contains_private = visitor.contains_private;
1147 self_is_public_path = visitor.outer_type_is_public_path;
1150 // Miscellaneous info about the impl:
1152 // `true` iff this is `impl Private for ...`.
1153 let not_private_trait =
1154 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1156 let did = tr.path.def.def_id();
1158 if let Some(node_id) = self.tcx.hir().as_local_node_id(did) {
1159 self.trait_is_public(node_id)
1161 true // external traits must be public
1165 // `true` iff this is a trait impl or at least one method is public.
1167 // `impl Public { $( fn ...() {} )* }` is not visible.
1169 // This is required over just using the methods' privacy
1170 // directly because we might have `impl<T: Foo<Private>> ...`,
1171 // and we shouldn't warn about the generics if all the methods
1172 // are private (because `T` won't be visible externally).
1173 let trait_or_some_public_method =
1174 trait_ref.is_some() ||
1175 impl_item_refs.iter()
1176 .any(|impl_item_ref| {
1177 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1178 match impl_item.node {
1179 hir::ImplItemKind::Const(..) |
1180 hir::ImplItemKind::Method(..) => {
1181 self.access_levels.is_reachable(impl_item.id)
1183 hir::ImplItemKind::Existential(..) |
1184 hir::ImplItemKind::Type(_) => false,
1188 if !self_contains_private &&
1189 not_private_trait &&
1190 trait_or_some_public_method {
1192 intravisit::walk_generics(self, g);
1196 for impl_item_ref in impl_item_refs {
1197 // This is where we choose whether to walk down
1198 // further into the impl to check its items. We
1199 // should only walk into public items so that we
1200 // don't erroneously report errors for private
1201 // types in private items.
1202 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1203 match impl_item.node {
1204 hir::ImplItemKind::Const(..) |
1205 hir::ImplItemKind::Method(..)
1206 if self.item_is_public(&impl_item.id, &impl_item.vis) =>
1208 intravisit::walk_impl_item(self, impl_item)
1210 hir::ImplItemKind::Type(..) => {
1211 intravisit::walk_impl_item(self, impl_item)
1218 // Any private types in a trait impl fall into three
1220 // 1. mentioned in the trait definition
1221 // 2. mentioned in the type params/generics
1222 // 3. mentioned in the associated types of the impl
1224 // Those in 1. can only occur if the trait is in
1225 // this crate and will've been warned about on the
1226 // trait definition (there's no need to warn twice
1227 // so we don't check the methods).
1229 // Those in 2. are warned via walk_generics and this
1231 intravisit::walk_path(self, &tr.path);
1233 // Those in 3. are warned with this call.
1234 for impl_item_ref in impl_item_refs {
1235 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1236 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1242 } else if trait_ref.is_none() && self_is_public_path {
1243 // `impl Public<Private> { ... }`. Any public static
1244 // methods will be visible as `Public::foo`.
1245 let mut found_pub_static = false;
1246 for impl_item_ref in impl_item_refs {
1247 if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
1248 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1249 match impl_item_ref.kind {
1250 hir::AssociatedItemKind::Const => {
1251 found_pub_static = true;
1252 intravisit::walk_impl_item(self, impl_item);
1254 hir::AssociatedItemKind::Method { has_self: false } => {
1255 found_pub_static = true;
1256 intravisit::walk_impl_item(self, impl_item);
1262 if found_pub_static {
1263 intravisit::walk_generics(self, g)
1269 // `type ... = ...;` can contain private types, because
1270 // we're introducing a new name.
1271 hir::ItemKind::Ty(..) => return,
1273 // Not at all public, so we don't care.
1274 _ if !self.item_is_public(&item.id, &item.vis) => {
1281 // We've carefully constructed it so that if we're here, then
1282 // any `visit_ty`'s will be called on things that are in
1283 // public signatures, i.e., things that we're interested in for
1285 intravisit::walk_item(self, item);
1288 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1289 for param in &generics.params {
1290 for bound in ¶m.bounds {
1291 self.check_generic_bound(bound);
1294 for predicate in &generics.where_clause.predicates {
1296 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1297 for bound in bound_pred.bounds.iter() {
1298 self.check_generic_bound(bound)
1301 &hir::WherePredicate::RegionPredicate(_) => {}
1302 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1303 self.visit_ty(&eq_pred.rhs_ty);
1309 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
1310 if self.access_levels.is_reachable(item.id) {
1311 intravisit::walk_foreign_item(self, item)
1315 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1316 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = t.node {
1317 if self.path_is_private_type(path) {
1318 self.old_error_set.insert(t.id);
1321 intravisit::walk_ty(self, t)
1324 fn visit_variant(&mut self,
1325 v: &'tcx hir::Variant,
1326 g: &'tcx hir::Generics,
1327 item_id: ast::NodeId) {
1328 if self.access_levels.is_reachable(v.node.data.id()) {
1329 self.in_variant = true;
1330 intravisit::walk_variant(self, v, g, item_id);
1331 self.in_variant = false;
1335 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
1336 if s.vis.node.is_pub() || self.in_variant {
1337 intravisit::walk_struct_field(self, s);
1341 // We don't need to introspect into these at all: an
1342 // expression/block context can't possibly contain exported things.
1343 // (Making them no-ops stops us from traversing the whole AST without
1344 // having to be super careful about our `walk_...` calls above.)
1345 fn visit_block(&mut self, _: &'tcx hir::Block) {}
1346 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1349 ///////////////////////////////////////////////////////////////////////////////
1350 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1351 /// finds any private components in it.
1352 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1353 /// and traits in public interfaces.
1354 ///////////////////////////////////////////////////////////////////////////////
1356 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1357 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1360 /// The visitor checks that each component type is at least this visible.
1361 required_visibility: ty::Visibility,
1362 /// The visibility of the least visible component that has been visited.
1363 min_visibility: ty::Visibility,
1364 has_pub_restricted: bool,
1365 has_old_errors: bool,
1369 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1370 fn generics(&mut self) -> &mut Self {
1371 for param in &self.tcx.generics_of(self.item_def_id).params {
1373 GenericParamDefKind::Type { has_default, .. } => {
1375 self.tcx.type_of(param.def_id).visit_with(self);
1378 GenericParamDefKind::Lifetime => {}
1384 fn predicates(&mut self) -> &mut Self {
1385 // N.B., we use `explicit_predicates_of` and not `predicates_of`
1386 // because we don't want to report privacy errors due to where
1387 // clauses that the compiler inferred. We only want to
1388 // consider the ones that the user wrote. This is important
1389 // for the inferred outlives rules; see
1390 // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1391 let predicates = self.tcx.explicit_predicates_of(self.item_def_id);
1392 for (predicate, _) in &predicates.predicates {
1393 predicate.visit_with(self);
1395 &ty::Predicate::Trait(poly_predicate) => {
1396 self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
1398 &ty::Predicate::Projection(poly_predicate) => {
1400 self.check_trait_ref(
1401 poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
1410 fn ty(&mut self) -> &mut Self {
1411 let ty = self.tcx.type_of(self.item_def_id);
1412 ty.visit_with(self);
1413 if let ty::FnDef(def_id, _) = ty.sty {
1414 if def_id == self.item_def_id {
1415 self.tcx.fn_sig(def_id).visit_with(self);
1421 fn impl_trait_ref(&mut self) -> &mut Self {
1422 if let Some(impl_trait_ref) = self.tcx.impl_trait_ref(self.item_def_id) {
1423 self.check_trait_ref(impl_trait_ref);
1424 impl_trait_ref.super_visit_with(self);
1429 fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
1430 // Non-local means public (private items can't leave their crate, modulo bugs).
1431 if let Some(node_id) = self.tcx.hir().as_local_node_id(trait_ref.def_id) {
1432 let item = self.tcx.hir().expect_item(node_id);
1433 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1434 if !vis.is_at_least(self.min_visibility, self.tcx) {
1435 self.min_visibility = vis;
1437 if !vis.is_at_least(self.required_visibility, self.tcx) {
1438 if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1439 struct_span_err!(self.tcx.sess, self.span, E0445,
1440 "private trait `{}` in public interface", trait_ref)
1441 .span_label(self.span, format!(
1442 "can't leak private trait"))
1445 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1448 &format!("private trait `{}` in public \
1449 interface (error E0445)", trait_ref));
1456 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1457 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
1458 let ty_def_id = match ty.sty {
1459 ty::Adt(adt, _) => Some(adt.did),
1460 ty::Foreign(did) => Some(did),
1461 ty::Dynamic(ref obj, ..) => Some(obj.principal().def_id()),
1462 ty::Projection(ref proj) => {
1463 if self.required_visibility == ty::Visibility::Invisible {
1464 // Conservatively approximate the whole type alias as public without
1465 // recursing into its components when determining impl publicity.
1466 // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
1467 // even if both `Type` and `Trait` are private.
1468 // Ideally, associated types should be substituted in the same way as
1469 // free type aliases, but this isn't done yet.
1472 let trait_ref = proj.trait_ref(self.tcx);
1473 Some(trait_ref.def_id)
1478 if let Some(def_id) = ty_def_id {
1479 // Non-local means public (private items can't leave their crate, modulo bugs).
1480 if let Some(node_id) = self.tcx.hir().as_local_node_id(def_id) {
1481 let hir_vis = match self.tcx.hir().find(node_id) {
1482 Some(Node::Item(item)) => &item.vis,
1483 Some(Node::ForeignItem(item)) => &item.vis,
1484 _ => bug!("expected item of foreign item"),
1487 let vis = ty::Visibility::from_hir(hir_vis, node_id, self.tcx);
1489 if !vis.is_at_least(self.min_visibility, self.tcx) {
1490 self.min_visibility = vis;
1492 if !vis.is_at_least(self.required_visibility, self.tcx) {
1493 let vis_adj = match hir_vis.node {
1494 hir::VisibilityKind::Crate(_) => "crate-visible",
1495 hir::VisibilityKind::Restricted { .. } => "restricted",
1499 if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1500 let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
1501 "{} type `{}` in public interface", vis_adj, ty);
1502 err.span_label(self.span, format!("can't leak {} type", vis_adj));
1503 err.span_label(hir_vis.span, format!("`{}` declared as {}", ty, vis_adj));
1506 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1509 &format!("{} type `{}` in public \
1510 interface (error E0446)", vis_adj, ty));
1516 ty.super_visit_with(self)
1520 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1521 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1522 has_pub_restricted: bool,
1523 old_error_set: &'a NodeSet,
1524 inner_visibility: ty::Visibility,
1527 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1528 fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1529 -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1530 let mut has_old_errors = false;
1532 // Slow path taken only if there any errors in the crate.
1533 for &id in self.old_error_set {
1534 // Walk up the nodes until we find `item_id` (or we hit a root).
1538 has_old_errors = true;
1541 let parent = self.tcx.hir().get_parent_node(id);
1553 SearchInterfaceForPrivateItemsVisitor {
1555 item_def_id: self.tcx.hir().local_def_id(item_id),
1556 span: self.tcx.hir().span(item_id),
1557 min_visibility: ty::Visibility::Public,
1558 required_visibility,
1559 has_pub_restricted: self.has_pub_restricted,
1566 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1567 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1568 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1571 fn visit_item(&mut self, item: &'tcx hir::Item) {
1573 let min = |vis1: ty::Visibility, vis2| {
1574 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1577 let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1580 // Crates are always public.
1581 hir::ItemKind::ExternCrate(..) => {}
1582 // All nested items are checked by `visit_item`.
1583 hir::ItemKind::Mod(..) => {}
1584 // Checked in resolve.
1585 hir::ItemKind::Use(..) => {}
1587 hir::ItemKind::GlobalAsm(..) => {}
1588 hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => {
1589 // Check the traits being exposed, as they're separate,
1590 // e.g., `impl Iterator<Item=T>` has two predicates,
1591 // `X: Iterator` and `<X as Iterator>::Item == T`,
1592 // where `X` is the `impl Iterator<Item=T>` itself,
1593 // 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 }