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