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