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