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