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