]> git.lizzy.rs Git - rust.git/blob - src/librustc_privacy/lib.rs
Auto merge of #28174 - steveklabnik:gh14705, r=alexcricton
[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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_privacy"]
14 #![unstable(feature = "rustc_private", issue = "27812")]
15 #![staged_api]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20       html_root_url = "https://doc.rust-lang.org/nightly/")]
21
22 #![feature(rustc_diagnostic_macros)]
23 #![feature(rustc_private)]
24 #![feature(staged_api)]
25
26 #[macro_use] extern crate log;
27 #[macro_use] extern crate syntax;
28
29 extern crate rustc;
30 extern crate rustc_front;
31
32 use self::PrivacyResult::*;
33 use self::FieldName::*;
34
35 use std::mem::replace;
36
37 use rustc_front::hir;
38 use rustc_front::visit::{self, Visitor};
39
40 use rustc::middle::def;
41 use rustc::middle::def_id::DefId;
42 use rustc::middle::privacy::ImportUse::*;
43 use rustc::middle::privacy::LastPrivate::*;
44 use rustc::middle::privacy::PrivateDep::*;
45 use rustc::middle::privacy::{ExternalExports, ExportedItems, PublicItems};
46 use rustc::middle::ty::{self, Ty};
47 use rustc::util::nodemap::{NodeMap, NodeSet};
48 use rustc::front::map as ast_map;
49
50 use syntax::ast;
51 use syntax::codemap::Span;
52
53 type Context<'a, 'tcx> = (&'a ty::MethodMap<'tcx>, &'a def::ExportMap);
54
55 /// Result of a checking operation - None => no errors were found. Some => an
56 /// error and contains the span and message for reporting that error and
57 /// optionally the same for a note about the error.
58 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
59
60 ////////////////////////////////////////////////////////////////////////////////
61 /// The parent visitor, used to determine what's the parent of what (node-wise)
62 ////////////////////////////////////////////////////////////////////////////////
63
64 struct ParentVisitor {
65     parents: NodeMap<ast::NodeId>,
66     curparent: ast::NodeId,
67 }
68
69 impl<'v> Visitor<'v> for ParentVisitor {
70     fn visit_item(&mut self, item: &hir::Item) {
71         self.parents.insert(item.id, self.curparent);
72
73         let prev = self.curparent;
74         match item.node {
75             hir::ItemMod(..) => { self.curparent = item.id; }
76             // Enum variants are parented to the enum definition itself because
77             // they inherit privacy
78             hir::ItemEnum(ref def, _) => {
79                 for variant in &def.variants {
80                     // The parent is considered the enclosing enum because the
81                     // enum will dictate the privacy visibility of this variant
82                     // instead.
83                     self.parents.insert(variant.node.id, item.id);
84                 }
85             }
86
87             // Trait methods are always considered "public", but if the trait is
88             // private then we need some private item in the chain from the
89             // method to the root. In this case, if the trait is private, then
90             // parent all the methods to the trait to indicate that they're
91             // private.
92             hir::ItemTrait(_, _, _, ref trait_items) if item.vis != hir::Public => {
93                 for trait_item in trait_items {
94                     self.parents.insert(trait_item.id, item.id);
95                 }
96             }
97
98             _ => {}
99         }
100         visit::walk_item(self, item);
101         self.curparent = prev;
102     }
103
104     fn visit_foreign_item(&mut self, a: &hir::ForeignItem) {
105         self.parents.insert(a.id, self.curparent);
106         visit::walk_foreign_item(self, a);
107     }
108
109     fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v hir::FnDecl,
110                 c: &'v hir::Block, d: Span, id: ast::NodeId) {
111         // We already took care of some trait methods above, otherwise things
112         // like impl methods and pub trait methods are parented to the
113         // containing module, not the containing trait.
114         if !self.parents.contains_key(&id) {
115             self.parents.insert(id, self.curparent);
116         }
117         visit::walk_fn(self, a, b, c, d);
118     }
119
120     fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) {
121         // visit_fn handles methods, but associated consts have to be handled
122         // here.
123         if !self.parents.contains_key(&ii.id) {
124             self.parents.insert(ii.id, self.curparent);
125         }
126         visit::walk_impl_item(self, ii);
127     }
128
129     fn visit_struct_def(&mut self, s: &hir::StructDef, _: ast::Ident,
130                         _: &'v hir::Generics, n: ast::NodeId) {
131         // Struct constructors are parented to their struct definitions because
132         // they essentially are the struct definitions.
133         match s.ctor_id {
134             Some(id) => { self.parents.insert(id, n); }
135             None => {}
136         }
137
138         // While we have the id of the struct definition, go ahead and parent
139         // all the fields.
140         for field in &s.fields {
141             self.parents.insert(field.node.id, self.curparent);
142         }
143         visit::walk_struct_def(self, s)
144     }
145 }
146
147 ////////////////////////////////////////////////////////////////////////////////
148 /// The embargo visitor, used to determine the exports of the ast
149 ////////////////////////////////////////////////////////////////////////////////
150
151 struct EmbargoVisitor<'a, 'tcx: 'a> {
152     tcx: &'a ty::ctxt<'tcx>,
153     export_map: &'a def::ExportMap,
154
155     // This flag is an indicator of whether the previous item in the
156     // hierarchical chain was exported or not. This is the indicator of whether
157     // children should be exported as well. Note that this can flip from false
158     // to true if a reexported module is entered (or an action similar).
159     prev_exported: bool,
160
161     // This is a list of all exported items in the AST. An exported item is any
162     // function/method/item which is usable by external crates. This essentially
163     // means that the result is "public all the way down", but the "path down"
164     // may jump across private boundaries through reexport statements.
165     exported_items: ExportedItems,
166
167     // This sets contains all the destination nodes which are publicly
168     // re-exported. This is *not* a set of all reexported nodes, only a set of
169     // all nodes which are reexported *and* reachable from external crates. This
170     // means that the destination of the reexport is exported, and hence the
171     // destination must also be exported.
172     reexports: NodeSet,
173
174     // These two fields are closely related to one another in that they are only
175     // used for generation of the 'PublicItems' set, not for privacy checking at
176     // all
177     public_items: PublicItems,
178     prev_public: bool,
179 }
180
181 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
182     // There are checks inside of privacy which depend on knowing whether a
183     // trait should be exported or not. The two current consumers of this are:
184     //
185     //  1. Should default methods of a trait be exported?
186     //  2. Should the methods of an implementation of a trait be exported?
187     //
188     // The answer to both of these questions partly rely on whether the trait
189     // itself is exported or not. If the trait is somehow exported, then the
190     // answers to both questions must be yes. Right now this question involves
191     // more analysis than is currently done in rustc, so we conservatively
192     // answer "yes" so that all traits need to be exported.
193     fn exported_trait(&self, _id: ast::NodeId) -> bool {
194         true
195     }
196 }
197
198 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
199     fn visit_item(&mut self, item: &hir::Item) {
200         let orig_all_pub = self.prev_public;
201         self.prev_public = orig_all_pub && item.vis == hir::Public;
202         if self.prev_public {
203             self.public_items.insert(item.id);
204         }
205
206         let orig_all_exported = self.prev_exported;
207         match item.node {
208             // impls/extern blocks do not break the "public chain" because they
209             // cannot have visibility qualifiers on them anyway
210             hir::ItemImpl(..) | hir::ItemDefaultImpl(..) | hir::ItemForeignMod(..) => {}
211
212             // Traits are a little special in that even if they themselves are
213             // not public they may still be exported.
214             hir::ItemTrait(..) => {
215                 self.prev_exported = self.exported_trait(item.id);
216             }
217
218             // Private by default, hence we only retain the "public chain" if
219             // `pub` is explicitly listed.
220             _ => {
221                 self.prev_exported =
222                     (orig_all_exported && item.vis == hir::Public) ||
223                      self.reexports.contains(&item.id);
224             }
225         }
226
227         let public_first = self.prev_exported &&
228                            self.exported_items.insert(item.id);
229
230         match item.node {
231             // Enum variants inherit from their parent, so if the enum is
232             // public all variants are public unless they're explicitly priv
233             hir::ItemEnum(ref def, _) if public_first => {
234                 for variant in &def.variants {
235                     self.exported_items.insert(variant.node.id);
236                     self.public_items.insert(variant.node.id);
237                 }
238             }
239
240             // Implementations are a little tricky to determine what's exported
241             // out of them. Here's a few cases which are currently defined:
242             //
243             // * Impls for private types do not need to export their methods
244             //   (either public or private methods)
245             //
246             // * Impls for public types only have public methods exported
247             //
248             // * Public trait impls for public types must have all methods
249             //   exported.
250             //
251             // * Private trait impls for public types can be ignored
252             //
253             // * Public trait impls for private types have their methods
254             //   exported. I'm not entirely certain that this is the correct
255             //   thing to do, but I have seen use cases of where this will cause
256             //   undefined symbols at linkage time if this case is not handled.
257             //
258             // * Private trait impls for private types can be completely ignored
259             hir::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
260                 let public_ty = match ty.node {
261                     hir::TyPath(..) => {
262                         match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
263                             def::DefPrimTy(..) => true,
264                             def => {
265                                 let did = def.def_id();
266                                 !did.is_local() ||
267                                  self.exported_items.contains(&did.node)
268                             }
269                         }
270                     }
271                     _ => true,
272                 };
273                 let tr = self.tcx.impl_trait_ref(DefId::local(item.id));
274                 let public_trait = tr.clone().map_or(false, |tr| {
275                     !tr.def_id.is_local() ||
276                      self.exported_items.contains(&tr.def_id.node)
277                 });
278
279                 if public_ty || public_trait {
280                     for impl_item in impl_items {
281                         match impl_item.node {
282                             hir::ConstImplItem(..) => {
283                                 if (public_ty && impl_item.vis == hir::Public)
284                                     || tr.is_some() {
285                                     self.exported_items.insert(impl_item.id);
286                                 }
287                             }
288                             hir::MethodImplItem(ref sig, _) => {
289                                 let meth_public = match sig.explicit_self.node {
290                                     hir::SelfStatic => public_ty,
291                                     _ => true,
292                                 } && impl_item.vis == hir::Public;
293                                 if meth_public || tr.is_some() {
294                                     self.exported_items.insert(impl_item.id);
295                                 }
296                             }
297                             hir::TypeImplItem(_) => {}
298                         }
299                     }
300                 }
301             }
302
303             // Default methods on traits are all public so long as the trait
304             // is public
305             hir::ItemTrait(_, _, _, ref trait_items) if public_first => {
306                 for trait_item in trait_items {
307                     debug!("trait item {}", trait_item.id);
308                     self.exported_items.insert(trait_item.id);
309                 }
310             }
311
312             // Struct constructors are public if the struct is all public.
313             hir::ItemStruct(ref def, _) if public_first => {
314                 match def.ctor_id {
315                     Some(id) => { self.exported_items.insert(id); }
316                     None => {}
317                 }
318                 // fields can be public or private, so lets check
319                 for field in &def.fields {
320                     let vis = match field.node.kind {
321                         hir::NamedField(_, vis) | hir::UnnamedField(vis) => vis
322                     };
323                     if vis == hir::Public {
324                         self.public_items.insert(field.node.id);
325                     }
326                 }
327             }
328
329             hir::ItemTy(ref ty, _) if public_first => {
330                 if let hir::TyPath(..) = ty.node {
331                     match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
332                         def::DefPrimTy(..) | def::DefTyParam(..) => {},
333                         def => {
334                             let did = def.def_id();
335                             if did.is_local() {
336                                 self.exported_items.insert(did.node);
337                             }
338                         }
339                     }
340                 }
341             }
342
343             _ => {}
344         }
345
346         visit::walk_item(self, item);
347
348         self.prev_exported = orig_all_exported;
349         self.prev_public = orig_all_pub;
350     }
351
352     fn visit_foreign_item(&mut self, a: &hir::ForeignItem) {
353         if (self.prev_exported && a.vis == hir::Public) || self.reexports.contains(&a.id) {
354             self.exported_items.insert(a.id);
355         }
356     }
357
358     fn visit_mod(&mut self, m: &hir::Mod, _sp: Span, id: ast::NodeId) {
359         // This code is here instead of in visit_item so that the
360         // crate module gets processed as well.
361         if self.prev_exported {
362             assert!(self.export_map.contains_key(&id), "wut {}", id);
363             for export in self.export_map.get(&id).unwrap() {
364                 if export.def_id.is_local() {
365                     self.reexports.insert(export.def_id.node);
366                 }
367             }
368         }
369         visit::walk_mod(self, m)
370     }
371 }
372
373 ////////////////////////////////////////////////////////////////////////////////
374 /// The privacy visitor, where privacy checks take place (violations reported)
375 ////////////////////////////////////////////////////////////////////////////////
376
377 struct PrivacyVisitor<'a, 'tcx: 'a> {
378     tcx: &'a ty::ctxt<'tcx>,
379     curitem: ast::NodeId,
380     in_foreign: bool,
381     parents: NodeMap<ast::NodeId>,
382     external_exports: ExternalExports,
383 }
384
385 enum PrivacyResult {
386     Allowable,
387     ExternallyDenied,
388     DisallowedBy(ast::NodeId),
389 }
390
391 enum FieldName {
392     UnnamedField(usize), // index
393     // (Name, not Ident, because struct fields are not macro-hygienic)
394     NamedField(ast::Name),
395 }
396
397 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
398     // used when debugging
399     fn nodestr(&self, id: ast::NodeId) -> String {
400         self.tcx.map.node_to_string(id).to_string()
401     }
402
403     // Determines whether the given definition is public from the point of view
404     // of the current item.
405     fn def_privacy(&self, did: DefId) -> PrivacyResult {
406         if !did.is_local() {
407             if self.external_exports.contains(&did) {
408                 debug!("privacy - {:?} was externally exported", did);
409                 return Allowable;
410             }
411             debug!("privacy - is {:?} a public method", did);
412
413             return match self.tcx.impl_or_trait_items.borrow().get(&did) {
414                 Some(&ty::ConstTraitItem(ref ac)) => {
415                     debug!("privacy - it's a const: {:?}", *ac);
416                     match ac.container {
417                         ty::TraitContainer(id) => {
418                             debug!("privacy - recursing on trait {:?}", id);
419                             self.def_privacy(id)
420                         }
421                         ty::ImplContainer(id) => {
422                             match self.tcx.impl_trait_ref(id) {
423                                 Some(t) => {
424                                     debug!("privacy - impl of trait {:?}", id);
425                                     self.def_privacy(t.def_id)
426                                 }
427                                 None => {
428                                     debug!("privacy - found inherent \
429                                             associated constant {:?}",
430                                             ac.vis);
431                                     if ac.vis == hir::Public {
432                                         Allowable
433                                     } else {
434                                         ExternallyDenied
435                                     }
436                                 }
437                             }
438                         }
439                     }
440                 }
441                 Some(&ty::MethodTraitItem(ref meth)) => {
442                     debug!("privacy - well at least it's a method: {:?}",
443                            *meth);
444                     match meth.container {
445                         ty::TraitContainer(id) => {
446                             debug!("privacy - recursing on trait {:?}", id);
447                             self.def_privacy(id)
448                         }
449                         ty::ImplContainer(id) => {
450                             match self.tcx.impl_trait_ref(id) {
451                                 Some(t) => {
452                                     debug!("privacy - impl of trait {:?}", id);
453                                     self.def_privacy(t.def_id)
454                                 }
455                                 None => {
456                                     debug!("privacy - found a method {:?}",
457                                             meth.vis);
458                                     if meth.vis == hir::Public {
459                                         Allowable
460                                     } else {
461                                         ExternallyDenied
462                                     }
463                                 }
464                             }
465                         }
466                     }
467                 }
468                 Some(&ty::TypeTraitItem(ref typedef)) => {
469                     match typedef.container {
470                         ty::TraitContainer(id) => {
471                             debug!("privacy - recursing on trait {:?}", id);
472                             self.def_privacy(id)
473                         }
474                         ty::ImplContainer(id) => {
475                             match self.tcx.impl_trait_ref(id) {
476                                 Some(t) => {
477                                     debug!("privacy - impl of trait {:?}", id);
478                                     self.def_privacy(t.def_id)
479                                 }
480                                 None => {
481                                     debug!("privacy - found a typedef {:?}",
482                                             typedef.vis);
483                                     if typedef.vis == hir::Public {
484                                         Allowable
485                                     } else {
486                                         ExternallyDenied
487                                     }
488                                 }
489                             }
490                         }
491                     }
492                 }
493                 None => {
494                     debug!("privacy - nope, not even a method");
495                     ExternallyDenied
496                 }
497             };
498         }
499
500         debug!("privacy - local {} not public all the way down",
501                self.tcx.map.node_to_string(did.node));
502         // return quickly for things in the same module
503         if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
504             debug!("privacy - same parent, we're done here");
505             return Allowable;
506         }
507
508         // We now know that there is at least one private member between the
509         // destination and the root.
510         let mut closest_private_id = did.node;
511         loop {
512             debug!("privacy - examining {}", self.nodestr(closest_private_id));
513             let vis = match self.tcx.map.find(closest_private_id) {
514                 // If this item is a method, then we know for sure that it's an
515                 // actual method and not a static method. The reason for this is
516                 // that these cases are only hit in the ExprMethodCall
517                 // expression, and ExprCall will have its path checked later
518                 // (the path of the trait/impl) if it's a static method.
519                 //
520                 // With this information, then we can completely ignore all
521                 // trait methods. The privacy violation would be if the trait
522                 // couldn't get imported, not if the method couldn't be used
523                 // (all trait methods are public).
524                 //
525                 // However, if this is an impl method, then we dictate this
526                 // decision solely based on the privacy of the method
527                 // invocation.
528                 // FIXME(#10573) is this the right behavior? Why not consider
529                 //               where the method was defined?
530                 Some(ast_map::NodeImplItem(ii)) => {
531                     match ii.node {
532                         hir::ConstImplItem(..) |
533                         hir::MethodImplItem(..) => {
534                             let imp = self.tcx.map
535                                           .get_parent_did(closest_private_id);
536                             match self.tcx.impl_trait_ref(imp) {
537                                 Some(..) => return Allowable,
538                                 _ if ii.vis == hir::Public => {
539                                     return Allowable
540                                 }
541                                 _ => ii.vis
542                             }
543                         }
544                         hir::TypeImplItem(_) => return Allowable,
545                     }
546                 }
547                 Some(ast_map::NodeTraitItem(_)) => {
548                     return Allowable;
549                 }
550
551                 // This is not a method call, extract the visibility as one
552                 // would normally look at it
553                 Some(ast_map::NodeItem(it)) => it.vis,
554                 Some(ast_map::NodeForeignItem(_)) => {
555                     self.tcx.map.get_foreign_vis(closest_private_id)
556                 }
557                 Some(ast_map::NodeVariant(..)) => {
558                     hir::Public // need to move up a level (to the enum)
559                 }
560                 _ => hir::Public,
561             };
562             if vis != hir::Public { break }
563             // if we've reached the root, then everything was allowable and this
564             // access is public.
565             if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
566             closest_private_id = *self.parents.get(&closest_private_id).unwrap();
567
568             // If we reached the top, then we were public all the way down and
569             // we can allow this access.
570             if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
571         }
572         debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
573         if self.private_accessible(closest_private_id) {
574             Allowable
575         } else {
576             DisallowedBy(closest_private_id)
577         }
578     }
579
580     /// For a local private node in the AST, this function will determine
581     /// whether the node is accessible by the current module that iteration is
582     /// inside.
583     fn private_accessible(&self, id: ast::NodeId) -> bool {
584         let parent = *self.parents.get(&id).unwrap();
585         debug!("privacy - accessible parent {}", self.nodestr(parent));
586
587         // After finding `did`'s closest private member, we roll ourselves back
588         // to see if this private member's parent is anywhere in our ancestry.
589         // By the privacy rules, we can access all of our ancestor's private
590         // members, so that's why we test the parent, and not the did itself.
591         let mut cur = self.curitem;
592         loop {
593             debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
594             match cur {
595                 // If the relevant parent is in our history, then we're allowed
596                 // to look inside any of our ancestor's immediate private items,
597                 // so this access is valid.
598                 x if x == parent => return true,
599
600                 // If we've reached the root, then we couldn't access this item
601                 // in the first place
602                 ast::DUMMY_NODE_ID => return false,
603
604                 // Keep going up
605                 _ => {}
606             }
607
608             cur = *self.parents.get(&cur).unwrap();
609         }
610     }
611
612     fn report_error(&self, result: CheckResult) -> bool {
613         match result {
614             None => true,
615             Some((span, msg, note)) => {
616                 self.tcx.sess.span_err(span, &msg[..]);
617                 match note {
618                     Some((span, msg)) => {
619                         self.tcx.sess.span_note(span, &msg[..])
620                     }
621                     None => {},
622                 }
623                 false
624             },
625         }
626     }
627
628     /// Guarantee that a particular definition is public. Returns a CheckResult
629     /// which contains any errors found. These can be reported using `report_error`.
630     /// If the result is `None`, no errors were found.
631     fn ensure_public(&self, span: Span, to_check: DefId,
632                      source_did: Option<DefId>, msg: &str) -> CheckResult {
633         let id = match self.def_privacy(to_check) {
634             ExternallyDenied => {
635                 return Some((span, format!("{} is private", msg), None))
636             }
637             Allowable => return None,
638             DisallowedBy(id) => id,
639         };
640
641         // If we're disallowed by a particular id, then we attempt to give a
642         // nice error message to say why it was disallowed. It was either
643         // because the item itself is private or because its parent is private
644         // and its parent isn't in our ancestry.
645         let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
646             return Some((span, format!("{} is private", msg), None));
647         } else {
648             (span, format!("{} is inaccessible", msg))
649         };
650         let item = match self.tcx.map.find(id) {
651             Some(ast_map::NodeItem(item)) => {
652                 match item.node {
653                     // If an impl disallowed this item, then this is resolve's
654                     // way of saying that a struct/enum's static method was
655                     // invoked, and the struct/enum itself is private. Crawl
656                     // back up the chains to find the relevant struct/enum that
657                     // was private.
658                     hir::ItemImpl(_, _, _, _, ref ty, _) => {
659                         match ty.node {
660                             hir::TyPath(..) => {}
661                             _ => return Some((err_span, err_msg, None)),
662                         };
663                         let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
664                         let did = def.def_id();
665                         assert!(did.is_local());
666                         match self.tcx.map.get(did.node) {
667                             ast_map::NodeItem(item) => item,
668                             _ => self.tcx.sess.span_bug(item.span,
669                                                         "path is not an item")
670                         }
671                     }
672                     _ => item
673                 }
674             }
675             Some(..) | None => return Some((err_span, err_msg, None)),
676         };
677         let desc = match item.node {
678             hir::ItemMod(..) => "module",
679             hir::ItemTrait(..) => "trait",
680             hir::ItemStruct(..) => "struct",
681             hir::ItemEnum(..) => "enum",
682             _ => return Some((err_span, err_msg, None))
683         };
684         let msg = format!("{} `{}` is private", desc, item.ident);
685         Some((err_span, err_msg, Some((span, msg))))
686     }
687
688     // Checks that a field is in scope.
689     fn check_field(&mut self,
690                    span: Span,
691                    def: ty::AdtDef<'tcx>,
692                    v: ty::VariantDef<'tcx>,
693                    name: FieldName) {
694         let field = match name {
695             NamedField(f_name) => {
696                 debug!("privacy - check named field {} in struct {:?}", f_name, def);
697                 v.field_named(f_name)
698             }
699             UnnamedField(idx) => &v.fields[idx]
700         };
701         if field.vis == hir::Public ||
702             (field.did.is_local() && self.private_accessible(field.did.node)) {
703             return
704         }
705
706         let struct_desc = match def.adt_kind() {
707             ty::AdtKind::Struct =>
708                 format!("struct `{}`", self.tcx.item_path_str(def.did)),
709             // struct variant fields have inherited visibility
710             ty::AdtKind::Enum => return
711         };
712         let msg = match name {
713             NamedField(name) => format!("field `{}` of {} is private",
714                                         name, struct_desc),
715             UnnamedField(idx) => format!("field #{} of {} is private",
716                                          idx + 1, struct_desc),
717         };
718         self.tcx.sess.span_err(span, &msg[..]);
719     }
720
721     // Given the ID of a method, checks to ensure it's in scope.
722     fn check_static_method(&mut self,
723                            span: Span,
724                            method_id: DefId,
725                            name: ast::Name) {
726         // If the method is a default method, we need to use the def_id of
727         // the default implementation.
728         let method_id = match self.tcx.impl_or_trait_item(method_id) {
729             ty::MethodTraitItem(method_type) => {
730                 method_type.provided_source.unwrap_or(method_id)
731             }
732             _ => {
733                 self.tcx.sess
734                     .span_bug(span,
735                               "got non-method item in check_static_method")
736             }
737         };
738
739         self.report_error(self.ensure_public(span,
740                                              method_id,
741                                              None,
742                                              &format!("method `{}`",
743                                                      name)));
744     }
745
746     // Checks that a path is in scope.
747     fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Name) {
748         debug!("privacy - path {}", self.nodestr(path_id));
749         let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap();
750         let ck = |tyname: &str| {
751             let ck_public = |def: DefId| {
752                 debug!("privacy - ck_public {:?}", def);
753                 let origdid = path_res.def_id();
754                 self.ensure_public(span,
755                                    def,
756                                    Some(origdid),
757                                    &format!("{} `{}`", tyname, last))
758             };
759
760             match path_res.last_private {
761                 LastMod(AllPublic) => {},
762                 LastMod(DependsOn(def)) => {
763                     self.report_error(ck_public(def));
764                 },
765                 LastImport { value_priv,
766                              value_used: check_value,
767                              type_priv,
768                              type_used: check_type } => {
769                     // This dance with found_error is because we don't want to
770                     // report a privacy error twice for the same directive.
771                     let found_error = match (type_priv, check_type) {
772                         (Some(DependsOn(def)), Used) => {
773                             !self.report_error(ck_public(def))
774                         },
775                         _ => false,
776                     };
777                     if !found_error {
778                         match (value_priv, check_value) {
779                             (Some(DependsOn(def)), Used) => {
780                                 self.report_error(ck_public(def));
781                             },
782                             _ => {},
783                         }
784                     }
785                     // If an import is not used in either namespace, we still
786                     // want to check that it could be legal. Therefore we check
787                     // in both namespaces and only report an error if both would
788                     // be illegal. We only report one error, even if it is
789                     // illegal to import from both namespaces.
790                     match (value_priv, check_value, type_priv, check_type) {
791                         (Some(p), Unused, None, _) |
792                         (None, _, Some(p), Unused) => {
793                             let p = match p {
794                                 AllPublic => None,
795                                 DependsOn(def) => ck_public(def),
796                             };
797                             if p.is_some() {
798                                 self.report_error(p);
799                             }
800                         },
801                         (Some(v), Unused, Some(t), Unused) => {
802                             let v = match v {
803                                 AllPublic => None,
804                                 DependsOn(def) => ck_public(def),
805                             };
806                             let t = match t {
807                                 AllPublic => None,
808                                 DependsOn(def) => ck_public(def),
809                             };
810                             if let (Some(_), Some(t)) = (v, t) {
811                                 self.report_error(Some(t));
812                             }
813                         },
814                         _ => {},
815                     }
816                 },
817             }
818         };
819         // FIXME(#12334) Imports can refer to definitions in both the type and
820         // value namespaces. The privacy information is aware of this, but the
821         // def map is not. Therefore the names we work out below will not always
822         // be accurate and we can get slightly wonky error messages (but type
823         // checking is always correct).
824         match path_res.full_def() {
825             def::DefFn(..) => ck("function"),
826             def::DefStatic(..) => ck("static"),
827             def::DefConst(..) => ck("const"),
828             def::DefAssociatedConst(..) => ck("associated const"),
829             def::DefVariant(..) => ck("variant"),
830             def::DefTy(_, false) => ck("type"),
831             def::DefTy(_, true) => ck("enum"),
832             def::DefTrait(..) => ck("trait"),
833             def::DefStruct(..) => ck("struct"),
834             def::DefMethod(..) => ck("method"),
835             def::DefMod(..) => ck("module"),
836             _ => {}
837         }
838     }
839
840     // Checks that a method is in scope.
841     fn check_method(&mut self, span: Span, method_def_id: DefId,
842                     name: ast::Name) {
843         match self.tcx.impl_or_trait_item(method_def_id).container() {
844             ty::ImplContainer(_) => {
845                 self.check_static_method(span, method_def_id, name)
846             }
847             // Trait methods are always all public. The only controlling factor
848             // is whether the trait itself is accessible or not.
849             ty::TraitContainer(trait_def_id) => {
850                 self.report_error(self.ensure_public(span, trait_def_id,
851                                                      None, "source trait"));
852             }
853         }
854     }
855 }
856
857 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
858     fn visit_item(&mut self, item: &hir::Item) {
859         if let hir::ItemUse(ref vpath) = item.node {
860             if let hir::ViewPathList(ref prefix, ref list) = vpath.node {
861                 for pid in list {
862                     match pid.node {
863                         hir::PathListIdent { id, name, .. } => {
864                             debug!("privacy - ident item {}", id);
865                             self.check_path(pid.span, id, name.name);
866                         }
867                         hir::PathListMod { id, .. } => {
868                             debug!("privacy - mod item {}", id);
869                             let name = prefix.segments.last().unwrap().identifier.name;
870                             self.check_path(pid.span, id, name);
871                         }
872                     }
873                 }
874             }
875         }
876         let orig_curitem = replace(&mut self.curitem, item.id);
877         visit::walk_item(self, item);
878         self.curitem = orig_curitem;
879     }
880
881     fn visit_expr(&mut self, expr: &hir::Expr) {
882         match expr.node {
883             hir::ExprField(ref base, ident) => {
884                 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
885                     self.check_field(expr.span,
886                                      def,
887                                      def.struct_variant(),
888                                      NamedField(ident.node.name));
889                 }
890             }
891             hir::ExprTupField(ref base, idx) => {
892                 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
893                     self.check_field(expr.span,
894                                      def,
895                                      def.struct_variant(),
896                                      UnnamedField(idx.node));
897                 }
898             }
899             hir::ExprMethodCall(ident, _, _) => {
900                 let method_call = ty::MethodCall::expr(expr.id);
901                 let method = self.tcx.tables.borrow().method_map[&method_call];
902                 debug!("(privacy checking) checking impl method");
903                 self.check_method(expr.span, method.def_id, ident.node.name);
904             }
905             hir::ExprStruct(..) => {
906                 let adt = self.tcx.expr_ty(expr).ty_adt_def().unwrap();
907                 let variant = adt.variant_of_def(self.tcx.resolve_expr(expr));
908                 // RFC 736: ensure all unmentioned fields are visible.
909                 // Rather than computing the set of unmentioned fields
910                 // (i.e. `all_fields - fields`), just check them all.
911                 for field in &variant.fields {
912                     self.check_field(expr.span, adt, variant, NamedField(field.name));
913                 }
914             }
915             hir::ExprPath(..) => {
916
917                 if let def::DefStruct(_) = self.tcx.resolve_expr(expr) {
918                     let expr_ty = self.tcx.expr_ty(expr);
919                     let def = match expr_ty.sty {
920                         ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
921                             output: ty::FnConverging(ty), ..
922                         }), ..}) => ty,
923                         _ => expr_ty
924                     }.ty_adt_def().unwrap();
925                     let any_priv = def.struct_variant().fields.iter().any(|f| {
926                         f.vis != hir::Public && (
927                             !f.did.is_local() ||
928                                     !self.private_accessible(f.did.node))
929                         });
930
931                     if any_priv {
932                         self.tcx.sess.span_err(expr.span,
933                                                "cannot invoke tuple struct constructor \
934                                                 with private fields");
935                     }
936                 }
937             }
938             _ => {}
939         }
940
941         visit::walk_expr(self, expr);
942     }
943
944     fn visit_pat(&mut self, pattern: &hir::Pat) {
945         // Foreign functions do not have their patterns mapped in the def_map,
946         // and there's nothing really relevant there anyway, so don't bother
947         // checking privacy. If you can name the type then you can pass it to an
948         // external C function anyway.
949         if self.in_foreign { return }
950
951         match pattern.node {
952             hir::PatStruct(_, ref fields, _) => {
953                 let adt = self.tcx.pat_ty(pattern).ty_adt_def().unwrap();
954                 let def = self.tcx.def_map.borrow().get(&pattern.id).unwrap().full_def();
955                 let variant = adt.variant_of_def(def);
956                 for field in fields {
957                     self.check_field(pattern.span, adt, variant,
958                                      NamedField(field.node.ident.name));
959                 }
960             }
961
962             // Patterns which bind no fields are allowable (the path is check
963             // elsewhere).
964             hir::PatEnum(_, Some(ref fields)) => {
965                 match self.tcx.pat_ty(pattern).sty {
966                     ty::TyStruct(def, _) => {
967                         for (i, field) in fields.iter().enumerate() {
968                             if let hir::PatWild(..) = field.node {
969                                 continue
970                             }
971                             self.check_field(field.span,
972                                              def,
973                                              def.struct_variant(),
974                                              UnnamedField(i));
975                         }
976                     }
977                     ty::TyEnum(..) => {
978                         // enum fields have no privacy at this time
979                     }
980                     _ => {}
981                 }
982
983             }
984             _ => {}
985         }
986
987         visit::walk_pat(self, pattern);
988     }
989
990     fn visit_foreign_item(&mut self, fi: &hir::ForeignItem) {
991         self.in_foreign = true;
992         visit::walk_foreign_item(self, fi);
993         self.in_foreign = false;
994     }
995
996     fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
997         self.check_path(path.span, id, path.segments.last().unwrap().identifier.name);
998         visit::walk_path(self, path);
999     }
1000 }
1001
1002 ////////////////////////////////////////////////////////////////////////////////
1003 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1004 ////////////////////////////////////////////////////////////////////////////////
1005
1006 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1007     tcx: &'a ty::ctxt<'tcx>,
1008     in_fn: bool,
1009 }
1010
1011 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1012     fn visit_item(&mut self, item: &hir::Item) {
1013         if self.in_fn {
1014             self.check_all_inherited(item);
1015         } else {
1016             self.check_sane_privacy(item);
1017         }
1018
1019         let in_fn = self.in_fn;
1020         let orig_in_fn = replace(&mut self.in_fn, match item.node {
1021             hir::ItemMod(..) => false, // modules turn privacy back on
1022             _ => in_fn,           // otherwise we inherit
1023         });
1024         visit::walk_item(self, item);
1025         self.in_fn = orig_in_fn;
1026     }
1027
1028     fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v hir::FnDecl,
1029                 b: &'v hir::Block, s: Span, _: ast::NodeId) {
1030         // This catches both functions and methods
1031         let orig_in_fn = replace(&mut self.in_fn, true);
1032         visit::walk_fn(self, fk, fd, b, s);
1033         self.in_fn = orig_in_fn;
1034     }
1035 }
1036
1037 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1038     /// Validates all of the visibility qualifiers placed on the item given. This
1039     /// ensures that there are no extraneous qualifiers that don't actually do
1040     /// anything. In theory these qualifiers wouldn't parse, but that may happen
1041     /// later on down the road...
1042     fn check_sane_privacy(&self, item: &hir::Item) {
1043         let tcx = self.tcx;
1044         let check_inherited = |sp: Span, vis: hir::Visibility, note: &str| {
1045             if vis != hir::Inherited {
1046                 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1047                 if !note.is_empty() {
1048                     tcx.sess.span_note(sp, note);
1049                 }
1050             }
1051         };
1052         match item.node {
1053             // implementations of traits don't need visibility qualifiers because
1054             // that's controlled by having the trait in scope.
1055             hir::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1056                 check_inherited(item.span, item.vis,
1057                                 "visibility qualifiers have no effect on trait \
1058                                  impls");
1059                 for impl_item in impl_items {
1060                     check_inherited(impl_item.span, impl_item.vis, "");
1061                 }
1062             }
1063
1064             hir::ItemImpl(..) => {
1065                 check_inherited(item.span, item.vis,
1066                                 "place qualifiers on individual methods instead");
1067             }
1068             hir::ItemForeignMod(..) => {
1069                 check_inherited(item.span, item.vis,
1070                                 "place qualifiers on individual functions \
1071                                  instead");
1072             }
1073
1074             hir::ItemEnum(ref def, _) => {
1075                 for v in &def.variants {
1076                     match v.node.vis {
1077                         hir::Public => {
1078                             if item.vis == hir::Public {
1079                                 tcx.sess.span_err(v.span, "unnecessary `pub` \
1080                                                            visibility");
1081                             }
1082                         }
1083                         hir::Inherited => {}
1084                     }
1085                 }
1086             }
1087
1088             hir::ItemTrait(..) | hir::ItemDefaultImpl(..) |
1089             hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemStruct(..) |
1090             hir::ItemFn(..) | hir::ItemMod(..) | hir::ItemTy(..) |
1091             hir::ItemExternCrate(_) | hir::ItemUse(_) => {}
1092         }
1093     }
1094
1095     /// When inside of something like a function or a method, visibility has no
1096     /// control over anything so this forbids any mention of any visibility
1097     fn check_all_inherited(&self, item: &hir::Item) {
1098         let tcx = self.tcx;
1099         fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: hir::Visibility) {
1100             if vis != hir::Inherited {
1101                 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1102             }
1103         }
1104         let check_struct = |def: &hir::StructDef| {
1105             for f in &def.fields {
1106                match f.node.kind {
1107                     hir::NamedField(_, p) => check_inherited(tcx, f.span, p),
1108                     hir::UnnamedField(..) => {}
1109                 }
1110             }
1111         };
1112         check_inherited(tcx, item.span, item.vis);
1113         match item.node {
1114             hir::ItemImpl(_, _, _, _, _, ref impl_items) => {
1115                 for impl_item in impl_items {
1116                     match impl_item.node {
1117                         hir::MethodImplItem(..) => {
1118                             check_inherited(tcx, impl_item.span, impl_item.vis);
1119                         }
1120                         _ => {}
1121                     }
1122                 }
1123             }
1124             hir::ItemForeignMod(ref fm) => {
1125                 for i in &fm.items {
1126                     check_inherited(tcx, i.span, i.vis);
1127                 }
1128             }
1129             hir::ItemEnum(ref def, _) => {
1130                 for v in &def.variants {
1131                     check_inherited(tcx, v.span, v.node.vis);
1132                 }
1133             }
1134
1135             hir::ItemStruct(ref def, _) => check_struct(&**def),
1136
1137             hir::ItemExternCrate(_) | hir::ItemUse(_) |
1138             hir::ItemTrait(..) | hir::ItemDefaultImpl(..) |
1139             hir::ItemStatic(..) | hir::ItemConst(..) |
1140             hir::ItemFn(..) | hir::ItemMod(..) | hir::ItemTy(..) => {}
1141         }
1142     }
1143 }
1144
1145 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1146     tcx: &'a ty::ctxt<'tcx>,
1147     exported_items: &'a ExportedItems,
1148     public_items: &'a PublicItems,
1149     in_variant: bool,
1150 }
1151
1152 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1153     inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1154     /// whether the type refers to private types.
1155     contains_private: bool,
1156     /// whether we've recurred at all (i.e. if we're pointing at the
1157     /// first type on which visit_ty was called).
1158     at_outer_type: bool,
1159     // whether that first type is a public path.
1160     outer_type_is_public_path: bool,
1161 }
1162
1163 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1164     fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1165         let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) {
1166             // `int` etc. (None doesn't seem to occur.)
1167             None | Some(def::DefPrimTy(..)) => return false,
1168             Some(def) => def.def_id(),
1169         };
1170         // A path can only be private if:
1171         // it's in this crate...
1172         if !did.is_local() {
1173             return false
1174         }
1175
1176         // .. and it corresponds to a private type in the AST (this returns
1177         // None for type parameters)
1178         match self.tcx.map.find(did.node) {
1179             Some(ast_map::NodeItem(ref item)) => item.vis != hir::Public,
1180             Some(_) | None => false,
1181         }
1182     }
1183
1184     fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1185         // FIXME: this would preferably be using `exported_items`, but all
1186         // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1187         self.public_items.contains(&trait_id)
1188     }
1189
1190     fn check_ty_param_bound(&self,
1191                             ty_param_bound: &hir::TyParamBound) {
1192         if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1193             if !self.tcx.sess.features.borrow().visible_private_types &&
1194                 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1195                     let span = trait_ref.trait_ref.path.span;
1196                     self.tcx.sess.span_err(span, "private trait in exported type \
1197                                                   parameter bound");
1198             }
1199         }
1200     }
1201
1202     fn item_is_public(&self, id: &ast::NodeId, vis: hir::Visibility) -> bool {
1203         self.exported_items.contains(id) || vis == hir::Public
1204     }
1205 }
1206
1207 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1208     fn visit_ty(&mut self, ty: &hir::Ty) {
1209         if let hir::TyPath(..) = ty.node {
1210             if self.inner.path_is_private_type(ty.id) {
1211                 self.contains_private = true;
1212                 // found what we're looking for so let's stop
1213                 // working.
1214                 return
1215             } else if self.at_outer_type {
1216                 self.outer_type_is_public_path = true;
1217             }
1218         }
1219         self.at_outer_type = false;
1220         visit::walk_ty(self, ty)
1221     }
1222
1223     // don't want to recurse into [, .. expr]
1224     fn visit_expr(&mut self, _: &hir::Expr) {}
1225 }
1226
1227 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1228     fn visit_item(&mut self, item: &hir::Item) {
1229         match item.node {
1230             // contents of a private mod can be reexported, so we need
1231             // to check internals.
1232             hir::ItemMod(_) => {}
1233
1234             // An `extern {}` doesn't introduce a new privacy
1235             // namespace (the contents have their own privacies).
1236             hir::ItemForeignMod(_) => {}
1237
1238             hir::ItemTrait(_, _, ref bounds, _) => {
1239                 if !self.trait_is_public(item.id) {
1240                     return
1241                 }
1242
1243                 for bound in bounds.iter() {
1244                     self.check_ty_param_bound(bound)
1245                 }
1246             }
1247
1248             // impls need some special handling to try to offer useful
1249             // error messages without (too many) false positives
1250             // (i.e. we could just return here to not check them at
1251             // all, or some worse estimation of whether an impl is
1252             // publicly visible).
1253             hir::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1254                 // `impl [... for] Private` is never visible.
1255                 let self_contains_private;
1256                 // impl [... for] Public<...>, but not `impl [... for]
1257                 // Vec<Public>` or `(Public,)` etc.
1258                 let self_is_public_path;
1259
1260                 // check the properties of the Self type:
1261                 {
1262                     let mut visitor = CheckTypeForPrivatenessVisitor {
1263                         inner: self,
1264                         contains_private: false,
1265                         at_outer_type: true,
1266                         outer_type_is_public_path: false,
1267                     };
1268                     visitor.visit_ty(&**self_);
1269                     self_contains_private = visitor.contains_private;
1270                     self_is_public_path = visitor.outer_type_is_public_path;
1271                 }
1272
1273                 // miscellaneous info about the impl
1274
1275                 // `true` iff this is `impl Private for ...`.
1276                 let not_private_trait =
1277                     trait_ref.as_ref().map_or(true, // no trait counts as public trait
1278                                               |tr| {
1279                         let did = self.tcx.trait_ref_to_def_id(tr);
1280
1281                         !did.is_local() || self.trait_is_public(did.node)
1282                     });
1283
1284                 // `true` iff this is a trait impl or at least one method is public.
1285                 //
1286                 // `impl Public { $( fn ...() {} )* }` is not visible.
1287                 //
1288                 // This is required over just using the methods' privacy
1289                 // directly because we might have `impl<T: Foo<Private>> ...`,
1290                 // and we shouldn't warn about the generics if all the methods
1291                 // are private (because `T` won't be visible externally).
1292                 let trait_or_some_public_method =
1293                     trait_ref.is_some() ||
1294                     impl_items.iter()
1295                               .any(|impl_item| {
1296                                   match impl_item.node {
1297                                       hir::ConstImplItem(..) |
1298                                       hir::MethodImplItem(..) => {
1299                                           self.exported_items.contains(&impl_item.id)
1300                                       }
1301                                       hir::TypeImplItem(_) => false,
1302                                   }
1303                               });
1304
1305                 if !self_contains_private &&
1306                         not_private_trait &&
1307                         trait_or_some_public_method {
1308
1309                     visit::walk_generics(self, g);
1310
1311                     match *trait_ref {
1312                         None => {
1313                             for impl_item in impl_items {
1314                                 // This is where we choose whether to walk down
1315                                 // further into the impl to check its items. We
1316                                 // should only walk into public items so that we
1317                                 // don't erroneously report errors for private
1318                                 // types in private items.
1319                                 match impl_item.node {
1320                                     hir::ConstImplItem(..) |
1321                                     hir::MethodImplItem(..)
1322                                         if self.item_is_public(&impl_item.id, impl_item.vis) =>
1323                                     {
1324                                         visit::walk_impl_item(self, impl_item)
1325                                     }
1326                                     hir::TypeImplItem(..) => {
1327                                         visit::walk_impl_item(self, impl_item)
1328                                     }
1329                                     _ => {}
1330                                 }
1331                             }
1332                         }
1333                         Some(ref tr) => {
1334                             // Any private types in a trait impl fall into three
1335                             // categories.
1336                             // 1. mentioned in the trait definition
1337                             // 2. mentioned in the type params/generics
1338                             // 3. mentioned in the associated types of the impl
1339                             //
1340                             // Those in 1. can only occur if the trait is in
1341                             // this crate and will've been warned about on the
1342                             // trait definition (there's no need to warn twice
1343                             // so we don't check the methods).
1344                             //
1345                             // Those in 2. are warned via walk_generics and this
1346                             // call here.
1347                             visit::walk_path(self, &tr.path);
1348
1349                             // Those in 3. are warned with this call.
1350                             for impl_item in impl_items {
1351                                 if let hir::TypeImplItem(ref ty) = impl_item.node {
1352                                     self.visit_ty(ty);
1353                                 }
1354                             }
1355                         }
1356                     }
1357                 } else if trait_ref.is_none() && self_is_public_path {
1358                     // impl Public<Private> { ... }. Any public static
1359                     // methods will be visible as `Public::foo`.
1360                     let mut found_pub_static = false;
1361                     for impl_item in impl_items {
1362                         match impl_item.node {
1363                             hir::ConstImplItem(..) => {
1364                                 if self.item_is_public(&impl_item.id, impl_item.vis) {
1365                                     found_pub_static = true;
1366                                     visit::walk_impl_item(self, impl_item);
1367                                 }
1368                             }
1369                             hir::MethodImplItem(ref sig, _) => {
1370                                 if sig.explicit_self.node == hir::SelfStatic &&
1371                                       self.item_is_public(&impl_item.id, impl_item.vis) {
1372                                     found_pub_static = true;
1373                                     visit::walk_impl_item(self, impl_item);
1374                                 }
1375                             }
1376                             _ => {}
1377                         }
1378                     }
1379                     if found_pub_static {
1380                         visit::walk_generics(self, g)
1381                     }
1382                 }
1383                 return
1384             }
1385
1386             // `type ... = ...;` can contain private types, because
1387             // we're introducing a new name.
1388             hir::ItemTy(..) => return,
1389
1390             // not at all public, so we don't care
1391             _ if !self.item_is_public(&item.id, item.vis) => {
1392                 return;
1393             }
1394
1395             _ => {}
1396         }
1397
1398         // We've carefully constructed it so that if we're here, then
1399         // any `visit_ty`'s will be called on things that are in
1400         // public signatures, i.e. things that we're interested in for
1401         // this visitor.
1402         debug!("VisiblePrivateTypesVisitor entering item {:?}", item);
1403         visit::walk_item(self, item);
1404     }
1405
1406     fn visit_generics(&mut self, generics: &hir::Generics) {
1407         for ty_param in generics.ty_params.iter() {
1408             for bound in ty_param.bounds.iter() {
1409                 self.check_ty_param_bound(bound)
1410             }
1411         }
1412         for predicate in &generics.where_clause.predicates {
1413             match predicate {
1414                 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1415                     for bound in bound_pred.bounds.iter() {
1416                         self.check_ty_param_bound(bound)
1417                     }
1418                 }
1419                 &hir::WherePredicate::RegionPredicate(_) => {}
1420                 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1421                     self.visit_ty(&*eq_pred.ty);
1422                 }
1423             }
1424         }
1425     }
1426
1427     fn visit_foreign_item(&mut self, item: &hir::ForeignItem) {
1428         if self.exported_items.contains(&item.id) {
1429             visit::walk_foreign_item(self, item)
1430         }
1431     }
1432
1433     fn visit_ty(&mut self, t: &hir::Ty) {
1434         debug!("VisiblePrivateTypesVisitor checking ty {:?}", t);
1435         if let hir::TyPath(_, ref p) = t.node {
1436             if !self.tcx.sess.features.borrow().visible_private_types &&
1437                 self.path_is_private_type(t.id) {
1438                 self.tcx.sess.span_err(p.span, "private type in exported type signature");
1439             }
1440         }
1441         visit::walk_ty(self, t)
1442     }
1443
1444     fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics) {
1445         if self.exported_items.contains(&v.node.id) {
1446             self.in_variant = true;
1447             visit::walk_variant(self, v, g);
1448             self.in_variant = false;
1449         }
1450     }
1451
1452     fn visit_struct_field(&mut self, s: &hir::StructField) {
1453         match s.node.kind {
1454             hir::NamedField(_, vis) if vis == hir::Public || self.in_variant => {
1455                 visit::walk_struct_field(self, s);
1456             }
1457             _ => {}
1458         }
1459     }
1460
1461
1462     // we don't need to introspect into these at all: an
1463     // expression/block context can't possibly contain exported things.
1464     // (Making them no-ops stops us from traversing the whole AST without
1465     // having to be super careful about our `walk_...` calls above.)
1466     fn visit_block(&mut self, _: &hir::Block) {}
1467     fn visit_expr(&mut self, _: &hir::Expr) {}
1468 }
1469
1470 pub fn check_crate(tcx: &ty::ctxt,
1471                    export_map: &def::ExportMap,
1472                    external_exports: ExternalExports)
1473                    -> (ExportedItems, PublicItems) {
1474     let krate = tcx.map.krate();
1475
1476     // Figure out who everyone's parent is
1477     let mut visitor = ParentVisitor {
1478         parents: NodeMap(),
1479         curparent: ast::DUMMY_NODE_ID,
1480     };
1481     visit::walk_crate(&mut visitor, krate);
1482
1483     // Use the parent map to check the privacy of everything
1484     let mut visitor = PrivacyVisitor {
1485         curitem: ast::DUMMY_NODE_ID,
1486         in_foreign: false,
1487         tcx: tcx,
1488         parents: visitor.parents,
1489         external_exports: external_exports,
1490     };
1491     visit::walk_crate(&mut visitor, krate);
1492
1493     // Sanity check to make sure that all privacy usage and controls are
1494     // reasonable.
1495     let mut visitor = SanePrivacyVisitor {
1496         in_fn: false,
1497         tcx: tcx,
1498     };
1499     visit::walk_crate(&mut visitor, krate);
1500
1501     tcx.sess.abort_if_errors();
1502
1503     // Build up a set of all exported items in the AST. This is a set of all
1504     // items which are reachable from external crates based on visibility.
1505     let mut visitor = EmbargoVisitor {
1506         tcx: tcx,
1507         exported_items: NodeSet(),
1508         public_items: NodeSet(),
1509         reexports: NodeSet(),
1510         export_map: export_map,
1511         prev_exported: true,
1512         prev_public: true,
1513     };
1514     loop {
1515         let before = visitor.exported_items.len();
1516         visit::walk_crate(&mut visitor, krate);
1517         if before == visitor.exported_items.len() {
1518             break
1519         }
1520     }
1521
1522     let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1523
1524     {
1525         let mut visitor = VisiblePrivateTypesVisitor {
1526             tcx: tcx,
1527             exported_items: &exported_items,
1528             public_items: &public_items,
1529             in_variant: false,
1530         };
1531         visit::walk_crate(&mut visitor, krate);
1532     }
1533     return (exported_items, public_items);
1534 }