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