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