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