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