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