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