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