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