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