]> git.lizzy.rs Git - rust.git/blob - src/librustc_privacy/lib.rs
Auto merge of #28780 - steveklabnik:doc_from_str, r=alexcrichton
[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::Name,
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     NamedField(ast::Name),
396 }
397
398 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
399     // used when debugging
400     fn nodestr(&self, id: ast::NodeId) -> String {
401         self.tcx.map.node_to_string(id).to_string()
402     }
403
404     // Determines whether the given definition is public from the point of view
405     // of the current item.
406     fn def_privacy(&self, did: DefId) -> PrivacyResult {
407         if !did.is_local() {
408             if self.external_exports.contains(&did) {
409                 debug!("privacy - {:?} was externally exported", did);
410                 return Allowable;
411             }
412             debug!("privacy - is {:?} a public method", did);
413
414             return match self.tcx.impl_or_trait_items.borrow().get(&did) {
415                 Some(&ty::ConstTraitItem(ref ac)) => {
416                     debug!("privacy - it's a const: {:?}", *ac);
417                     match ac.container {
418                         ty::TraitContainer(id) => {
419                             debug!("privacy - recursing on trait {:?}", id);
420                             self.def_privacy(id)
421                         }
422                         ty::ImplContainer(id) => {
423                             match self.tcx.impl_trait_ref(id) {
424                                 Some(t) => {
425                                     debug!("privacy - impl of trait {:?}", id);
426                                     self.def_privacy(t.def_id)
427                                 }
428                                 None => {
429                                     debug!("privacy - found inherent \
430                                             associated constant {:?}",
431                                             ac.vis);
432                                     if ac.vis == hir::Public {
433                                         Allowable
434                                     } else {
435                                         ExternallyDenied
436                                     }
437                                 }
438                             }
439                         }
440                     }
441                 }
442                 Some(&ty::MethodTraitItem(ref meth)) => {
443                     debug!("privacy - well at least it's a method: {:?}",
444                            *meth);
445                     match meth.container {
446                         ty::TraitContainer(id) => {
447                             debug!("privacy - recursing on trait {:?}", id);
448                             self.def_privacy(id)
449                         }
450                         ty::ImplContainer(id) => {
451                             match self.tcx.impl_trait_ref(id) {
452                                 Some(t) => {
453                                     debug!("privacy - impl of trait {:?}", id);
454                                     self.def_privacy(t.def_id)
455                                 }
456                                 None => {
457                                     debug!("privacy - found a method {:?}",
458                                             meth.vis);
459                                     if meth.vis == hir::Public {
460                                         Allowable
461                                     } else {
462                                         ExternallyDenied
463                                     }
464                                 }
465                             }
466                         }
467                     }
468                 }
469                 Some(&ty::TypeTraitItem(ref typedef)) => {
470                     match typedef.container {
471                         ty::TraitContainer(id) => {
472                             debug!("privacy - recursing on trait {:?}", id);
473                             self.def_privacy(id)
474                         }
475                         ty::ImplContainer(id) => {
476                             match self.tcx.impl_trait_ref(id) {
477                                 Some(t) => {
478                                     debug!("privacy - impl of trait {:?}", id);
479                                     self.def_privacy(t.def_id)
480                                 }
481                                 None => {
482                                     debug!("privacy - found a typedef {:?}",
483                                             typedef.vis);
484                                     if typedef.vis == hir::Public {
485                                         Allowable
486                                     } else {
487                                         ExternallyDenied
488                                     }
489                                 }
490                             }
491                         }
492                     }
493                 }
494                 None => {
495                     debug!("privacy - nope, not even a method");
496                     ExternallyDenied
497                 }
498             };
499         }
500
501         debug!("privacy - local {} not public all the way down",
502                self.tcx.map.node_to_string(did.node));
503         // return quickly for things in the same module
504         if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
505             debug!("privacy - same parent, we're done here");
506             return Allowable;
507         }
508
509         // We now know that there is at least one private member between the
510         // destination and the root.
511         let mut closest_private_id = did.node;
512         loop {
513             debug!("privacy - examining {}", self.nodestr(closest_private_id));
514             let vis = match self.tcx.map.find(closest_private_id) {
515                 // If this item is a method, then we know for sure that it's an
516                 // actual method and not a static method. The reason for this is
517                 // that these cases are only hit in the ExprMethodCall
518                 // expression, and ExprCall will have its path checked later
519                 // (the path of the trait/impl) if it's a static method.
520                 //
521                 // With this information, then we can completely ignore all
522                 // trait methods. The privacy violation would be if the trait
523                 // couldn't get imported, not if the method couldn't be used
524                 // (all trait methods are public).
525                 //
526                 // However, if this is an impl method, then we dictate this
527                 // decision solely based on the privacy of the method
528                 // invocation.
529                 // FIXME(#10573) is this the right behavior? Why not consider
530                 //               where the method was defined?
531                 Some(ast_map::NodeImplItem(ii)) => {
532                     match ii.node {
533                         hir::ConstImplItem(..) |
534                         hir::MethodImplItem(..) => {
535                             let imp = self.tcx.map
536                                           .get_parent_did(closest_private_id);
537                             match self.tcx.impl_trait_ref(imp) {
538                                 Some(..) => return Allowable,
539                                 _ if ii.vis == hir::Public => {
540                                     return Allowable
541                                 }
542                                 _ => ii.vis
543                             }
544                         }
545                         hir::TypeImplItem(_) => return Allowable,
546                     }
547                 }
548                 Some(ast_map::NodeTraitItem(_)) => {
549                     return Allowable;
550                 }
551
552                 // This is not a method call, extract the visibility as one
553                 // would normally look at it
554                 Some(ast_map::NodeItem(it)) => it.vis,
555                 Some(ast_map::NodeForeignItem(_)) => {
556                     self.tcx.map.get_foreign_vis(closest_private_id)
557                 }
558                 Some(ast_map::NodeVariant(..)) => {
559                     hir::Public // need to move up a level (to the enum)
560                 }
561                 _ => hir::Public,
562             };
563             if vis != hir::Public { break }
564             // if we've reached the root, then everything was allowable and this
565             // access is public.
566             if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
567             closest_private_id = *self.parents.get(&closest_private_id).unwrap();
568
569             // If we reached the top, then we were public all the way down and
570             // we can allow this access.
571             if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
572         }
573         debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
574         if self.private_accessible(closest_private_id) {
575             Allowable
576         } else {
577             DisallowedBy(closest_private_id)
578         }
579     }
580
581     /// For a local private node in the AST, this function will determine
582     /// whether the node is accessible by the current module that iteration is
583     /// inside.
584     fn private_accessible(&self, id: ast::NodeId) -> bool {
585         let parent = *self.parents.get(&id).unwrap();
586         debug!("privacy - accessible parent {}", self.nodestr(parent));
587
588         // After finding `did`'s closest private member, we roll ourselves back
589         // to see if this private member's parent is anywhere in our ancestry.
590         // By the privacy rules, we can access all of our ancestor's private
591         // members, so that's why we test the parent, and not the did itself.
592         let mut cur = self.curitem;
593         loop {
594             debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
595             match cur {
596                 // If the relevant parent is in our history, then we're allowed
597                 // to look inside any of our ancestor's immediate private items,
598                 // so this access is valid.
599                 x if x == parent => return true,
600
601                 // If we've reached the root, then we couldn't access this item
602                 // in the first place
603                 ast::DUMMY_NODE_ID => return false,
604
605                 // Keep going up
606                 _ => {}
607             }
608
609             cur = *self.parents.get(&cur).unwrap();
610         }
611     }
612
613     fn report_error(&self, result: CheckResult) -> bool {
614         match result {
615             None => true,
616             Some((span, msg, note)) => {
617                 self.tcx.sess.span_err(span, &msg[..]);
618                 match note {
619                     Some((span, msg)) => {
620                         self.tcx.sess.span_note(span, &msg[..])
621                     }
622                     None => {},
623                 }
624                 false
625             },
626         }
627     }
628
629     /// Guarantee that a particular definition is public. Returns a CheckResult
630     /// which contains any errors found. These can be reported using `report_error`.
631     /// If the result is `None`, no errors were found.
632     fn ensure_public(&self, span: Span, to_check: DefId,
633                      source_did: Option<DefId>, msg: &str) -> CheckResult {
634         let id = match self.def_privacy(to_check) {
635             ExternallyDenied => {
636                 return Some((span, format!("{} is private", msg), None))
637             }
638             Allowable => return None,
639             DisallowedBy(id) => id,
640         };
641
642         // If we're disallowed by a particular id, then we attempt to give a
643         // nice error message to say why it was disallowed. It was either
644         // because the item itself is private or because its parent is private
645         // and its parent isn't in our ancestry.
646         let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
647             return Some((span, format!("{} is private", msg), None));
648         } else {
649             (span, format!("{} is inaccessible", msg))
650         };
651         let item = match self.tcx.map.find(id) {
652             Some(ast_map::NodeItem(item)) => {
653                 match item.node {
654                     // If an impl disallowed this item, then this is resolve's
655                     // way of saying that a struct/enum's static method was
656                     // invoked, and the struct/enum itself is private. Crawl
657                     // back up the chains to find the relevant struct/enum that
658                     // was private.
659                     hir::ItemImpl(_, _, _, _, ref ty, _) => {
660                         match ty.node {
661                             hir::TyPath(..) => {}
662                             _ => return Some((err_span, err_msg, None)),
663                         };
664                         let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
665                         let did = def.def_id();
666                         assert!(did.is_local());
667                         match self.tcx.map.get(did.node) {
668                             ast_map::NodeItem(item) => item,
669                             _ => self.tcx.sess.span_bug(item.span,
670                                                         "path is not an item")
671                         }
672                     }
673                     _ => item
674                 }
675             }
676             Some(..) | None => return Some((err_span, err_msg, None)),
677         };
678         let desc = match item.node {
679             hir::ItemMod(..) => "module",
680             hir::ItemTrait(..) => "trait",
681             hir::ItemStruct(..) => "struct",
682             hir::ItemEnum(..) => "enum",
683             _ => return Some((err_span, err_msg, None))
684         };
685         let msg = format!("{} `{}` is private", desc, item.name);
686         Some((err_span, err_msg, Some((span, msg))))
687     }
688
689     // Checks that a field is in scope.
690     fn check_field(&mut self,
691                    span: Span,
692                    def: ty::AdtDef<'tcx>,
693                    v: ty::VariantDef<'tcx>,
694                    name: FieldName) {
695         let field = match name {
696             NamedField(f_name) => {
697                 debug!("privacy - check named field {} in struct {:?}", f_name, def);
698                 v.field_named(f_name)
699             }
700             UnnamedField(idx) => &v.fields[idx]
701         };
702         if field.vis == hir::Public ||
703             (field.did.is_local() && self.private_accessible(field.did.node)) {
704             return
705         }
706
707         let struct_desc = match def.adt_kind() {
708             ty::AdtKind::Struct =>
709                 format!("struct `{}`", self.tcx.item_path_str(def.did)),
710             // struct variant fields have inherited visibility
711             ty::AdtKind::Enum => return
712         };
713         let msg = match name {
714             NamedField(name) => format!("field `{}` of {} is private",
715                                         name, struct_desc),
716             UnnamedField(idx) => format!("field #{} of {} is private",
717                                          idx + 1, struct_desc),
718         };
719         span_err!(self.tcx.sess, span, E0451,
720                   "{}", &msg[..]);
721     }
722
723     // Given the ID of a method, checks to ensure it's in scope.
724     fn check_static_method(&mut self,
725                            span: Span,
726                            method_id: DefId,
727                            name: ast::Name) {
728         self.report_error(self.ensure_public(span,
729                                              method_id,
730                                              None,
731                                              &format!("method `{}`",
732                                                      name)));
733     }
734
735     // Checks that a path is in scope.
736     fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Name) {
737         debug!("privacy - path {}", self.nodestr(path_id));
738         let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap();
739         let ck = |tyname: &str| {
740             let ck_public = |def: DefId| {
741                 debug!("privacy - ck_public {:?}", def);
742                 let origdid = path_res.def_id();
743                 self.ensure_public(span,
744                                    def,
745                                    Some(origdid),
746                                    &format!("{} `{}`", tyname, last))
747             };
748
749             match path_res.last_private {
750                 LastMod(AllPublic) => {},
751                 LastMod(DependsOn(def)) => {
752                     self.report_error(ck_public(def));
753                 },
754                 LastImport { value_priv,
755                              value_used: check_value,
756                              type_priv,
757                              type_used: check_type } => {
758                     // This dance with found_error is because we don't want to
759                     // report a privacy error twice for the same directive.
760                     let found_error = match (type_priv, check_type) {
761                         (Some(DependsOn(def)), Used) => {
762                             !self.report_error(ck_public(def))
763                         },
764                         _ => false,
765                     };
766                     if !found_error {
767                         match (value_priv, check_value) {
768                             (Some(DependsOn(def)), Used) => {
769                                 self.report_error(ck_public(def));
770                             },
771                             _ => {},
772                         }
773                     }
774                     // If an import is not used in either namespace, we still
775                     // want to check that it could be legal. Therefore we check
776                     // in both namespaces and only report an error if both would
777                     // be illegal. We only report one error, even if it is
778                     // illegal to import from both namespaces.
779                     match (value_priv, check_value, type_priv, check_type) {
780                         (Some(p), Unused, None, _) |
781                         (None, _, Some(p), Unused) => {
782                             let p = match p {
783                                 AllPublic => None,
784                                 DependsOn(def) => ck_public(def),
785                             };
786                             if p.is_some() {
787                                 self.report_error(p);
788                             }
789                         },
790                         (Some(v), Unused, Some(t), Unused) => {
791                             let v = match v {
792                                 AllPublic => None,
793                                 DependsOn(def) => ck_public(def),
794                             };
795                             let t = match t {
796                                 AllPublic => None,
797                                 DependsOn(def) => ck_public(def),
798                             };
799                             if let (Some(_), Some(t)) = (v, t) {
800                                 self.report_error(Some(t));
801                             }
802                         },
803                         _ => {},
804                     }
805                 },
806             }
807         };
808         // FIXME(#12334) Imports can refer to definitions in both the type and
809         // value namespaces. The privacy information is aware of this, but the
810         // def map is not. Therefore the names we work out below will not always
811         // be accurate and we can get slightly wonky error messages (but type
812         // checking is always correct).
813         match path_res.full_def() {
814             def::DefFn(..) => ck("function"),
815             def::DefStatic(..) => ck("static"),
816             def::DefConst(..) => ck("const"),
817             def::DefAssociatedConst(..) => ck("associated const"),
818             def::DefVariant(..) => ck("variant"),
819             def::DefTy(_, false) => ck("type"),
820             def::DefTy(_, true) => ck("enum"),
821             def::DefTrait(..) => ck("trait"),
822             def::DefStruct(..) => ck("struct"),
823             def::DefMethod(..) => ck("method"),
824             def::DefMod(..) => ck("module"),
825             _ => {}
826         }
827     }
828
829     // Checks that a method is in scope.
830     fn check_method(&mut self, span: Span, method_def_id: DefId,
831                     name: ast::Name) {
832         match self.tcx.impl_or_trait_item(method_def_id).container() {
833             ty::ImplContainer(_) => {
834                 self.check_static_method(span, method_def_id, name)
835             }
836             // Trait methods are always accessible if the trait is in scope.
837             ty::TraitContainer(_) => {}
838         }
839     }
840 }
841
842 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
843     fn visit_item(&mut self, item: &hir::Item) {
844         let orig_curitem = replace(&mut self.curitem, item.id);
845         visit::walk_item(self, item);
846         self.curitem = orig_curitem;
847     }
848
849     fn visit_expr(&mut self, expr: &hir::Expr) {
850         match expr.node {
851             hir::ExprField(ref base, name) => {
852                 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
853                     self.check_field(expr.span,
854                                      def,
855                                      def.struct_variant(),
856                                      NamedField(name.node));
857                 }
858             }
859             hir::ExprTupField(ref base, idx) => {
860                 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(&**base).sty {
861                     self.check_field(expr.span,
862                                      def,
863                                      def.struct_variant(),
864                                      UnnamedField(idx.node));
865                 }
866             }
867             hir::ExprMethodCall(name, _, _) => {
868                 let method_call = ty::MethodCall::expr(expr.id);
869                 let method = self.tcx.tables.borrow().method_map[&method_call];
870                 debug!("(privacy checking) checking impl method");
871                 self.check_method(expr.span, method.def_id, name.node);
872             }
873             hir::ExprStruct(..) => {
874                 let adt = self.tcx.expr_ty(expr).ty_adt_def().unwrap();
875                 let variant = adt.variant_of_def(self.tcx.resolve_expr(expr));
876                 // RFC 736: ensure all unmentioned fields are visible.
877                 // Rather than computing the set of unmentioned fields
878                 // (i.e. `all_fields - fields`), just check them all.
879                 for field in &variant.fields {
880                     self.check_field(expr.span, adt, variant, NamedField(field.name));
881                 }
882             }
883             hir::ExprPath(..) => {
884
885                 if let def::DefStruct(_) = self.tcx.resolve_expr(expr) {
886                     let expr_ty = self.tcx.expr_ty(expr);
887                     let def = match expr_ty.sty {
888                         ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
889                             output: ty::FnConverging(ty), ..
890                         }), ..}) => ty,
891                         _ => expr_ty
892                     }.ty_adt_def().unwrap();
893                     let any_priv = def.struct_variant().fields.iter().any(|f| {
894                         f.vis != hir::Public && (
895                             !f.did.is_local() ||
896                                     !self.private_accessible(f.did.node))
897                         });
898
899                     if any_priv {
900                         span_err!(self.tcx.sess, expr.span, E0450,
901                                   "cannot invoke tuple struct constructor with private \
902                                    fields");
903                     }
904                 }
905             }
906             _ => {}
907         }
908
909         visit::walk_expr(self, expr);
910     }
911
912     fn visit_pat(&mut self, pattern: &hir::Pat) {
913         // Foreign functions do not have their patterns mapped in the def_map,
914         // and there's nothing really relevant there anyway, so don't bother
915         // checking privacy. If you can name the type then you can pass it to an
916         // external C function anyway.
917         if self.in_foreign { return }
918
919         match pattern.node {
920             hir::PatStruct(_, ref fields, _) => {
921                 let adt = self.tcx.pat_ty(pattern).ty_adt_def().unwrap();
922                 let def = self.tcx.def_map.borrow().get(&pattern.id).unwrap().full_def();
923                 let variant = adt.variant_of_def(def);
924                 for field in fields {
925                     self.check_field(pattern.span, adt, variant,
926                                      NamedField(field.node.name));
927                 }
928             }
929
930             // Patterns which bind no fields are allowable (the path is check
931             // elsewhere).
932             hir::PatEnum(_, Some(ref fields)) => {
933                 match self.tcx.pat_ty(pattern).sty {
934                     ty::TyStruct(def, _) => {
935                         for (i, field) in fields.iter().enumerate() {
936                             if let hir::PatWild(..) = field.node {
937                                 continue
938                             }
939                             self.check_field(field.span,
940                                              def,
941                                              def.struct_variant(),
942                                              UnnamedField(i));
943                         }
944                     }
945                     ty::TyEnum(..) => {
946                         // enum fields have no privacy at this time
947                     }
948                     _ => {}
949                 }
950
951             }
952             _ => {}
953         }
954
955         visit::walk_pat(self, pattern);
956     }
957
958     fn visit_foreign_item(&mut self, fi: &hir::ForeignItem) {
959         self.in_foreign = true;
960         visit::walk_foreign_item(self, fi);
961         self.in_foreign = false;
962     }
963
964     fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
965         if !path.segments.is_empty() {
966             self.check_path(path.span, id, path.segments.last().unwrap().identifier.name);
967             visit::walk_path(self, path);
968         }
969     }
970
971     fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
972         let name = if let hir::PathListIdent { name, .. } = item.node {
973             name
974         } else if !prefix.segments.is_empty() {
975             prefix.segments.last().unwrap().identifier.name
976         } else {
977             self.tcx.sess.bug("`self` import in an import list with empty prefix");
978         };
979         self.check_path(item.span, item.node.id(), name);
980         visit::walk_path_list_item(self, prefix, item);
981     }
982 }
983
984 ////////////////////////////////////////////////////////////////////////////////
985 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
986 ////////////////////////////////////////////////////////////////////////////////
987
988 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
989     tcx: &'a ty::ctxt<'tcx>,
990     in_fn: bool,
991 }
992
993 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
994     fn visit_item(&mut self, item: &hir::Item) {
995         if self.in_fn {
996             self.check_all_inherited(item);
997         } else {
998             self.check_sane_privacy(item);
999         }
1000
1001         let in_fn = self.in_fn;
1002         let orig_in_fn = replace(&mut self.in_fn, match item.node {
1003             hir::ItemMod(..) => false, // modules turn privacy back on
1004             _ => in_fn,           // otherwise we inherit
1005         });
1006         visit::walk_item(self, item);
1007         self.in_fn = orig_in_fn;
1008     }
1009
1010     fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v hir::FnDecl,
1011                 b: &'v hir::Block, s: Span, _: ast::NodeId) {
1012         // This catches both functions and methods
1013         let orig_in_fn = replace(&mut self.in_fn, true);
1014         visit::walk_fn(self, fk, fd, b, s);
1015         self.in_fn = orig_in_fn;
1016     }
1017 }
1018
1019 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1020     /// Validates all of the visibility qualifiers placed on the item given. This
1021     /// ensures that there are no extraneous qualifiers that don't actually do
1022     /// anything. In theory these qualifiers wouldn't parse, but that may happen
1023     /// later on down the road...
1024     fn check_sane_privacy(&self, item: &hir::Item) {
1025         let tcx = self.tcx;
1026         let check_inherited = |sp: Span, vis: hir::Visibility, note: &str| {
1027             if vis != hir::Inherited {
1028                 span_err!(tcx.sess, sp, E0449,
1029                           "unnecessary visibility qualifier");
1030                 if !note.is_empty() {
1031                     tcx.sess.span_note(sp, note);
1032                 }
1033             }
1034         };
1035         match item.node {
1036             // implementations of traits don't need visibility qualifiers because
1037             // that's controlled by having the trait in scope.
1038             hir::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1039                 check_inherited(item.span, item.vis,
1040                                 "visibility qualifiers have no effect on trait \
1041                                  impls");
1042                 for impl_item in impl_items {
1043                     check_inherited(impl_item.span, impl_item.vis, "");
1044                 }
1045             }
1046
1047             hir::ItemImpl(..) => {
1048                 check_inherited(item.span, item.vis,
1049                                 "place qualifiers on individual methods instead");
1050             }
1051             hir::ItemForeignMod(..) => {
1052                 check_inherited(item.span, item.vis,
1053                                 "place qualifiers on individual functions \
1054                                  instead");
1055             }
1056
1057             hir::ItemEnum(..) |
1058             hir::ItemTrait(..) | hir::ItemDefaultImpl(..) |
1059             hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemStruct(..) |
1060             hir::ItemFn(..) | hir::ItemMod(..) | hir::ItemTy(..) |
1061             hir::ItemExternCrate(_) | hir::ItemUse(_) => {}
1062         }
1063     }
1064
1065     /// When inside of something like a function or a method, visibility has no
1066     /// control over anything so this forbids any mention of any visibility
1067     fn check_all_inherited(&self, item: &hir::Item) {
1068         let tcx = self.tcx;
1069         fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: hir::Visibility) {
1070             if vis != hir::Inherited {
1071                 span_err!(tcx.sess, sp, E0447,
1072                           "visibility has no effect inside functions");
1073             }
1074         }
1075         let check_struct = |def: &hir::StructDef| {
1076             for f in &def.fields {
1077                match f.node.kind {
1078                     hir::NamedField(_, p) => check_inherited(tcx, f.span, p),
1079                     hir::UnnamedField(..) => {}
1080                 }
1081             }
1082         };
1083         check_inherited(tcx, item.span, item.vis);
1084         match item.node {
1085             hir::ItemImpl(_, _, _, _, _, ref impl_items) => {
1086                 for impl_item in impl_items {
1087                     match impl_item.node {
1088                         hir::MethodImplItem(..) => {
1089                             check_inherited(tcx, impl_item.span, impl_item.vis);
1090                         }
1091                         _ => {}
1092                     }
1093                 }
1094             }
1095             hir::ItemForeignMod(ref fm) => {
1096                 for i in &fm.items {
1097                     check_inherited(tcx, i.span, i.vis);
1098                 }
1099             }
1100
1101             hir::ItemStruct(ref def, _) => check_struct(&**def),
1102
1103             hir::ItemEnum(..) |
1104             hir::ItemExternCrate(_) | hir::ItemUse(_) |
1105             hir::ItemTrait(..) | hir::ItemDefaultImpl(..) |
1106             hir::ItemStatic(..) | hir::ItemConst(..) |
1107             hir::ItemFn(..) | hir::ItemMod(..) | hir::ItemTy(..) => {}
1108         }
1109     }
1110 }
1111
1112 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1113     tcx: &'a ty::ctxt<'tcx>,
1114     exported_items: &'a ExportedItems,
1115     public_items: &'a PublicItems,
1116     in_variant: bool,
1117 }
1118
1119 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1120     inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1121     /// whether the type refers to private types.
1122     contains_private: bool,
1123     /// whether we've recurred at all (i.e. if we're pointing at the
1124     /// first type on which visit_ty was called).
1125     at_outer_type: bool,
1126     // whether that first type is a public path.
1127     outer_type_is_public_path: bool,
1128 }
1129
1130 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1131     fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1132         let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) {
1133             // `int` etc. (None doesn't seem to occur.)
1134             None | Some(def::DefPrimTy(..)) => return false,
1135             Some(def) => def.def_id(),
1136         };
1137         // A path can only be private if:
1138         // it's in this crate...
1139         if !did.is_local() {
1140             return false
1141         }
1142
1143         // .. and it corresponds to a private type in the AST (this returns
1144         // None for type parameters)
1145         match self.tcx.map.find(did.node) {
1146             Some(ast_map::NodeItem(ref item)) => item.vis != hir::Public,
1147             Some(_) | None => false,
1148         }
1149     }
1150
1151     fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1152         // FIXME: this would preferably be using `exported_items`, but all
1153         // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1154         self.public_items.contains(&trait_id)
1155     }
1156
1157     fn check_ty_param_bound(&self,
1158                             ty_param_bound: &hir::TyParamBound) {
1159         if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1160             if !self.tcx.sess.features.borrow().visible_private_types &&
1161                 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1162                     let span = trait_ref.trait_ref.path.span;
1163                     span_err!(self.tcx.sess, span, E0445,
1164                               "private trait in exported type parameter bound");
1165             }
1166         }
1167     }
1168
1169     fn item_is_public(&self, id: &ast::NodeId, vis: hir::Visibility) -> bool {
1170         self.exported_items.contains(id) || vis == hir::Public
1171     }
1172 }
1173
1174 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1175     fn visit_ty(&mut self, ty: &hir::Ty) {
1176         if let hir::TyPath(..) = ty.node {
1177             if self.inner.path_is_private_type(ty.id) {
1178                 self.contains_private = true;
1179                 // found what we're looking for so let's stop
1180                 // working.
1181                 return
1182             } else if self.at_outer_type {
1183                 self.outer_type_is_public_path = true;
1184             }
1185         }
1186         self.at_outer_type = false;
1187         visit::walk_ty(self, ty)
1188     }
1189
1190     // don't want to recurse into [, .. expr]
1191     fn visit_expr(&mut self, _: &hir::Expr) {}
1192 }
1193
1194 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1195     fn visit_item(&mut self, item: &hir::Item) {
1196         match item.node {
1197             // contents of a private mod can be reexported, so we need
1198             // to check internals.
1199             hir::ItemMod(_) => {}
1200
1201             // An `extern {}` doesn't introduce a new privacy
1202             // namespace (the contents have their own privacies).
1203             hir::ItemForeignMod(_) => {}
1204
1205             hir::ItemTrait(_, _, ref bounds, _) => {
1206                 if !self.trait_is_public(item.id) {
1207                     return
1208                 }
1209
1210                 for bound in bounds.iter() {
1211                     self.check_ty_param_bound(bound)
1212                 }
1213             }
1214
1215             // impls need some special handling to try to offer useful
1216             // error messages without (too many) false positives
1217             // (i.e. we could just return here to not check them at
1218             // all, or some worse estimation of whether an impl is
1219             // publicly visible).
1220             hir::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1221                 // `impl [... for] Private` is never visible.
1222                 let self_contains_private;
1223                 // impl [... for] Public<...>, but not `impl [... for]
1224                 // Vec<Public>` or `(Public,)` etc.
1225                 let self_is_public_path;
1226
1227                 // check the properties of the Self type:
1228                 {
1229                     let mut visitor = CheckTypeForPrivatenessVisitor {
1230                         inner: self,
1231                         contains_private: false,
1232                         at_outer_type: true,
1233                         outer_type_is_public_path: false,
1234                     };
1235                     visitor.visit_ty(&**self_);
1236                     self_contains_private = visitor.contains_private;
1237                     self_is_public_path = visitor.outer_type_is_public_path;
1238                 }
1239
1240                 // miscellaneous info about the impl
1241
1242                 // `true` iff this is `impl Private for ...`.
1243                 let not_private_trait =
1244                     trait_ref.as_ref().map_or(true, // no trait counts as public trait
1245                                               |tr| {
1246                         let did = self.tcx.trait_ref_to_def_id(tr);
1247
1248                         !did.is_local() || self.trait_is_public(did.node)
1249                     });
1250
1251                 // `true` iff this is a trait impl or at least one method is public.
1252                 //
1253                 // `impl Public { $( fn ...() {} )* }` is not visible.
1254                 //
1255                 // This is required over just using the methods' privacy
1256                 // directly because we might have `impl<T: Foo<Private>> ...`,
1257                 // and we shouldn't warn about the generics if all the methods
1258                 // are private (because `T` won't be visible externally).
1259                 let trait_or_some_public_method =
1260                     trait_ref.is_some() ||
1261                     impl_items.iter()
1262                               .any(|impl_item| {
1263                                   match impl_item.node {
1264                                       hir::ConstImplItem(..) |
1265                                       hir::MethodImplItem(..) => {
1266                                           self.exported_items.contains(&impl_item.id)
1267                                       }
1268                                       hir::TypeImplItem(_) => false,
1269                                   }
1270                               });
1271
1272                 if !self_contains_private &&
1273                         not_private_trait &&
1274                         trait_or_some_public_method {
1275
1276                     visit::walk_generics(self, g);
1277
1278                     match *trait_ref {
1279                         None => {
1280                             for impl_item in impl_items {
1281                                 // This is where we choose whether to walk down
1282                                 // further into the impl to check its items. We
1283                                 // should only walk into public items so that we
1284                                 // don't erroneously report errors for private
1285                                 // types in private items.
1286                                 match impl_item.node {
1287                                     hir::ConstImplItem(..) |
1288                                     hir::MethodImplItem(..)
1289                                         if self.item_is_public(&impl_item.id, impl_item.vis) =>
1290                                     {
1291                                         visit::walk_impl_item(self, impl_item)
1292                                     }
1293                                     hir::TypeImplItem(..) => {
1294                                         visit::walk_impl_item(self, impl_item)
1295                                     }
1296                                     _ => {}
1297                                 }
1298                             }
1299                         }
1300                         Some(ref tr) => {
1301                             // Any private types in a trait impl fall into three
1302                             // categories.
1303                             // 1. mentioned in the trait definition
1304                             // 2. mentioned in the type params/generics
1305                             // 3. mentioned in the associated types of the impl
1306                             //
1307                             // Those in 1. can only occur if the trait is in
1308                             // this crate and will've been warned about on the
1309                             // trait definition (there's no need to warn twice
1310                             // so we don't check the methods).
1311                             //
1312                             // Those in 2. are warned via walk_generics and this
1313                             // call here.
1314                             visit::walk_path(self, &tr.path);
1315
1316                             // Those in 3. are warned with this call.
1317                             for impl_item in impl_items {
1318                                 if let hir::TypeImplItem(ref ty) = impl_item.node {
1319                                     self.visit_ty(ty);
1320                                 }
1321                             }
1322                         }
1323                     }
1324                 } else if trait_ref.is_none() && self_is_public_path {
1325                     // impl Public<Private> { ... }. Any public static
1326                     // methods will be visible as `Public::foo`.
1327                     let mut found_pub_static = false;
1328                     for impl_item in impl_items {
1329                         match impl_item.node {
1330                             hir::ConstImplItem(..) => {
1331                                 if self.item_is_public(&impl_item.id, impl_item.vis) {
1332                                     found_pub_static = true;
1333                                     visit::walk_impl_item(self, impl_item);
1334                                 }
1335                             }
1336                             hir::MethodImplItem(ref sig, _) => {
1337                                 if sig.explicit_self.node == hir::SelfStatic &&
1338                                       self.item_is_public(&impl_item.id, impl_item.vis) {
1339                                     found_pub_static = true;
1340                                     visit::walk_impl_item(self, impl_item);
1341                                 }
1342                             }
1343                             _ => {}
1344                         }
1345                     }
1346                     if found_pub_static {
1347                         visit::walk_generics(self, g)
1348                     }
1349                 }
1350                 return
1351             }
1352
1353             // `type ... = ...;` can contain private types, because
1354             // we're introducing a new name.
1355             hir::ItemTy(..) => return,
1356
1357             // not at all public, so we don't care
1358             _ if !self.item_is_public(&item.id, item.vis) => {
1359                 return;
1360             }
1361
1362             _ => {}
1363         }
1364
1365         // We've carefully constructed it so that if we're here, then
1366         // any `visit_ty`'s will be called on things that are in
1367         // public signatures, i.e. things that we're interested in for
1368         // this visitor.
1369         debug!("VisiblePrivateTypesVisitor entering item {:?}", item);
1370         visit::walk_item(self, item);
1371     }
1372
1373     fn visit_generics(&mut self, generics: &hir::Generics) {
1374         for ty_param in generics.ty_params.iter() {
1375             for bound in ty_param.bounds.iter() {
1376                 self.check_ty_param_bound(bound)
1377             }
1378         }
1379         for predicate in &generics.where_clause.predicates {
1380             match predicate {
1381                 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1382                     for bound in bound_pred.bounds.iter() {
1383                         self.check_ty_param_bound(bound)
1384                     }
1385                 }
1386                 &hir::WherePredicate::RegionPredicate(_) => {}
1387                 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1388                     self.visit_ty(&*eq_pred.ty);
1389                 }
1390             }
1391         }
1392     }
1393
1394     fn visit_foreign_item(&mut self, item: &hir::ForeignItem) {
1395         if self.exported_items.contains(&item.id) {
1396             visit::walk_foreign_item(self, item)
1397         }
1398     }
1399
1400     fn visit_ty(&mut self, t: &hir::Ty) {
1401         debug!("VisiblePrivateTypesVisitor checking ty {:?}", t);
1402         if let hir::TyPath(_, ref p) = t.node {
1403             if !self.tcx.sess.features.borrow().visible_private_types &&
1404                 self.path_is_private_type(t.id) {
1405                 span_err!(self.tcx.sess, p.span, E0446,
1406                           "private type in exported type signature");
1407             }
1408         }
1409         visit::walk_ty(self, t)
1410     }
1411
1412     fn visit_variant(&mut self, v: &hir::Variant, g: &hir::Generics) {
1413         if self.exported_items.contains(&v.node.id) {
1414             self.in_variant = true;
1415             visit::walk_variant(self, v, g);
1416             self.in_variant = false;
1417         }
1418     }
1419
1420     fn visit_struct_field(&mut self, s: &hir::StructField) {
1421         match s.node.kind {
1422             hir::NamedField(_, vis) if vis == hir::Public || self.in_variant => {
1423                 visit::walk_struct_field(self, s);
1424             }
1425             _ => {}
1426         }
1427     }
1428
1429
1430     // we don't need to introspect into these at all: an
1431     // expression/block context can't possibly contain exported things.
1432     // (Making them no-ops stops us from traversing the whole AST without
1433     // having to be super careful about our `walk_...` calls above.)
1434     fn visit_block(&mut self, _: &hir::Block) {}
1435     fn visit_expr(&mut self, _: &hir::Expr) {}
1436 }
1437
1438 pub fn check_crate(tcx: &ty::ctxt,
1439                    export_map: &def::ExportMap,
1440                    external_exports: ExternalExports)
1441                    -> (ExportedItems, PublicItems) {
1442     let krate = tcx.map.krate();
1443
1444     // Figure out who everyone's parent is
1445     let mut visitor = ParentVisitor {
1446         parents: NodeMap(),
1447         curparent: ast::DUMMY_NODE_ID,
1448     };
1449     visit::walk_crate(&mut visitor, krate);
1450
1451     // Use the parent map to check the privacy of everything
1452     let mut visitor = PrivacyVisitor {
1453         curitem: ast::DUMMY_NODE_ID,
1454         in_foreign: false,
1455         tcx: tcx,
1456         parents: visitor.parents,
1457         external_exports: external_exports,
1458     };
1459     visit::walk_crate(&mut visitor, krate);
1460
1461     // Sanity check to make sure that all privacy usage and controls are
1462     // reasonable.
1463     let mut visitor = SanePrivacyVisitor {
1464         in_fn: false,
1465         tcx: tcx,
1466     };
1467     visit::walk_crate(&mut visitor, krate);
1468
1469     tcx.sess.abort_if_errors();
1470
1471     // Build up a set of all exported items in the AST. This is a set of all
1472     // items which are reachable from external crates based on visibility.
1473     let mut visitor = EmbargoVisitor {
1474         tcx: tcx,
1475         exported_items: NodeSet(),
1476         public_items: NodeSet(),
1477         reexports: NodeSet(),
1478         export_map: export_map,
1479         prev_exported: true,
1480         prev_public: true,
1481     };
1482     loop {
1483         let before = visitor.exported_items.len();
1484         visit::walk_crate(&mut visitor, krate);
1485         if before == visitor.exported_items.len() {
1486             break
1487         }
1488     }
1489
1490     let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1491
1492     {
1493         let mut visitor = VisiblePrivateTypesVisitor {
1494             tcx: tcx,
1495             exported_items: &exported_items,
1496             public_items: &public_items,
1497             in_variant: false,
1498         };
1499         visit::walk_crate(&mut visitor, krate);
1500     }
1501     return (exported_items, public_items);
1502 }