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