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