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