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