]> git.lizzy.rs Git - rust.git/blob - src/librustc_privacy/lib.rs
Auto merge of #40826 - frewsxcv:rollup, r=frewsxcv
[rust.git] / src / librustc_privacy / lib.rs
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.
4 //
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.
10
11 #![crate_name = "rustc_privacy"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17       html_root_url = "https://doc.rust-lang.org/nightly/")]
18 #![deny(warnings)]
19
20 #![cfg_attr(stage0, feature(field_init_shorthand))]
21 #![feature(rustc_diagnostic_macros)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
24
25 extern crate rustc;
26 #[macro_use] extern crate syntax;
27 extern crate syntax_pos;
28
29 use rustc::hir::{self, PatKind};
30 use rustc::hir::def::Def;
31 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
32 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
33 use rustc::hir::itemlikevisit::DeepVisitor;
34 use rustc::hir::pat_util::EnumerateAndAdjustIterator;
35 use rustc::lint;
36 use rustc::middle::privacy::{AccessLevel, AccessLevels};
37 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable};
38 use rustc::ty::fold::TypeVisitor;
39 use rustc::ty::maps::Providers;
40 use rustc::util::nodemap::NodeSet;
41 use syntax::ast;
42 use syntax_pos::{DUMMY_SP, Span};
43
44 use std::cmp;
45 use std::mem::replace;
46 use std::rc::Rc;
47
48 pub mod diagnostics;
49
50 ////////////////////////////////////////////////////////////////////////////////
51 /// Visitor used to determine if pub(restricted) is used anywhere in the crate.
52 ///
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,
59 }
60
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)
64     }
65     fn visit_vis(&mut self, vis: &'tcx hir::Visibility) {
66         self.has_pub_restricted = self.has_pub_restricted || vis.is_pub_restricted();
67     }
68 }
69
70 ////////////////////////////////////////////////////////////////////////////////
71 /// The embargo visitor, used to determine the exports of the ast
72 ////////////////////////////////////////////////////////////////////////////////
73
74 struct EmbargoVisitor<'a, 'tcx: 'a> {
75     tcx: TyCtxt<'a, 'tcx, 'tcx>,
76
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?
82     changed: bool,
83 }
84
85 struct ReachEverythingInTheInterfaceVisitor<'b, 'a: 'b, 'tcx: 'a> {
86     item_def_id: DefId,
87     ev: &'b mut EmbargoVisitor<'a, 'tcx>,
88 }
89
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.item_type(item_def_id).sty {
93             ty::TyAdt(adt, _) => adt.did,
94             ty::TyDynamic(ref obj, ..) if obj.principal().is_some() =>
95                 obj.principal().unwrap().def_id(),
96             ty::TyProjection(ref proj) => proj.trait_ref.def_id,
97             _ => return Some(AccessLevel::Public)
98         };
99         if let Some(node_id) = self.tcx.hir.as_local_node_id(ty_def_id) {
100             self.get(node_id)
101         } else {
102             Some(AccessLevel::Public)
103         }
104     }
105
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);
110             }
111         }
112         Some(AccessLevel::Public)
113     }
114
115     fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
116         self.access_levels.map.get(&id).cloned()
117     }
118
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());
125             self.changed = true;
126             level
127         } else {
128             old_level
129         }
130     }
131
132     fn reach<'b>(&'b mut self, item_id: ast::NodeId)
133                  -> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
134         ReachEverythingInTheInterfaceVisitor {
135             item_def_id: self.tcx.hir.local_def_id(item_id),
136             ev: self,
137         }
138     }
139 }
140
141 impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> {
142     /// We want to visit items in the context of their containing
143     /// module and so forth, so supply a crate for doing a deep walk.
144     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
145         NestedVisitorMap::All(&self.tcx.hir)
146     }
147
148     fn visit_item(&mut self, item: &'tcx hir::Item) {
149         let inherited_item_level = match item.node {
150             // Impls inherit level from their types and traits
151             hir::ItemImpl(..) => {
152                 let def_id = self.tcx.hir.local_def_id(item.id);
153                 cmp::min(self.item_ty_level(def_id), self.impl_trait_level(def_id))
154             }
155             hir::ItemDefaultImpl(..) => {
156                 let def_id = self.tcx.hir.local_def_id(item.id);
157                 self.impl_trait_level(def_id)
158             }
159             // Foreign mods inherit level from parents
160             hir::ItemForeignMod(..) => {
161                 self.prev_level
162             }
163             // Other `pub` items inherit levels from parents
164             _ => {
165                 if item.vis == hir::Public { self.prev_level } else { None }
166             }
167         };
168
169         // Update level of the item itself
170         let item_level = self.update(item.id, inherited_item_level);
171
172         // Update levels of nested things
173         match item.node {
174             hir::ItemEnum(ref def, _) => {
175                 for variant in &def.variants {
176                     let variant_level = self.update(variant.node.data.id(), item_level);
177                     for field in variant.node.data.fields() {
178                         self.update(field.id, variant_level);
179                     }
180                 }
181             }
182             hir::ItemImpl(.., None, _, ref impl_item_refs) => {
183                 for impl_item_ref in impl_item_refs {
184                     if impl_item_ref.vis == hir::Public {
185                         self.update(impl_item_ref.id.node_id, item_level);
186                     }
187                 }
188             }
189             hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
190                 for impl_item_ref in impl_item_refs {
191                     self.update(impl_item_ref.id.node_id, item_level);
192                 }
193             }
194             hir::ItemTrait(.., ref trait_item_refs) => {
195                 for trait_item_ref in trait_item_refs {
196                     self.update(trait_item_ref.id.node_id, item_level);
197                 }
198             }
199             hir::ItemStruct(ref def, _) | hir::ItemUnion(ref def, _) => {
200                 if !def.is_struct() {
201                     self.update(def.id(), item_level);
202                 }
203                 for field in def.fields() {
204                     if field.vis == hir::Public {
205                         self.update(field.id, item_level);
206                     }
207                 }
208             }
209             hir::ItemForeignMod(ref foreign_mod) => {
210                 for foreign_item in &foreign_mod.items {
211                     if foreign_item.vis == hir::Public {
212                         self.update(foreign_item.id, item_level);
213                     }
214                 }
215             }
216             _ => {}
217         }
218
219         // Mark all items in interfaces of reachable items as reachable
220         match item.node {
221             // The interface is empty
222             hir::ItemExternCrate(..) => {}
223             // All nested items are checked by visit_item
224             hir::ItemMod(..) => {}
225             // Reexports are handled in visit_mod
226             hir::ItemUse(..) => {}
227             // The interface is empty
228             hir::ItemDefaultImpl(..) => {}
229             // Visit everything
230             hir::ItemConst(..) | hir::ItemStatic(..) |
231             hir::ItemFn(..) | hir::ItemTy(..) => {
232                 if item_level.is_some() {
233                     self.reach(item.id).generics().predicates().item_type();
234                 }
235             }
236             hir::ItemTrait(.., ref trait_item_refs) => {
237                 if item_level.is_some() {
238                     self.reach(item.id).generics().predicates();
239
240                     for trait_item_ref in trait_item_refs {
241                         let mut reach = self.reach(trait_item_ref.id.node_id);
242                         reach.generics().predicates();
243
244                         if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
245                            !trait_item_ref.defaultness.has_value() {
246                             // No type to visit.
247                         } else {
248                             reach.item_type();
249                         }
250                     }
251                 }
252             }
253             // Visit everything except for private impl items
254             hir::ItemImpl(.., ref trait_ref, _, ref impl_item_refs) => {
255                 if item_level.is_some() {
256                     self.reach(item.id).generics().predicates().impl_trait_ref();
257
258                     for impl_item_ref in impl_item_refs {
259                         let id = impl_item_ref.id.node_id;
260                         if trait_ref.is_some() || self.get(id).is_some() {
261                             self.reach(id).generics().predicates().item_type();
262                         }
263                     }
264                 }
265             }
266
267             // Visit everything, but enum variants have their own levels
268             hir::ItemEnum(ref def, _) => {
269                 if item_level.is_some() {
270                     self.reach(item.id).generics().predicates();
271                 }
272                 for variant in &def.variants {
273                     if self.get(variant.node.data.id()).is_some() {
274                         for field in variant.node.data.fields() {
275                             self.reach(field.id).item_type();
276                         }
277                         // Corner case: if the variant is reachable, but its
278                         // enum is not, make the enum reachable as well.
279                         self.update(item.id, Some(AccessLevel::Reachable));
280                     }
281                 }
282             }
283             // Visit everything, but foreign items have their own levels
284             hir::ItemForeignMod(ref foreign_mod) => {
285                 for foreign_item in &foreign_mod.items {
286                     if self.get(foreign_item.id).is_some() {
287                         self.reach(foreign_item.id).generics().predicates().item_type();
288                     }
289                 }
290             }
291             // Visit everything except for private fields
292             hir::ItemStruct(ref struct_def, _) |
293             hir::ItemUnion(ref struct_def, _) => {
294                 if item_level.is_some() {
295                     self.reach(item.id).generics().predicates();
296                     for field in struct_def.fields() {
297                         if self.get(field.id).is_some() {
298                             self.reach(field.id).item_type();
299                         }
300                     }
301                 }
302             }
303         }
304
305         let orig_level = self.prev_level;
306         self.prev_level = item_level;
307
308         intravisit::walk_item(self, item);
309
310         self.prev_level = orig_level;
311     }
312
313     fn visit_block(&mut self, b: &'tcx hir::Block) {
314         let orig_level = replace(&mut self.prev_level, None);
315
316         // Blocks can have public items, for example impls, but they always
317         // start as completely private regardless of publicity of a function,
318         // constant, type, field, etc. in which this block resides
319         intravisit::walk_block(self, b);
320
321         self.prev_level = orig_level;
322     }
323
324     fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
325         // This code is here instead of in visit_item so that the
326         // crate module gets processed as well.
327         if self.prev_level.is_some() {
328             if let Some(exports) = self.tcx.export_map.get(&id) {
329                 for export in exports {
330                     if let Some(node_id) = self.tcx.hir.as_local_node_id(export.def.def_id()) {
331                         self.update(node_id, Some(AccessLevel::Exported));
332                     }
333                 }
334             }
335         }
336
337         intravisit::walk_mod(self, m, id);
338     }
339
340     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
341         self.update(md.id, Some(AccessLevel::Public));
342     }
343
344     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
345         if let hir::TyImplTrait(..) = ty.node {
346             if self.get(ty.id).is_some() {
347                 // Reach the (potentially private) type and the API being exposed.
348                 self.reach(ty.id).item_type().predicates();
349             }
350         }
351
352         intravisit::walk_ty(self, ty);
353     }
354 }
355
356 impl<'b, 'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
357     fn generics(&mut self) -> &mut Self {
358         for def in &self.ev.tcx.item_generics(self.item_def_id).types {
359             if def.has_default {
360                 self.ev.tcx.item_type(def.def_id).visit_with(self);
361             }
362         }
363         self
364     }
365
366     fn predicates(&mut self) -> &mut Self {
367         self.ev.tcx.item_predicates(self.item_def_id).visit_with(self);
368         self
369     }
370
371     fn item_type(&mut self) -> &mut Self {
372         self.ev.tcx.item_type(self.item_def_id).visit_with(self);
373         self
374     }
375
376     fn impl_trait_ref(&mut self) -> &mut Self {
377         self.ev.tcx.impl_trait_ref(self.item_def_id).visit_with(self);
378         self
379     }
380 }
381
382 impl<'b, 'a, 'tcx> TypeVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
383     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
384         let ty_def_id = match ty.sty {
385             ty::TyAdt(adt, _) => Some(adt.did),
386             ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
387             ty::TyProjection(ref proj) => Some(proj.trait_ref.def_id),
388             ty::TyFnDef(def_id, ..) |
389             ty::TyAnon(def_id, _) => Some(def_id),
390             _ => None
391         };
392
393         if let Some(def_id) = ty_def_id {
394             if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(def_id) {
395                 self.ev.update(node_id, Some(AccessLevel::Reachable));
396             }
397         }
398
399         ty.super_visit_with(self)
400     }
401
402     fn visit_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
403         if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(trait_ref.def_id) {
404             let item = self.ev.tcx.hir.expect_item(node_id);
405             self.ev.update(item.id, Some(AccessLevel::Reachable));
406         }
407
408         trait_ref.super_visit_with(self)
409     }
410 }
411
412 ////////////////////////////////////////////////////////////////////////////////
413 /// The privacy visitor, where privacy checks take place (violations reported)
414 ////////////////////////////////////////////////////////////////////////////////
415
416 struct PrivacyVisitor<'a, 'tcx: 'a> {
417     tcx: TyCtxt<'a, 'tcx, 'tcx>,
418     curitem: DefId,
419     in_foreign: bool,
420     tables: &'a ty::TypeckTables<'tcx>,
421 }
422
423 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
424     fn item_is_accessible(&self, did: DefId) -> bool {
425         match self.tcx.hir.as_local_node_id(did) {
426             Some(node_id) =>
427                 ty::Visibility::from_hir(&self.tcx.hir.expect_item(node_id).vis, node_id, self.tcx),
428             None => self.tcx.sess.cstore.visibility(did),
429         }.is_accessible_from(self.curitem, self.tcx)
430     }
431
432     // Checks that a field is in scope.
433     fn check_field(&mut self, span: Span, def: &'tcx ty::AdtDef, field: &'tcx ty::FieldDef) {
434         if !def.is_enum() && !field.vis.is_accessible_from(self.curitem, self.tcx) {
435             struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
436                       field.name, def.variant_descr(), self.tcx.item_path_str(def.did))
437                 .span_label(span, &format!("field `{}` is private", field.name))
438                 .emit();
439         }
440     }
441
442     // Checks that a method is in scope.
443     fn check_method(&mut self, span: Span, method_def_id: DefId) {
444         match self.tcx.associated_item(method_def_id).container {
445             // Trait methods are always all public. The only controlling factor
446             // is whether the trait itself is accessible or not.
447             ty::TraitContainer(trait_def_id) if !self.item_is_accessible(trait_def_id) => {
448                 let msg = format!("source trait `{}` is private",
449                                   self.tcx.item_path_str(trait_def_id));
450                 self.tcx.sess.span_err(span, &msg);
451             }
452             _ => {}
453         }
454     }
455 }
456
457 impl<'a, 'tcx> Visitor<'tcx> for PrivacyVisitor<'a, 'tcx> {
458     /// We want to visit items in the context of their containing
459     /// module and so forth, so supply a crate for doing a deep walk.
460     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
461         NestedVisitorMap::All(&self.tcx.hir)
462     }
463
464     fn visit_nested_body(&mut self, body: hir::BodyId) {
465         let old_tables = self.tables;
466         self.tables = self.tcx.body_tables(body);
467         let body = self.tcx.hir.body(body);
468         self.visit_body(body);
469         self.tables = old_tables;
470     }
471
472     fn visit_item(&mut self, item: &'tcx hir::Item) {
473         let orig_curitem = replace(&mut self.curitem, self.tcx.hir.local_def_id(item.id));
474         intravisit::walk_item(self, item);
475         self.curitem = orig_curitem;
476     }
477
478     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
479         match expr.node {
480             hir::ExprMethodCall(..) => {
481                 let method_call = ty::MethodCall::expr(expr.id);
482                 let method = self.tables.method_map[&method_call];
483                 self.check_method(expr.span, method.def_id);
484             }
485             hir::ExprStruct(ref qpath, ref expr_fields, _) => {
486                 let def = self.tables.qpath_def(qpath, expr.id);
487                 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
488                 let variant = adt.variant_of_def(def);
489                 // RFC 736: ensure all unmentioned fields are visible.
490                 // Rather than computing the set of unmentioned fields
491                 // (i.e. `all_fields - fields`), just check them all,
492                 // unless the ADT is a union, then unmentioned fields
493                 // are not checked.
494                 if adt.is_union() {
495                     for expr_field in expr_fields {
496                         self.check_field(expr.span, adt, variant.field_named(expr_field.name.node));
497                     }
498                 } else {
499                     for field in &variant.fields {
500                         let expr_field = expr_fields.iter().find(|f| f.name.node == field.name);
501                         let span = if let Some(f) = expr_field { f.span } else { expr.span };
502                         self.check_field(span, adt, field);
503                     }
504                 }
505             }
506             _ => {}
507         }
508
509         intravisit::walk_expr(self, expr);
510     }
511
512     fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
513         // Foreign functions do not have their patterns mapped in the def_map,
514         // and there's nothing really relevant there anyway, so don't bother
515         // checking privacy. If you can name the type then you can pass it to an
516         // external C function anyway.
517         if self.in_foreign { return }
518
519         match pattern.node {
520             PatKind::Struct(ref qpath, ref fields, _) => {
521                 let def = self.tables.qpath_def(qpath, pattern.id);
522                 let adt = self.tables.pat_ty(pattern).ty_adt_def().unwrap();
523                 let variant = adt.variant_of_def(def);
524                 for field in fields {
525                     self.check_field(field.span, adt, variant.field_named(field.node.name));
526                 }
527             }
528             PatKind::TupleStruct(_, ref fields, ddpos) => {
529                 match self.tables.pat_ty(pattern).sty {
530                     // enum fields have no privacy at this time
531                     ty::TyAdt(def, _) if !def.is_enum() => {
532                         let expected_len = def.struct_variant().fields.len();
533                         for (i, field) in fields.iter().enumerate_and_adjust(expected_len, ddpos) {
534                             if let PatKind::Wild = field.node {
535                                 continue
536                             }
537                             self.check_field(field.span, def, &def.struct_variant().fields[i]);
538                         }
539                     }
540                     _ => {}
541                 }
542             }
543             _ => {}
544         }
545
546         intravisit::walk_pat(self, pattern);
547     }
548
549     fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem) {
550         self.in_foreign = true;
551         intravisit::walk_foreign_item(self, fi);
552         self.in_foreign = false;
553     }
554 }
555
556 ///////////////////////////////////////////////////////////////////////////////
557 /// Obsolete visitors for checking for private items in public interfaces.
558 /// These visitors are supposed to be kept in frozen state and produce an
559 /// "old error node set". For backward compatibility the new visitor reports
560 /// warnings instead of hard errors when the erroneous node is not in this old set.
561 ///////////////////////////////////////////////////////////////////////////////
562
563 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
564     tcx: TyCtxt<'a, 'tcx, 'tcx>,
565     access_levels: &'a AccessLevels,
566     in_variant: bool,
567     // set of errors produced by this obsolete visitor
568     old_error_set: NodeSet,
569 }
570
571 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
572     inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
573     /// whether the type refers to private types.
574     contains_private: bool,
575     /// whether we've recurred at all (i.e. if we're pointing at the
576     /// first type on which visit_ty was called).
577     at_outer_type: bool,
578     // whether that first type is a public path.
579     outer_type_is_public_path: bool,
580 }
581
582 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
583     fn path_is_private_type(&self, path: &hir::Path) -> bool {
584         let did = match path.def {
585             Def::PrimTy(..) | Def::SelfTy(..) => return false,
586             def => def.def_id(),
587         };
588
589         // A path can only be private if:
590         // it's in this crate...
591         if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
592             // .. and it corresponds to a private type in the AST (this returns
593             // None for type parameters)
594             match self.tcx.hir.find(node_id) {
595                 Some(hir::map::NodeItem(ref item)) => item.vis != hir::Public,
596                 Some(_) | None => false,
597             }
598         } else {
599             return false
600         }
601     }
602
603     fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
604         // FIXME: this would preferably be using `exported_items`, but all
605         // traits are exported currently (see `EmbargoVisitor.exported_trait`)
606         self.access_levels.is_public(trait_id)
607     }
608
609     fn check_ty_param_bound(&mut self,
610                             ty_param_bound: &hir::TyParamBound) {
611         if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
612             if self.path_is_private_type(&trait_ref.trait_ref.path) {
613                 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
614             }
615         }
616     }
617
618     fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
619         self.access_levels.is_reachable(*id) || *vis == hir::Public
620     }
621 }
622
623 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
624     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
625         NestedVisitorMap::None
626     }
627
628     fn visit_ty(&mut self, ty: &hir::Ty) {
629         if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = ty.node {
630             if self.inner.path_is_private_type(path) {
631                 self.contains_private = true;
632                 // found what we're looking for so let's stop
633                 // working.
634                 return
635             }
636         }
637         if let hir::TyPath(_) = ty.node {
638             if self.at_outer_type {
639                 self.outer_type_is_public_path = true;
640             }
641         }
642         self.at_outer_type = false;
643         intravisit::walk_ty(self, ty)
644     }
645
646     // don't want to recurse into [, .. expr]
647     fn visit_expr(&mut self, _: &hir::Expr) {}
648 }
649
650 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
651     /// We want to visit items in the context of their containing
652     /// module and so forth, so supply a crate for doing a deep walk.
653     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
654         NestedVisitorMap::All(&self.tcx.hir)
655     }
656
657     fn visit_item(&mut self, item: &'tcx hir::Item) {
658         match item.node {
659             // contents of a private mod can be reexported, so we need
660             // to check internals.
661             hir::ItemMod(_) => {}
662
663             // An `extern {}` doesn't introduce a new privacy
664             // namespace (the contents have their own privacies).
665             hir::ItemForeignMod(_) => {}
666
667             hir::ItemTrait(.., ref bounds, _) => {
668                 if !self.trait_is_public(item.id) {
669                     return
670                 }
671
672                 for bound in bounds.iter() {
673                     self.check_ty_param_bound(bound)
674                 }
675             }
676
677             // impls need some special handling to try to offer useful
678             // error messages without (too many) false positives
679             // (i.e. we could just return here to not check them at
680             // all, or some worse estimation of whether an impl is
681             // publicly visible).
682             hir::ItemImpl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
683                 // `impl [... for] Private` is never visible.
684                 let self_contains_private;
685                 // impl [... for] Public<...>, but not `impl [... for]
686                 // Vec<Public>` or `(Public,)` etc.
687                 let self_is_public_path;
688
689                 // check the properties of the Self type:
690                 {
691                     let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
692                         inner: self,
693                         contains_private: false,
694                         at_outer_type: true,
695                         outer_type_is_public_path: false,
696                     };
697                     visitor.visit_ty(&self_);
698                     self_contains_private = visitor.contains_private;
699                     self_is_public_path = visitor.outer_type_is_public_path;
700                 }
701
702                 // miscellaneous info about the impl
703
704                 // `true` iff this is `impl Private for ...`.
705                 let not_private_trait =
706                     trait_ref.as_ref().map_or(true, // no trait counts as public trait
707                                               |tr| {
708                         let did = tr.path.def.def_id();
709
710                         if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
711                             self.trait_is_public(node_id)
712                         } else {
713                             true // external traits must be public
714                         }
715                     });
716
717                 // `true` iff this is a trait impl or at least one method is public.
718                 //
719                 // `impl Public { $( fn ...() {} )* }` is not visible.
720                 //
721                 // This is required over just using the methods' privacy
722                 // directly because we might have `impl<T: Foo<Private>> ...`,
723                 // and we shouldn't warn about the generics if all the methods
724                 // are private (because `T` won't be visible externally).
725                 let trait_or_some_public_method =
726                     trait_ref.is_some() ||
727                     impl_item_refs.iter()
728                                  .any(|impl_item_ref| {
729                                      let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
730                                      match impl_item.node {
731                                          hir::ImplItemKind::Const(..) |
732                                          hir::ImplItemKind::Method(..) => {
733                                              self.access_levels.is_reachable(impl_item.id)
734                                          }
735                                          hir::ImplItemKind::Type(_) => false,
736                                      }
737                                  });
738
739                 if !self_contains_private &&
740                         not_private_trait &&
741                         trait_or_some_public_method {
742
743                     intravisit::walk_generics(self, g);
744
745                     match *trait_ref {
746                         None => {
747                             for impl_item_ref in impl_item_refs {
748                                 // This is where we choose whether to walk down
749                                 // further into the impl to check its items. We
750                                 // should only walk into public items so that we
751                                 // don't erroneously report errors for private
752                                 // types in private items.
753                                 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
754                                 match impl_item.node {
755                                     hir::ImplItemKind::Const(..) |
756                                     hir::ImplItemKind::Method(..)
757                                         if self.item_is_public(&impl_item.id, &impl_item.vis) =>
758                                     {
759                                         intravisit::walk_impl_item(self, impl_item)
760                                     }
761                                     hir::ImplItemKind::Type(..) => {
762                                         intravisit::walk_impl_item(self, impl_item)
763                                     }
764                                     _ => {}
765                                 }
766                             }
767                         }
768                         Some(ref tr) => {
769                             // Any private types in a trait impl fall into three
770                             // categories.
771                             // 1. mentioned in the trait definition
772                             // 2. mentioned in the type params/generics
773                             // 3. mentioned in the associated types of the impl
774                             //
775                             // Those in 1. can only occur if the trait is in
776                             // this crate and will've been warned about on the
777                             // trait definition (there's no need to warn twice
778                             // so we don't check the methods).
779                             //
780                             // Those in 2. are warned via walk_generics and this
781                             // call here.
782                             intravisit::walk_path(self, &tr.path);
783
784                             // Those in 3. are warned with this call.
785                             for impl_item_ref in impl_item_refs {
786                                 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
787                                 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
788                                     self.visit_ty(ty);
789                                 }
790                             }
791                         }
792                     }
793                 } else if trait_ref.is_none() && self_is_public_path {
794                     // impl Public<Private> { ... }. Any public static
795                     // methods will be visible as `Public::foo`.
796                     let mut found_pub_static = false;
797                     for impl_item_ref in impl_item_refs {
798                         if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
799                             let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
800                             match impl_item_ref.kind {
801                                 hir::AssociatedItemKind::Const => {
802                                     found_pub_static = true;
803                                     intravisit::walk_impl_item(self, impl_item);
804                                 }
805                                 hir::AssociatedItemKind::Method { has_self: false } => {
806                                     found_pub_static = true;
807                                     intravisit::walk_impl_item(self, impl_item);
808                                 }
809                                 _ => {}
810                             }
811                         }
812                     }
813                     if found_pub_static {
814                         intravisit::walk_generics(self, g)
815                     }
816                 }
817                 return
818             }
819
820             // `type ... = ...;` can contain private types, because
821             // we're introducing a new name.
822             hir::ItemTy(..) => return,
823
824             // not at all public, so we don't care
825             _ if !self.item_is_public(&item.id, &item.vis) => {
826                 return;
827             }
828
829             _ => {}
830         }
831
832         // We've carefully constructed it so that if we're here, then
833         // any `visit_ty`'s will be called on things that are in
834         // public signatures, i.e. things that we're interested in for
835         // this visitor.
836         intravisit::walk_item(self, item);
837     }
838
839     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
840         for ty_param in generics.ty_params.iter() {
841             for bound in ty_param.bounds.iter() {
842                 self.check_ty_param_bound(bound)
843             }
844         }
845         for predicate in &generics.where_clause.predicates {
846             match predicate {
847                 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
848                     for bound in bound_pred.bounds.iter() {
849                         self.check_ty_param_bound(bound)
850                     }
851                 }
852                 &hir::WherePredicate::RegionPredicate(_) => {}
853                 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
854                     self.visit_ty(&eq_pred.rhs_ty);
855                 }
856             }
857         }
858     }
859
860     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
861         if self.access_levels.is_reachable(item.id) {
862             intravisit::walk_foreign_item(self, item)
863         }
864     }
865
866     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
867         if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = t.node {
868             if self.path_is_private_type(path) {
869                 self.old_error_set.insert(t.id);
870             }
871         }
872         intravisit::walk_ty(self, t)
873     }
874
875     fn visit_variant(&mut self,
876                      v: &'tcx hir::Variant,
877                      g: &'tcx hir::Generics,
878                      item_id: ast::NodeId) {
879         if self.access_levels.is_reachable(v.node.data.id()) {
880             self.in_variant = true;
881             intravisit::walk_variant(self, v, g, item_id);
882             self.in_variant = false;
883         }
884     }
885
886     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
887         if s.vis == hir::Public || self.in_variant {
888             intravisit::walk_struct_field(self, s);
889         }
890     }
891
892     // we don't need to introspect into these at all: an
893     // expression/block context can't possibly contain exported things.
894     // (Making them no-ops stops us from traversing the whole AST without
895     // having to be super careful about our `walk_...` calls above.)
896     fn visit_block(&mut self, _: &'tcx hir::Block) {}
897     fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
898 }
899
900 ///////////////////////////////////////////////////////////////////////////////
901 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
902 /// finds any private components in it.
903 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
904 /// and traits in public interfaces.
905 ///////////////////////////////////////////////////////////////////////////////
906
907 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
908     tcx: TyCtxt<'a, 'tcx, 'tcx>,
909     item_def_id: DefId,
910     span: Span,
911     /// The visitor checks that each component type is at least this visible
912     required_visibility: ty::Visibility,
913     /// The visibility of the least visible component that has been visited
914     min_visibility: ty::Visibility,
915     has_pub_restricted: bool,
916     has_old_errors: bool,
917 }
918
919 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
920     fn generics(&mut self) -> &mut Self {
921         for def in &self.tcx.item_generics(self.item_def_id).types {
922             if def.has_default {
923                 self.tcx.item_type(def.def_id).visit_with(self);
924             }
925         }
926         self
927     }
928
929     fn predicates(&mut self) -> &mut Self {
930         self.tcx.item_predicates(self.item_def_id).visit_with(self);
931         self
932     }
933
934     fn item_type(&mut self) -> &mut Self {
935         self.tcx.item_type(self.item_def_id).visit_with(self);
936         self
937     }
938
939     fn impl_trait_ref(&mut self) -> &mut Self {
940         self.tcx.impl_trait_ref(self.item_def_id).visit_with(self);
941         self
942     }
943 }
944
945 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
946     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
947         let ty_def_id = match ty.sty {
948             ty::TyAdt(adt, _) => Some(adt.did),
949             ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
950             ty::TyProjection(ref proj) => {
951                 if self.required_visibility == ty::Visibility::Invisible {
952                     // Conservatively approximate the whole type alias as public without
953                     // recursing into its components when determining impl publicity.
954                     // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
955                     // even if both `Type` and `Trait` are private.
956                     // Ideally, associated types should be substituted in the same way as
957                     // free type aliases, but this isn't done yet.
958                     return false;
959                 }
960
961                 Some(proj.trait_ref.def_id)
962             }
963             _ => None
964         };
965
966         if let Some(def_id) = ty_def_id {
967             // Non-local means public (private items can't leave their crate, modulo bugs)
968             if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
969                 let item = self.tcx.hir.expect_item(node_id);
970                 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
971
972                 if !vis.is_at_least(self.min_visibility, self.tcx) {
973                     self.min_visibility = vis;
974                 }
975                 if !vis.is_at_least(self.required_visibility, self.tcx) {
976                     if self.has_pub_restricted || self.has_old_errors {
977                         let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
978                             "private type `{}` in public interface", ty);
979                         err.span_label(self.span, &format!("can't leak private type"));
980                         err.emit();
981                     } else {
982                         self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
983                                                node_id,
984                                                self.span,
985                                                format!("private type `{}` in public \
986                                                         interface (error E0446)", ty));
987                     }
988                 }
989             }
990         }
991
992         if let ty::TyProjection(ref proj) = ty.sty {
993             // Avoid calling `visit_trait_ref` below on the trait,
994             // as we have already checked the trait itself above.
995             proj.trait_ref.super_visit_with(self)
996         } else {
997             ty.super_visit_with(self)
998         }
999     }
1000
1001     fn visit_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
1002         // Non-local means public (private items can't leave their crate, modulo bugs)
1003         if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
1004             let item = self.tcx.hir.expect_item(node_id);
1005             let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1006
1007             if !vis.is_at_least(self.min_visibility, self.tcx) {
1008                 self.min_visibility = vis;
1009             }
1010             if !vis.is_at_least(self.required_visibility, self.tcx) {
1011                 if self.has_pub_restricted || self.has_old_errors {
1012                     struct_span_err!(self.tcx.sess, self.span, E0445,
1013                                      "private trait `{}` in public interface", trait_ref)
1014                         .span_label(self.span, &format!(
1015                                     "private trait can't be public"))
1016                         .emit();
1017                 } else {
1018                     self.tcx.sess.add_lint(lint::builtin::PRIVATE_IN_PUBLIC,
1019                                            node_id,
1020                                            self.span,
1021                                            format!("private trait `{}` in public \
1022                                                     interface (error E0445)", trait_ref));
1023                 }
1024             }
1025         }
1026
1027         trait_ref.super_visit_with(self)
1028     }
1029 }
1030
1031 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1032     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1033     has_pub_restricted: bool,
1034     old_error_set: &'a NodeSet,
1035     inner_visibility: ty::Visibility,
1036 }
1037
1038 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1039     fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1040              -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1041         let mut has_old_errors = false;
1042
1043         // Slow path taken only if there any errors in the crate.
1044         for &id in self.old_error_set {
1045             // Walk up the nodes until we find `item_id` (or we hit a root).
1046             let mut id = id;
1047             loop {
1048                 if id == item_id {
1049                     has_old_errors = true;
1050                     break;
1051                 }
1052                 let parent = self.tcx.hir.get_parent_node(id);
1053                 if parent == id {
1054                     break;
1055                 }
1056                 id = parent;
1057             }
1058
1059             if has_old_errors {
1060                 break;
1061             }
1062         }
1063
1064         SearchInterfaceForPrivateItemsVisitor {
1065             tcx: self.tcx,
1066             item_def_id: self.tcx.hir.local_def_id(item_id),
1067             span: self.tcx.hir.span(item_id),
1068             min_visibility: ty::Visibility::Public,
1069             required_visibility: required_visibility,
1070             has_pub_restricted: self.has_pub_restricted,
1071             has_old_errors: has_old_errors,
1072         }
1073     }
1074 }
1075
1076 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1077     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1078         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
1079     }
1080
1081     fn visit_item(&mut self, item: &'tcx hir::Item) {
1082         let tcx = self.tcx;
1083         let min = |vis1: ty::Visibility, vis2| {
1084             if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1085         };
1086
1087         let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1088
1089         match item.node {
1090             // Crates are always public
1091             hir::ItemExternCrate(..) => {}
1092             // All nested items are checked by visit_item
1093             hir::ItemMod(..) => {}
1094             // Checked in resolve
1095             hir::ItemUse(..) => {}
1096             // Subitems of these items have inherited publicity
1097             hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1098             hir::ItemTy(..) => {
1099                 self.check(item.id, item_visibility).generics().predicates().item_type();
1100
1101                 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1102                 self.inner_visibility = item_visibility;
1103                 intravisit::walk_item(self, item);
1104             }
1105             hir::ItemTrait(.., ref trait_item_refs) => {
1106                 self.check(item.id, item_visibility).generics().predicates();
1107
1108                 for trait_item_ref in trait_item_refs {
1109                     let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1110                     check.generics().predicates();
1111
1112                     if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1113                        !trait_item_ref.defaultness.has_value() {
1114                         // No type to visit.
1115                     } else {
1116                         check.item_type();
1117                     }
1118                 }
1119             }
1120             hir::ItemEnum(ref def, _) => {
1121                 self.check(item.id, item_visibility).generics().predicates();
1122
1123                 for variant in &def.variants {
1124                     for field in variant.node.data.fields() {
1125                         self.check(field.id, item_visibility).item_type();
1126                     }
1127                 }
1128             }
1129             // Subitems of foreign modules have their own publicity
1130             hir::ItemForeignMod(ref foreign_mod) => {
1131                 for foreign_item in &foreign_mod.items {
1132                     let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1133                     self.check(foreign_item.id, vis).generics().predicates().item_type();
1134                 }
1135             }
1136             // Subitems of structs and unions have their own publicity
1137             hir::ItemStruct(ref struct_def, _) |
1138             hir::ItemUnion(ref struct_def, _) => {
1139                 self.check(item.id, item_visibility).generics().predicates();
1140
1141                 for field in struct_def.fields() {
1142                     let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1143                     self.check(field.id, min(item_visibility, field_visibility)).item_type();
1144                 }
1145             }
1146             // The interface is empty
1147             hir::ItemDefaultImpl(..) => {}
1148             // An inherent impl is public when its type is public
1149             // Subitems of inherent impls have their own publicity
1150             hir::ItemImpl(.., None, _, ref impl_item_refs) => {
1151                 let ty_vis =
1152                     self.check(item.id, ty::Visibility::Invisible).item_type().min_visibility;
1153                 self.check(item.id, ty_vis).generics().predicates();
1154
1155                 for impl_item_ref in impl_item_refs {
1156                     let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1157                     let impl_item_vis =
1158                         ty::Visibility::from_hir(&impl_item.vis, item.id, tcx);
1159                     self.check(impl_item.id, min(impl_item_vis, ty_vis))
1160                         .generics().predicates().item_type();
1161
1162                     // Recurse for e.g. `impl Trait` (see `visit_ty`).
1163                     self.inner_visibility = impl_item_vis;
1164                     intravisit::walk_impl_item(self, impl_item);
1165                 }
1166             }
1167             // A trait impl is public when both its type and its trait are public
1168             // Subitems of trait impls have inherited publicity
1169             hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
1170                 let vis = self.check(item.id, ty::Visibility::Invisible)
1171                               .item_type().impl_trait_ref().min_visibility;
1172                 self.check(item.id, vis).generics().predicates();
1173                 for impl_item_ref in impl_item_refs {
1174                     let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1175                     self.check(impl_item.id, vis).generics().predicates().item_type();
1176
1177                     // Recurse for e.g. `impl Trait` (see `visit_ty`).
1178                     self.inner_visibility = vis;
1179                     intravisit::walk_impl_item(self, impl_item);
1180                 }
1181             }
1182         }
1183     }
1184
1185     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
1186         // handled in `visit_item` above
1187     }
1188
1189     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1190         if let hir::TyImplTrait(..) = ty.node {
1191             // Check the traits being exposed, as they're separate,
1192             // e.g. `impl Iterator<Item=T>` has two predicates,
1193             // `X: Iterator` and `<X as Iterator>::Item == T`,
1194             // where `X` is the `impl Iterator<Item=T>` itself,
1195             // stored in `item_predicates`, not in the `Ty` itself.
1196             self.check(ty.id, self.inner_visibility).predicates();
1197         }
1198
1199         intravisit::walk_ty(self, ty);
1200     }
1201
1202     // Don't recurse into expressions in array sizes or const initializers
1203     fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1204     // Don't recurse into patterns in function arguments
1205     fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
1206 }
1207
1208 pub fn provide(providers: &mut Providers) {
1209     *providers = Providers {
1210         privacy_access_levels,
1211         ..*providers
1212     };
1213 }
1214
1215 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Rc<AccessLevels> {
1216     tcx.dep_graph.with_ignore(|| { // FIXME
1217         ty::queries::privacy_access_levels::get(tcx, DUMMY_SP, LOCAL_CRATE)
1218     })
1219 }
1220
1221 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1222                                    krate: CrateNum)
1223                                    -> Rc<AccessLevels> {
1224     assert_eq!(krate, LOCAL_CRATE);
1225
1226     let krate = tcx.hir.krate();
1227
1228     // Use the parent map to check the privacy of everything
1229     let mut visitor = PrivacyVisitor {
1230         curitem: DefId::local(CRATE_DEF_INDEX),
1231         in_foreign: false,
1232         tcx: tcx,
1233         tables: &ty::TypeckTables::empty(),
1234     };
1235     intravisit::walk_crate(&mut visitor, krate);
1236
1237     tcx.sess.abort_if_errors();
1238
1239     // Build up a set of all exported items in the AST. This is a set of all
1240     // items which are reachable from external crates based on visibility.
1241     let mut visitor = EmbargoVisitor {
1242         tcx: tcx,
1243         access_levels: Default::default(),
1244         prev_level: Some(AccessLevel::Public),
1245         changed: false,
1246     };
1247     loop {
1248         intravisit::walk_crate(&mut visitor, krate);
1249         if visitor.changed {
1250             visitor.changed = false;
1251         } else {
1252             break
1253         }
1254     }
1255     visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1256
1257     {
1258         let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1259             tcx: tcx,
1260             access_levels: &visitor.access_levels,
1261             in_variant: false,
1262             old_error_set: NodeSet(),
1263         };
1264         intravisit::walk_crate(&mut visitor, krate);
1265
1266
1267         let has_pub_restricted = {
1268             let mut pub_restricted_visitor = PubRestrictedVisitor {
1269                 tcx: tcx,
1270                 has_pub_restricted: false
1271             };
1272             intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1273             pub_restricted_visitor.has_pub_restricted
1274         };
1275
1276         // Check for private types and traits in public interfaces
1277         let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1278             tcx: tcx,
1279             has_pub_restricted: has_pub_restricted,
1280             old_error_set: &visitor.old_error_set,
1281             inner_visibility: ty::Visibility::Public,
1282         };
1283         krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1284     }
1285
1286     Rc::new(visitor.access_levels)
1287 }
1288
1289 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }