]> git.lizzy.rs Git - rust.git/blob - src/librustc_privacy/lib.rs
872a29e7bc0c56f46ed8649207fbb3f0e0c355ef
[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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13        html_root_url = "https://doc.rust-lang.org/nightly/")]
14 #![deny(warnings)]
15
16 #![feature(rustc_diagnostic_macros)]
17
18 #[macro_use] extern crate rustc;
19 #[macro_use] extern crate syntax;
20 extern crate syntax_pos;
21
22 use rustc::hir::{self, PatKind};
23 use rustc::hir::def::Def;
24 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
25 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
26 use rustc::hir::itemlikevisit::DeepVisitor;
27 use rustc::lint;
28 use rustc::middle::privacy::{AccessLevel, AccessLevels};
29 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable};
30 use rustc::ty::fold::TypeVisitor;
31 use rustc::ty::maps::Providers;
32 use rustc::util::nodemap::NodeSet;
33 use syntax::ast::{self, CRATE_NODE_ID, Ident};
34 use syntax::symbol::keywords;
35 use syntax_pos::Span;
36
37 use std::cmp;
38 use std::mem::replace;
39 use std::rc::Rc;
40
41 mod diagnostics;
42
43 ////////////////////////////////////////////////////////////////////////////////
44 /// Visitor used to determine if pub(restricted) is used anywhere in the crate.
45 ///
46 /// This is done so that `private_in_public` warnings can be turned into hard errors
47 /// in crates that have been updated to use pub(restricted).
48 ////////////////////////////////////////////////////////////////////////////////
49 struct PubRestrictedVisitor<'a, 'tcx: 'a> {
50     tcx:  TyCtxt<'a, 'tcx, 'tcx>,
51     has_pub_restricted: bool,
52 }
53
54 impl<'a, 'tcx> Visitor<'tcx> for PubRestrictedVisitor<'a, 'tcx> {
55     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
56         NestedVisitorMap::All(&self.tcx.hir)
57     }
58     fn visit_vis(&mut self, vis: &'tcx hir::Visibility) {
59         self.has_pub_restricted = self.has_pub_restricted || vis.is_pub_restricted();
60     }
61 }
62
63 ////////////////////////////////////////////////////////////////////////////////
64 /// The embargo visitor, used to determine the exports of the ast
65 ////////////////////////////////////////////////////////////////////////////////
66
67 struct EmbargoVisitor<'a, 'tcx: 'a> {
68     tcx: TyCtxt<'a, 'tcx, 'tcx>,
69
70     // Accessibility levels for reachable nodes
71     access_levels: AccessLevels,
72     // Previous accessibility level, None means unreachable
73     prev_level: Option<AccessLevel>,
74     // Have something changed in the level map?
75     changed: bool,
76 }
77
78 struct ReachEverythingInTheInterfaceVisitor<'b, 'a: 'b, 'tcx: 'a> {
79     item_def_id: DefId,
80     ev: &'b mut EmbargoVisitor<'a, 'tcx>,
81 }
82
83 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
84     fn item_ty_level(&self, item_def_id: DefId) -> Option<AccessLevel> {
85         let ty_def_id = match self.tcx.type_of(item_def_id).sty {
86             ty::TyAdt(adt, _) => adt.did,
87             ty::TyDynamic(ref obj, ..) if obj.principal().is_some() =>
88                 obj.principal().unwrap().def_id(),
89             ty::TyProjection(ref proj) => proj.trait_ref(self.tcx).def_id,
90             _ => return Some(AccessLevel::Public)
91         };
92         if let Some(node_id) = self.tcx.hir.as_local_node_id(ty_def_id) {
93             self.get(node_id)
94         } else {
95             Some(AccessLevel::Public)
96         }
97     }
98
99     fn impl_trait_level(&self, impl_def_id: DefId) -> Option<AccessLevel> {
100         if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_def_id) {
101             if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
102                 return self.get(node_id);
103             }
104         }
105         Some(AccessLevel::Public)
106     }
107
108     fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
109         self.access_levels.map.get(&id).cloned()
110     }
111
112     // Updates node level and returns the updated level
113     fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
114         let old_level = self.get(id);
115         // Accessibility levels can only grow
116         if level > old_level {
117             self.access_levels.map.insert(id, level.unwrap());
118             self.changed = true;
119             level
120         } else {
121             old_level
122         }
123     }
124
125     fn reach<'b>(&'b mut self, item_id: ast::NodeId)
126                  -> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
127         ReachEverythingInTheInterfaceVisitor {
128             item_def_id: self.tcx.hir.local_def_id(item_id),
129             ev: self,
130         }
131     }
132 }
133
134 impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> {
135     /// We want to visit items in the context of their containing
136     /// module and so forth, so supply a crate for doing a deep walk.
137     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
138         NestedVisitorMap::All(&self.tcx.hir)
139     }
140
141     fn visit_item(&mut self, item: &'tcx hir::Item) {
142         let inherited_item_level = match item.node {
143             // Impls inherit level from their types and traits
144             hir::ItemImpl(..) => {
145                 let def_id = self.tcx.hir.local_def_id(item.id);
146                 cmp::min(self.item_ty_level(def_id), self.impl_trait_level(def_id))
147             }
148             hir::ItemDefaultImpl(..) => {
149                 let def_id = self.tcx.hir.local_def_id(item.id);
150                 self.impl_trait_level(def_id)
151             }
152             // Foreign mods inherit level from parents
153             hir::ItemForeignMod(..) => {
154                 self.prev_level
155             }
156             // Other `pub` items inherit levels from parents
157             hir::ItemConst(..) | hir::ItemEnum(..) | hir::ItemExternCrate(..) |
158             hir::ItemGlobalAsm(..) | hir::ItemFn(..) | hir::ItemMod(..) |
159             hir::ItemStatic(..) | hir::ItemStruct(..) | hir::ItemTrait(..) |
160             hir::ItemTy(..) | hir::ItemUnion(..) | hir::ItemUse(..) => {
161                 if item.vis == hir::Public { self.prev_level } else { None }
162             }
163         };
164
165         // Update level of the item itself
166         let item_level = self.update(item.id, inherited_item_level);
167
168         // Update levels of nested things
169         match item.node {
170             hir::ItemEnum(ref def, _) => {
171                 for variant in &def.variants {
172                     let variant_level = self.update(variant.node.data.id(), item_level);
173                     for field in variant.node.data.fields() {
174                         self.update(field.id, variant_level);
175                     }
176                 }
177             }
178             hir::ItemImpl(.., None, _, ref impl_item_refs) => {
179                 for impl_item_ref in impl_item_refs {
180                     if impl_item_ref.vis == hir::Public {
181                         self.update(impl_item_ref.id.node_id, item_level);
182                     }
183                 }
184             }
185             hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
186                 for impl_item_ref in impl_item_refs {
187                     self.update(impl_item_ref.id.node_id, item_level);
188                 }
189             }
190             hir::ItemTrait(.., ref trait_item_refs) => {
191                 for trait_item_ref in trait_item_refs {
192                     self.update(trait_item_ref.id.node_id, item_level);
193                 }
194             }
195             hir::ItemStruct(ref def, _) | hir::ItemUnion(ref def, _) => {
196                 if !def.is_struct() {
197                     self.update(def.id(), item_level);
198                 }
199                 for field in def.fields() {
200                     if field.vis == hir::Public {
201                         self.update(field.id, item_level);
202                     }
203                 }
204             }
205             hir::ItemForeignMod(ref foreign_mod) => {
206                 for foreign_item in &foreign_mod.items {
207                     if foreign_item.vis == hir::Public {
208                         self.update(foreign_item.id, item_level);
209                     }
210                 }
211             }
212             hir::ItemUse(..) | hir::ItemStatic(..) | hir::ItemConst(..) |
213             hir::ItemGlobalAsm(..) | hir::ItemTy(..) | hir::ItemMod(..) |
214             hir::ItemFn(..) | hir::ItemExternCrate(..) | hir::ItemDefaultImpl(..) => {}
215         }
216
217         // Mark all items in interfaces of reachable items as reachable
218         match item.node {
219             // The interface is empty
220             hir::ItemExternCrate(..) => {}
221             // All nested items are checked by visit_item
222             hir::ItemMod(..) => {}
223             // Reexports are handled in visit_mod
224             hir::ItemUse(..) => {}
225             // The interface is empty
226             hir::ItemDefaultImpl(..) => {}
227             // The interface is empty
228             hir::ItemGlobalAsm(..) => {}
229             // Visit everything
230             hir::ItemConst(..) | hir::ItemStatic(..) |
231             hir::ItemFn(..) | hir::ItemTy(..) => {
232                 if item_level.is_some() {
233                     self.reach(item.id).generics().predicates().ty();
234                 }
235             }
236             hir::ItemTrait(.., ref trait_item_refs) => {
237                 if item_level.is_some() {
238                     self.reach(item.id).generics().predicates();
239
240                     for trait_item_ref in trait_item_refs {
241                         let mut reach = self.reach(trait_item_ref.id.node_id);
242                         reach.generics().predicates();
243
244                         if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
245                            !trait_item_ref.defaultness.has_value() {
246                             // No type to visit.
247                         } else {
248                             reach.ty();
249                         }
250                     }
251                 }
252             }
253             // Visit everything except for private impl items
254             hir::ItemImpl(.., ref trait_ref, _, ref impl_item_refs) => {
255                 if item_level.is_some() {
256                     self.reach(item.id).generics().predicates().impl_trait_ref();
257
258                     for impl_item_ref in impl_item_refs {
259                         let id = impl_item_ref.id.node_id;
260                         if trait_ref.is_some() || self.get(id).is_some() {
261                             self.reach(id).generics().predicates().ty();
262                         }
263                     }
264                 }
265             }
266
267             // Visit everything, but enum variants have their own levels
268             hir::ItemEnum(ref def, _) => {
269                 if item_level.is_some() {
270                     self.reach(item.id).generics().predicates();
271                 }
272                 for variant in &def.variants {
273                     if self.get(variant.node.data.id()).is_some() {
274                         for field in variant.node.data.fields() {
275                             self.reach(field.id).ty();
276                         }
277                         // Corner case: if the variant is reachable, but its
278                         // enum is not, make the enum reachable as well.
279                         self.update(item.id, Some(AccessLevel::Reachable));
280                     }
281                 }
282             }
283             // Visit everything, but foreign items have their own levels
284             hir::ItemForeignMod(ref foreign_mod) => {
285                 for foreign_item in &foreign_mod.items {
286                     if self.get(foreign_item.id).is_some() {
287                         self.reach(foreign_item.id).generics().predicates().ty();
288                     }
289                 }
290             }
291             // Visit everything except for private fields
292             hir::ItemStruct(ref struct_def, _) |
293             hir::ItemUnion(ref struct_def, _) => {
294                 if item_level.is_some() {
295                     self.reach(item.id).generics().predicates();
296                     for field in struct_def.fields() {
297                         if self.get(field.id).is_some() {
298                             self.reach(field.id).ty();
299                         }
300                     }
301                 }
302             }
303         }
304
305         let orig_level = self.prev_level;
306         self.prev_level = item_level;
307
308         intravisit::walk_item(self, item);
309
310         self.prev_level = orig_level;
311     }
312
313     fn visit_block(&mut self, b: &'tcx hir::Block) {
314         let orig_level = replace(&mut self.prev_level, None);
315
316         // Blocks can have public items, for example impls, but they always
317         // start as completely private regardless of publicity of a function,
318         // constant, type, field, etc. in which this block resides
319         intravisit::walk_block(self, b);
320
321         self.prev_level = orig_level;
322     }
323
324     fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
325         // This code is here instead of in visit_item so that the
326         // crate module gets processed as well.
327         if self.prev_level.is_some() {
328             let hir_id = self.tcx.hir.node_to_hir_id(id);
329             if let Some(exports) = self.tcx.module_exports(hir_id) {
330                 for export in exports.iter() {
331                     if let Some(node_id) = self.tcx.hir.as_local_node_id(export.def.def_id()) {
332                         self.update(node_id, Some(AccessLevel::Exported));
333                     }
334                 }
335             }
336         }
337
338         intravisit::walk_mod(self, m, id);
339     }
340
341     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
342         if md.legacy {
343             self.update(md.id, Some(AccessLevel::Public));
344             return
345         }
346
347         let module_did = ty::DefIdTree::parent(self.tcx, self.tcx.hir.local_def_id(md.id)).unwrap();
348         let mut module_id = self.tcx.hir.as_local_node_id(module_did).unwrap();
349         let level = if md.vis == hir::Public { self.get(module_id) } else { None };
350         let level = self.update(md.id, level);
351         if level.is_none() {
352             return
353         }
354
355         loop {
356             let module = if module_id == ast::CRATE_NODE_ID {
357                 &self.tcx.hir.krate().module
358             } else if let hir::ItemMod(ref module) = self.tcx.hir.expect_item(module_id).node {
359                 module
360             } else {
361                 unreachable!()
362             };
363             for id in &module.item_ids {
364                 self.update(id.id, level);
365             }
366             if module_id == ast::CRATE_NODE_ID {
367                 break
368             }
369             module_id = self.tcx.hir.get_parent_node(module_id);
370         }
371     }
372
373     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
374         if let hir::TyImplTrait(..) = ty.node {
375             if self.get(ty.id).is_some() {
376                 // Reach the (potentially private) type and the API being exposed.
377                 self.reach(ty.id).ty().predicates();
378             }
379         }
380
381         intravisit::walk_ty(self, ty);
382     }
383 }
384
385 impl<'b, 'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
386     fn generics(&mut self) -> &mut Self {
387         for def in &self.ev.tcx.generics_of(self.item_def_id).types {
388             if def.has_default {
389                 self.ev.tcx.type_of(def.def_id).visit_with(self);
390             }
391         }
392         self
393     }
394
395     fn predicates(&mut self) -> &mut Self {
396         let predicates = self.ev.tcx.predicates_of(self.item_def_id);
397         for predicate in &predicates.predicates {
398             predicate.visit_with(self);
399             match predicate {
400                 &ty::Predicate::Trait(poly_predicate) => {
401                     self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
402                 },
403                 &ty::Predicate::Projection(poly_predicate) => {
404                     let tcx = self.ev.tcx;
405                     self.check_trait_ref(
406                         poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
407                     );
408                 },
409                 _ => (),
410             };
411         }
412         self
413     }
414
415     fn ty(&mut self) -> &mut Self {
416         let ty = self.ev.tcx.type_of(self.item_def_id);
417         ty.visit_with(self);
418         if let ty::TyFnDef(def_id, _) = ty.sty {
419             if def_id == self.item_def_id {
420                 self.ev.tcx.fn_sig(def_id).visit_with(self);
421             }
422         }
423         self
424     }
425
426     fn impl_trait_ref(&mut self) -> &mut Self {
427         if let Some(impl_trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
428             self.check_trait_ref(impl_trait_ref);
429             impl_trait_ref.super_visit_with(self);
430         }
431         self
432     }
433
434     fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
435         if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(trait_ref.def_id) {
436             let item = self.ev.tcx.hir.expect_item(node_id);
437             self.ev.update(item.id, Some(AccessLevel::Reachable));
438         }
439     }
440 }
441
442 impl<'b, 'a, 'tcx> TypeVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'b, 'a, 'tcx> {
443     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
444         let ty_def_id = match ty.sty {
445             ty::TyAdt(adt, _) => Some(adt.did),
446             ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
447             ty::TyProjection(ref proj) => Some(proj.item_def_id),
448             ty::TyFnDef(def_id, ..) |
449             ty::TyClosure(def_id, ..) |
450             ty::TyGenerator(def_id, ..) |
451             ty::TyAnon(def_id, _) => Some(def_id),
452             _ => None
453         };
454
455         if let Some(def_id) = ty_def_id {
456             if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(def_id) {
457                 self.ev.update(node_id, Some(AccessLevel::Reachable));
458             }
459         }
460
461         ty.super_visit_with(self)
462     }
463 }
464
465 //////////////////////////////////////////////////////////////////////////////////////
466 /// Name privacy visitor, checks privacy and reports violations.
467 /// Most of name privacy checks are performed during the main resolution phase,
468 /// or later in type checking when field accesses and associated items are resolved.
469 /// This pass performs remaining checks for fields in struct expressions and patterns.
470 //////////////////////////////////////////////////////////////////////////////////////
471
472 struct NamePrivacyVisitor<'a, 'tcx: 'a> {
473     tcx: TyCtxt<'a, 'tcx, 'tcx>,
474     tables: &'a ty::TypeckTables<'tcx>,
475     current_item: ast::NodeId,
476     empty_tables: &'a ty::TypeckTables<'tcx>,
477 }
478
479 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
480     // Checks that a field is accessible.
481     fn check_field(&mut self, span: Span, def: &'tcx ty::AdtDef, field: &'tcx ty::FieldDef) {
482         let ident = Ident { ctxt: span.ctxt().modern(), ..keywords::Invalid.ident() };
483         let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
484         if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
485             struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
486                              field.name, def.variant_descr(), self.tcx.item_path_str(def.did))
487                 .span_label(span, format!("field `{}` is private", field.name))
488                 .emit();
489         }
490     }
491 }
492
493 // Set the correct TypeckTables for the given `item_id` (or an empty table if
494 // there is no TypeckTables for the item).
495 fn update_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
496                            item_id: ast::NodeId,
497                            tables: &mut &'a ty::TypeckTables<'tcx>,
498                            empty_tables: &'a ty::TypeckTables<'tcx>)
499                            -> &'a ty::TypeckTables<'tcx> {
500     let def_id = tcx.hir.local_def_id(item_id);
501
502     if tcx.has_typeck_tables(def_id) {
503         replace(tables, tcx.typeck_tables_of(def_id))
504     } else {
505         replace(tables, empty_tables)
506     }
507 }
508
509 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
510     /// We want to visit items in the context of their containing
511     /// module and so forth, so supply a crate for doing a deep walk.
512     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
513         NestedVisitorMap::All(&self.tcx.hir)
514     }
515
516     fn visit_nested_body(&mut self, body: hir::BodyId) {
517         let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
518         let body = self.tcx.hir.body(body);
519         self.visit_body(body);
520         self.tables = orig_tables;
521     }
522
523     fn visit_item(&mut self, item: &'tcx hir::Item) {
524         let orig_current_item = replace(&mut self.current_item, item.id);
525         let orig_tables = update_tables(self.tcx, item.id, &mut self.tables, self.empty_tables);
526         intravisit::walk_item(self, item);
527         self.current_item = orig_current_item;
528         self.tables = orig_tables;
529     }
530
531     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
532         let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
533         intravisit::walk_trait_item(self, ti);
534         self.tables = orig_tables;
535     }
536
537     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
538         let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
539         intravisit::walk_impl_item(self, ii);
540         self.tables = orig_tables;
541     }
542
543     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
544         match expr.node {
545             hir::ExprStruct(ref qpath, ref fields, ref base) => {
546                 let def = self.tables.qpath_def(qpath, expr.hir_id);
547                 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
548                 let variant = adt.variant_of_def(def);
549                 if let Some(ref base) = *base {
550                     // If the expression uses FRU we need to make sure all the unmentioned fields
551                     // are checked for privacy (RFC 736). Rather than computing the set of
552                     // unmentioned fields, just check them all.
553                     for variant_field in &variant.fields {
554                         let field = fields.iter().find(|f| f.name.node == variant_field.name);
555                         let span = if let Some(f) = field { f.span } else { base.span };
556                         self.check_field(span, adt, variant_field);
557                     }
558                 } else {
559                     for field in fields {
560                         self.check_field(field.span, adt, variant.field_named(field.name.node));
561                     }
562                 }
563             }
564             _ => {}
565         }
566
567         intravisit::walk_expr(self, expr);
568     }
569
570     fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
571         match pat.node {
572             PatKind::Struct(ref qpath, ref fields, _) => {
573                 let def = self.tables.qpath_def(qpath, pat.hir_id);
574                 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
575                 let variant = adt.variant_of_def(def);
576                 for field in fields {
577                     self.check_field(field.span, adt, variant.field_named(field.node.name));
578                 }
579             }
580             _ => {}
581         }
582
583         intravisit::walk_pat(self, pat);
584     }
585 }
586
587 ////////////////////////////////////////////////////////////////////////////////////////////
588 /// Type privacy visitor, checks types for privacy and reports violations.
589 /// Both explicitly written types and inferred types of expressions and patters are checked.
590 /// Checks are performed on "semantic" types regardless of names and their hygiene.
591 ////////////////////////////////////////////////////////////////////////////////////////////
592
593 struct TypePrivacyVisitor<'a, 'tcx: 'a> {
594     tcx: TyCtxt<'a, 'tcx, 'tcx>,
595     tables: &'a ty::TypeckTables<'tcx>,
596     current_item: DefId,
597     span: Span,
598     empty_tables: &'a ty::TypeckTables<'tcx>,
599 }
600
601 impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
602     fn def_id_visibility(&self, did: DefId) -> ty::Visibility {
603         match self.tcx.hir.as_local_node_id(did) {
604             Some(node_id) => {
605                 let vis = match self.tcx.hir.get(node_id) {
606                     hir::map::NodeItem(item) => &item.vis,
607                     hir::map::NodeForeignItem(foreign_item) => &foreign_item.vis,
608                     hir::map::NodeImplItem(impl_item) => &impl_item.vis,
609                     hir::map::NodeTraitItem(..) |
610                     hir::map::NodeVariant(..) => {
611                         return self.def_id_visibility(self.tcx.hir.get_parent_did(node_id));
612                     }
613                     hir::map::NodeStructCtor(vdata) => {
614                         let struct_node_id = self.tcx.hir.get_parent(node_id);
615                         let struct_vis = match self.tcx.hir.get(struct_node_id) {
616                             hir::map::NodeItem(item) => &item.vis,
617                             node => bug!("unexpected node kind: {:?}", node),
618                         };
619                         let mut ctor_vis
620                             = ty::Visibility::from_hir(struct_vis, struct_node_id, self.tcx);
621                         for field in vdata.fields() {
622                             let field_vis = ty::Visibility::from_hir(&field.vis, node_id, self.tcx);
623                             if ctor_vis.is_at_least(field_vis, self.tcx) {
624                                 ctor_vis = field_vis;
625                             }
626                         }
627                         return ctor_vis;
628                     }
629                     node => bug!("unexpected node kind: {:?}", node)
630                 };
631                 ty::Visibility::from_hir(vis, node_id, self.tcx)
632             }
633             None => self.tcx.sess.cstore.visibility(did),
634         }
635     }
636
637     fn item_is_accessible(&self, did: DefId) -> bool {
638         self.def_id_visibility(did).is_accessible_from(self.current_item, self.tcx)
639     }
640
641     // Take node ID of an expression or pattern and check its type for privacy.
642     fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
643         self.span = span;
644         if let Some(ty) = self.tables.node_id_to_type_opt(id) {
645             if ty.visit_with(self) {
646                 return true;
647             }
648         }
649         if self.tables.node_substs(id).visit_with(self) {
650             return true;
651         }
652         if let Some(adjustments) = self.tables.adjustments().get(id) {
653             for adjustment in adjustments {
654                 if adjustment.target.visit_with(self) {
655                     return true;
656                 }
657             }
658         }
659         false
660     }
661
662     fn check_item(&mut self, item_id: ast::NodeId) -> &mut Self {
663         self.current_item = self.tcx.hir.local_def_id(item_id);
664         self.span = self.tcx.hir.span(item_id);
665         self
666     }
667
668     // Convenience methods for checking item interfaces
669     fn ty(&mut self) -> &mut Self {
670         self.tcx.type_of(self.current_item).visit_with(self);
671         self
672     }
673
674     fn generics(&mut self) -> &mut Self {
675         for def in &self.tcx.generics_of(self.current_item).types {
676             if def.has_default {
677                 self.tcx.type_of(def.def_id).visit_with(self);
678             }
679         }
680         self
681     }
682
683     fn predicates(&mut self) -> &mut Self {
684         let predicates = self.tcx.predicates_of(self.current_item);
685         for predicate in &predicates.predicates {
686             predicate.visit_with(self);
687             match predicate {
688                 &ty::Predicate::Trait(poly_predicate) => {
689                     self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
690                 },
691                 &ty::Predicate::Projection(poly_predicate) => {
692                     let tcx = self.tcx;
693                     self.check_trait_ref(
694                         poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
695                     );
696                 },
697                 _ => (),
698             };
699         }
700         self
701     }
702
703     fn impl_trait_ref(&mut self) -> &mut Self {
704         if let Some(impl_trait_ref) = self.tcx.impl_trait_ref(self.current_item) {
705             self.check_trait_ref(impl_trait_ref);
706         }
707         self.tcx.predicates_of(self.current_item).visit_with(self);
708         self
709     }
710
711     fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
712         if !self.item_is_accessible(trait_ref.def_id) {
713             let msg = format!("trait `{}` is private", trait_ref);
714             self.tcx.sess.span_err(self.span, &msg);
715             return true;
716         }
717
718         trait_ref.super_visit_with(self)
719     }
720 }
721
722 impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
723     /// We want to visit items in the context of their containing
724     /// module and so forth, so supply a crate for doing a deep walk.
725     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
726         NestedVisitorMap::All(&self.tcx.hir)
727     }
728
729     fn visit_nested_body(&mut self, body: hir::BodyId) {
730         let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
731         let body = self.tcx.hir.body(body);
732         self.visit_body(body);
733         self.tables = orig_tables;
734     }
735
736     // Check types of expressions
737     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
738         if self.check_expr_pat_type(expr.hir_id, expr.span) {
739             // Do not check nested expressions if the error already happened.
740             return;
741         }
742         match expr.node {
743             hir::ExprAssign(.., ref rhs) | hir::ExprMatch(ref rhs, ..) => {
744                 // Do not report duplicate errors for `x = y` and `match x { ... }`.
745                 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
746                     return;
747                 }
748             }
749             hir::ExprMethodCall(_, span, _) => {
750                 // Method calls have to be checked specially.
751                 let def_id = self.tables.type_dependent_defs()[expr.hir_id].def_id();
752                 self.span = span;
753                 if self.tcx.type_of(def_id).visit_with(self) {
754                     return;
755                 }
756             }
757             _ => {}
758         }
759
760         intravisit::walk_expr(self, expr);
761     }
762
763     fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: ast::NodeId, span: Span) {
764         // Inherent associated constants don't have self type in substs,
765         // we have to check it additionally.
766         if let hir::QPath::TypeRelative(..) = *qpath {
767             let hir_id = self.tcx.hir.node_to_hir_id(id);
768             if let Some(def) = self.tables.type_dependent_defs().get(hir_id).cloned() {
769                 if let Some(assoc_item) = self.tcx.opt_associated_item(def.def_id()) {
770                     if let ty::ImplContainer(impl_def_id) = assoc_item.container {
771                         if self.tcx.type_of(impl_def_id).visit_with(self) {
772                             return;
773                         }
774                     }
775                 }
776             }
777         }
778
779         intravisit::walk_qpath(self, qpath, id, span);
780     }
781
782     // Check types of patterns
783     fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
784         if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
785             // Do not check nested patterns if the error already happened.
786             return;
787         }
788
789         intravisit::walk_pat(self, pattern);
790     }
791
792     fn visit_local(&mut self, local: &'tcx hir::Local) {
793         if let Some(ref init) = local.init {
794             if self.check_expr_pat_type(init.hir_id, init.span) {
795                 // Do not report duplicate errors for `let x = y`.
796                 return;
797             }
798         }
799
800         intravisit::walk_local(self, local);
801     }
802
803     // Check types in item interfaces
804     fn visit_item(&mut self, item: &'tcx hir::Item) {
805         let orig_current_item = self.current_item;
806         let orig_tables = update_tables(self.tcx,
807                                         item.id,
808                                         &mut self.tables,
809                                         self.empty_tables);
810
811         match item.node {
812             hir::ItemExternCrate(..) | hir::ItemMod(..) |
813             hir::ItemUse(..) | hir::ItemGlobalAsm(..) => {}
814             hir::ItemConst(..) | hir::ItemStatic(..) |
815             hir::ItemTy(..) | hir::ItemFn(..) => {
816                 self.check_item(item.id).generics().predicates().ty();
817             }
818             hir::ItemTrait(.., ref trait_item_refs) => {
819                 self.check_item(item.id).generics().predicates();
820                 for trait_item_ref in trait_item_refs {
821                     let check = self.check_item(trait_item_ref.id.node_id);
822                     check.generics().predicates();
823                     if trait_item_ref.kind != hir::AssociatedItemKind::Type ||
824                        trait_item_ref.defaultness.has_value() {
825                         check.ty();
826                     }
827                 }
828             }
829             hir::ItemEnum(ref def, _) => {
830                 self.check_item(item.id).generics().predicates();
831                 for variant in &def.variants {
832                     for field in variant.node.data.fields() {
833                         self.check_item(field.id).ty();
834                     }
835                 }
836             }
837             hir::ItemForeignMod(ref foreign_mod) => {
838                 for foreign_item in &foreign_mod.items {
839                     self.check_item(foreign_item.id).generics().predicates().ty();
840                 }
841             }
842             hir::ItemStruct(ref struct_def, _) |
843             hir::ItemUnion(ref struct_def, _) => {
844                 self.check_item(item.id).generics().predicates();
845                 for field in struct_def.fields() {
846                     self.check_item(field.id).ty();
847                 }
848             }
849             hir::ItemDefaultImpl(..) => {
850                 self.check_item(item.id).impl_trait_ref();
851             }
852             hir::ItemImpl(.., ref trait_ref, _, ref impl_item_refs) => {
853                 {
854                     let check = self.check_item(item.id);
855                     check.ty().generics().predicates();
856                     if trait_ref.is_some() {
857                         check.impl_trait_ref();
858                     }
859                 }
860                 for impl_item_ref in impl_item_refs {
861                     let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
862                     self.check_item(impl_item.id).generics().predicates().ty();
863                 }
864             }
865         }
866
867         self.current_item = self.tcx.hir.local_def_id(item.id);
868         intravisit::walk_item(self, item);
869         self.tables = orig_tables;
870         self.current_item = orig_current_item;
871     }
872
873     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
874         let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
875         intravisit::walk_trait_item(self, ti);
876         self.tables = orig_tables;
877     }
878
879     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
880         let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
881         intravisit::walk_impl_item(self, ii);
882         self.tables = orig_tables;
883     }
884 }
885
886 impl<'a, 'tcx> TypeVisitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
887     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
888         match ty.sty {
889             ty::TyAdt(&ty::AdtDef { did: def_id, .. }, ..) | ty::TyFnDef(def_id, ..) => {
890                 if !self.item_is_accessible(def_id) {
891                     let msg = format!("type `{}` is private", ty);
892                     self.tcx.sess.span_err(self.span, &msg);
893                     return true;
894                 }
895                 if let ty::TyFnDef(..) = ty.sty {
896                     if self.tcx.fn_sig(def_id).visit_with(self) {
897                         return true;
898                     }
899                 }
900                 // Inherent static methods don't have self type in substs,
901                 // we have to check it additionally.
902                 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
903                     if let ty::ImplContainer(impl_def_id) = assoc_item.container {
904                         if self.tcx.type_of(impl_def_id).visit_with(self) {
905                             return true;
906                         }
907                     }
908                 }
909             }
910             ty::TyDynamic(ref predicates, ..) => {
911                 let is_private = predicates.skip_binder().iter().any(|predicate| {
912                     let def_id = match *predicate {
913                         ty::ExistentialPredicate::Trait(trait_ref) => trait_ref.def_id,
914                         ty::ExistentialPredicate::Projection(proj) =>
915                             proj.trait_ref(self.tcx).def_id,
916                         ty::ExistentialPredicate::AutoTrait(def_id) => def_id,
917                     };
918                     !self.item_is_accessible(def_id)
919                 });
920                 if is_private {
921                     let msg = format!("type `{}` is private", ty);
922                     self.tcx.sess.span_err(self.span, &msg);
923                     return true;
924                 }
925             }
926             ty::TyProjection(ref proj) => {
927                 let tcx = self.tcx;
928                 if self.check_trait_ref(proj.trait_ref(tcx)) {
929                     return true;
930                 }
931             }
932             ty::TyAnon(def_id, ..) => {
933                 for predicate in &self.tcx.predicates_of(def_id).predicates {
934                     let trait_ref = match *predicate {
935                         ty::Predicate::Trait(ref poly_trait_predicate) => {
936                             Some(poly_trait_predicate.skip_binder().trait_ref)
937                         }
938                         ty::Predicate::Projection(ref poly_projection_predicate) => {
939                             if poly_projection_predicate.skip_binder().ty.visit_with(self) {
940                                 return true;
941                             }
942                             Some(poly_projection_predicate.skip_binder()
943                                                           .projection_ty.trait_ref(self.tcx))
944                         }
945                         ty::Predicate::TypeOutlives(..) => None,
946                         _ => bug!("unexpected predicate: {:?}", predicate),
947                     };
948                     if let Some(trait_ref) = trait_ref {
949                         if !self.item_is_accessible(trait_ref.def_id) {
950                             let msg = format!("trait `{}` is private", trait_ref);
951                             self.tcx.sess.span_err(self.span, &msg);
952                             return true;
953                         }
954                         // `Self` here is the same `TyAnon`, so skip it to avoid infinite recursion
955                         for subst in trait_ref.substs.iter().skip(1) {
956                             if subst.visit_with(self) {
957                                 return true;
958                             }
959                         }
960                     }
961                 }
962             }
963             _ => {}
964         }
965
966         ty.super_visit_with(self)
967     }
968 }
969
970 ///////////////////////////////////////////////////////////////////////////////
971 /// Obsolete visitors for checking for private items in public interfaces.
972 /// These visitors are supposed to be kept in frozen state and produce an
973 /// "old error node set". For backward compatibility the new visitor reports
974 /// warnings instead of hard errors when the erroneous node is not in this old set.
975 ///////////////////////////////////////////////////////////////////////////////
976
977 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
978     tcx: TyCtxt<'a, 'tcx, 'tcx>,
979     access_levels: &'a AccessLevels,
980     in_variant: bool,
981     // set of errors produced by this obsolete visitor
982     old_error_set: NodeSet,
983 }
984
985 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
986     inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
987     /// whether the type refers to private types.
988     contains_private: bool,
989     /// whether we've recurred at all (i.e. if we're pointing at the
990     /// first type on which visit_ty was called).
991     at_outer_type: bool,
992     // whether that first type is a public path.
993     outer_type_is_public_path: bool,
994 }
995
996 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
997     fn path_is_private_type(&self, path: &hir::Path) -> bool {
998         let did = match path.def {
999             Def::PrimTy(..) | Def::SelfTy(..) => return false,
1000             def => def.def_id(),
1001         };
1002
1003         // A path can only be private if:
1004         // it's in this crate...
1005         if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
1006             // .. and it corresponds to a private type in the AST (this returns
1007             // None for type parameters)
1008             match self.tcx.hir.find(node_id) {
1009                 Some(hir::map::NodeItem(ref item)) => item.vis != hir::Public,
1010                 Some(_) | None => false,
1011             }
1012         } else {
1013             return false
1014         }
1015     }
1016
1017     fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1018         // FIXME: this would preferably be using `exported_items`, but all
1019         // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1020         self.access_levels.is_public(trait_id)
1021     }
1022
1023     fn check_ty_param_bound(&mut self,
1024                             ty_param_bound: &hir::TyParamBound) {
1025         if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1026             if self.path_is_private_type(&trait_ref.trait_ref.path) {
1027                 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1028             }
1029         }
1030     }
1031
1032     fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
1033         self.access_levels.is_reachable(*id) || *vis == hir::Public
1034     }
1035 }
1036
1037 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1038     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1039         NestedVisitorMap::None
1040     }
1041
1042     fn visit_ty(&mut self, ty: &hir::Ty) {
1043         if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = ty.node {
1044             if self.inner.path_is_private_type(path) {
1045                 self.contains_private = true;
1046                 // found what we're looking for so let's stop
1047                 // working.
1048                 return
1049             }
1050         }
1051         if let hir::TyPath(_) = ty.node {
1052             if self.at_outer_type {
1053                 self.outer_type_is_public_path = true;
1054             }
1055         }
1056         self.at_outer_type = false;
1057         intravisit::walk_ty(self, ty)
1058     }
1059
1060     // don't want to recurse into [, .. expr]
1061     fn visit_expr(&mut self, _: &hir::Expr) {}
1062 }
1063
1064 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1065     /// We want to visit items in the context of their containing
1066     /// module and so forth, so supply a crate for doing a deep walk.
1067     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1068         NestedVisitorMap::All(&self.tcx.hir)
1069     }
1070
1071     fn visit_item(&mut self, item: &'tcx hir::Item) {
1072         match item.node {
1073             // contents of a private mod can be reexported, so we need
1074             // to check internals.
1075             hir::ItemMod(_) => {}
1076
1077             // An `extern {}` doesn't introduce a new privacy
1078             // namespace (the contents have their own privacies).
1079             hir::ItemForeignMod(_) => {}
1080
1081             hir::ItemTrait(.., ref bounds, _) => {
1082                 if !self.trait_is_public(item.id) {
1083                     return
1084                 }
1085
1086                 for bound in bounds.iter() {
1087                     self.check_ty_param_bound(bound)
1088                 }
1089             }
1090
1091             // impls need some special handling to try to offer useful
1092             // error messages without (too many) false positives
1093             // (i.e. we could just return here to not check them at
1094             // all, or some worse estimation of whether an impl is
1095             // publicly visible).
1096             hir::ItemImpl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
1097                 // `impl [... for] Private` is never visible.
1098                 let self_contains_private;
1099                 // impl [... for] Public<...>, but not `impl [... for]
1100                 // Vec<Public>` or `(Public,)` etc.
1101                 let self_is_public_path;
1102
1103                 // check the properties of the Self type:
1104                 {
1105                     let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1106                         inner: self,
1107                         contains_private: false,
1108                         at_outer_type: true,
1109                         outer_type_is_public_path: false,
1110                     };
1111                     visitor.visit_ty(&self_);
1112                     self_contains_private = visitor.contains_private;
1113                     self_is_public_path = visitor.outer_type_is_public_path;
1114                 }
1115
1116                 // miscellaneous info about the impl
1117
1118                 // `true` iff this is `impl Private for ...`.
1119                 let not_private_trait =
1120                     trait_ref.as_ref().map_or(true, // no trait counts as public trait
1121                                               |tr| {
1122                         let did = tr.path.def.def_id();
1123
1124                         if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
1125                             self.trait_is_public(node_id)
1126                         } else {
1127                             true // external traits must be public
1128                         }
1129                     });
1130
1131                 // `true` iff this is a trait impl or at least one method is public.
1132                 //
1133                 // `impl Public { $( fn ...() {} )* }` is not visible.
1134                 //
1135                 // This is required over just using the methods' privacy
1136                 // directly because we might have `impl<T: Foo<Private>> ...`,
1137                 // and we shouldn't warn about the generics if all the methods
1138                 // are private (because `T` won't be visible externally).
1139                 let trait_or_some_public_method =
1140                     trait_ref.is_some() ||
1141                     impl_item_refs.iter()
1142                                  .any(|impl_item_ref| {
1143                                      let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1144                                      match impl_item.node {
1145                                          hir::ImplItemKind::Const(..) |
1146                                          hir::ImplItemKind::Method(..) => {
1147                                              self.access_levels.is_reachable(impl_item.id)
1148                                          }
1149                                          hir::ImplItemKind::Type(_) => false,
1150                                      }
1151                                  });
1152
1153                 if !self_contains_private &&
1154                         not_private_trait &&
1155                         trait_or_some_public_method {
1156
1157                     intravisit::walk_generics(self, g);
1158
1159                     match *trait_ref {
1160                         None => {
1161                             for impl_item_ref in impl_item_refs {
1162                                 // This is where we choose whether to walk down
1163                                 // further into the impl to check its items. We
1164                                 // should only walk into public items so that we
1165                                 // don't erroneously report errors for private
1166                                 // types in private items.
1167                                 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1168                                 match impl_item.node {
1169                                     hir::ImplItemKind::Const(..) |
1170                                     hir::ImplItemKind::Method(..)
1171                                         if self.item_is_public(&impl_item.id, &impl_item.vis) =>
1172                                     {
1173                                         intravisit::walk_impl_item(self, impl_item)
1174                                     }
1175                                     hir::ImplItemKind::Type(..) => {
1176                                         intravisit::walk_impl_item(self, impl_item)
1177                                     }
1178                                     _ => {}
1179                                 }
1180                             }
1181                         }
1182                         Some(ref tr) => {
1183                             // Any private types in a trait impl fall into three
1184                             // categories.
1185                             // 1. mentioned in the trait definition
1186                             // 2. mentioned in the type params/generics
1187                             // 3. mentioned in the associated types of the impl
1188                             //
1189                             // Those in 1. can only occur if the trait is in
1190                             // this crate and will've been warned about on the
1191                             // trait definition (there's no need to warn twice
1192                             // so we don't check the methods).
1193                             //
1194                             // Those in 2. are warned via walk_generics and this
1195                             // call here.
1196                             intravisit::walk_path(self, &tr.path);
1197
1198                             // Those in 3. are warned with this call.
1199                             for impl_item_ref in impl_item_refs {
1200                                 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1201                                 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1202                                     self.visit_ty(ty);
1203                                 }
1204                             }
1205                         }
1206                     }
1207                 } else if trait_ref.is_none() && self_is_public_path {
1208                     // impl Public<Private> { ... }. Any public static
1209                     // methods will be visible as `Public::foo`.
1210                     let mut found_pub_static = false;
1211                     for impl_item_ref in impl_item_refs {
1212                         if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
1213                             let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1214                             match impl_item_ref.kind {
1215                                 hir::AssociatedItemKind::Const => {
1216                                     found_pub_static = true;
1217                                     intravisit::walk_impl_item(self, impl_item);
1218                                 }
1219                                 hir::AssociatedItemKind::Method { has_self: false } => {
1220                                     found_pub_static = true;
1221                                     intravisit::walk_impl_item(self, impl_item);
1222                                 }
1223                                 _ => {}
1224                             }
1225                         }
1226                     }
1227                     if found_pub_static {
1228                         intravisit::walk_generics(self, g)
1229                     }
1230                 }
1231                 return
1232             }
1233
1234             // `type ... = ...;` can contain private types, because
1235             // we're introducing a new name.
1236             hir::ItemTy(..) => return,
1237
1238             // not at all public, so we don't care
1239             _ if !self.item_is_public(&item.id, &item.vis) => {
1240                 return;
1241             }
1242
1243             _ => {}
1244         }
1245
1246         // We've carefully constructed it so that if we're here, then
1247         // any `visit_ty`'s will be called on things that are in
1248         // public signatures, i.e. things that we're interested in for
1249         // this visitor.
1250         intravisit::walk_item(self, item);
1251     }
1252
1253     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1254         for ty_param in generics.ty_params.iter() {
1255             for bound in ty_param.bounds.iter() {
1256                 self.check_ty_param_bound(bound)
1257             }
1258         }
1259         for predicate in &generics.where_clause.predicates {
1260             match predicate {
1261                 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1262                     for bound in bound_pred.bounds.iter() {
1263                         self.check_ty_param_bound(bound)
1264                     }
1265                 }
1266                 &hir::WherePredicate::RegionPredicate(_) => {}
1267                 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1268                     self.visit_ty(&eq_pred.rhs_ty);
1269                 }
1270             }
1271         }
1272     }
1273
1274     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
1275         if self.access_levels.is_reachable(item.id) {
1276             intravisit::walk_foreign_item(self, item)
1277         }
1278     }
1279
1280     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1281         if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = t.node {
1282             if self.path_is_private_type(path) {
1283                 self.old_error_set.insert(t.id);
1284             }
1285         }
1286         intravisit::walk_ty(self, t)
1287     }
1288
1289     fn visit_variant(&mut self,
1290                      v: &'tcx hir::Variant,
1291                      g: &'tcx hir::Generics,
1292                      item_id: ast::NodeId) {
1293         if self.access_levels.is_reachable(v.node.data.id()) {
1294             self.in_variant = true;
1295             intravisit::walk_variant(self, v, g, item_id);
1296             self.in_variant = false;
1297         }
1298     }
1299
1300     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
1301         if s.vis == hir::Public || self.in_variant {
1302             intravisit::walk_struct_field(self, s);
1303         }
1304     }
1305
1306     // we don't need to introspect into these at all: an
1307     // expression/block context can't possibly contain exported things.
1308     // (Making them no-ops stops us from traversing the whole AST without
1309     // having to be super careful about our `walk_...` calls above.)
1310     fn visit_block(&mut self, _: &'tcx hir::Block) {}
1311     fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1312 }
1313
1314 ///////////////////////////////////////////////////////////////////////////////
1315 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1316 /// finds any private components in it.
1317 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1318 /// and traits in public interfaces.
1319 ///////////////////////////////////////////////////////////////////////////////
1320
1321 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1322     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1323     item_def_id: DefId,
1324     span: Span,
1325     /// The visitor checks that each component type is at least this visible
1326     required_visibility: ty::Visibility,
1327     /// The visibility of the least visible component that has been visited
1328     min_visibility: ty::Visibility,
1329     has_pub_restricted: bool,
1330     has_old_errors: bool,
1331 }
1332
1333 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1334     fn generics(&mut self) -> &mut Self {
1335         for def in &self.tcx.generics_of(self.item_def_id).types {
1336             if def.has_default {
1337                 self.tcx.type_of(def.def_id).visit_with(self);
1338             }
1339         }
1340         self
1341     }
1342
1343     fn predicates(&mut self) -> &mut Self {
1344         let predicates = self.tcx.predicates_of(self.item_def_id);
1345         for predicate in &predicates.predicates {
1346             predicate.visit_with(self);
1347             match predicate {
1348                 &ty::Predicate::Trait(poly_predicate) => {
1349                     self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
1350                 },
1351                 &ty::Predicate::Projection(poly_predicate) => {
1352                     let tcx = self.tcx;
1353                     self.check_trait_ref(
1354                         poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
1355                     );
1356                 },
1357                 _ => (),
1358             };
1359         }
1360         self
1361     }
1362
1363     fn ty(&mut self) -> &mut Self {
1364         let ty = self.tcx.type_of(self.item_def_id);
1365         ty.visit_with(self);
1366         if let ty::TyFnDef(def_id, _) = ty.sty {
1367             if def_id == self.item_def_id {
1368                 self.tcx.fn_sig(def_id).visit_with(self);
1369             }
1370         }
1371         self
1372     }
1373
1374     fn impl_trait_ref(&mut self) -> &mut Self {
1375         if let Some(impl_trait_ref) = self.tcx.impl_trait_ref(self.item_def_id) {
1376             self.check_trait_ref(impl_trait_ref);
1377             impl_trait_ref.super_visit_with(self);
1378         }
1379         self
1380     }
1381
1382     fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
1383         // Non-local means public (private items can't leave their crate, modulo bugs)
1384         if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
1385             let item = self.tcx.hir.expect_item(node_id);
1386             let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1387             if !vis.is_at_least(self.min_visibility, self.tcx) {
1388                 self.min_visibility = vis;
1389             }
1390             if !vis.is_at_least(self.required_visibility, self.tcx) {
1391                 if self.has_pub_restricted || self.has_old_errors {
1392                     struct_span_err!(self.tcx.sess, self.span, E0445,
1393                                      "private trait `{}` in public interface", trait_ref)
1394                         .span_label(self.span, format!(
1395                                     "private trait can't be public"))
1396                         .emit();
1397                 } else {
1398                     self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1399                                        node_id,
1400                                        self.span,
1401                                        &format!("private trait `{}` in public \
1402                                                  interface (error E0445)", trait_ref));
1403                 }
1404             }
1405         }
1406     }
1407 }
1408
1409 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1410     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
1411         let ty_def_id = match ty.sty {
1412             ty::TyAdt(adt, _) => Some(adt.did),
1413             ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
1414             ty::TyProjection(ref proj) => {
1415                 if self.required_visibility == ty::Visibility::Invisible {
1416                     // Conservatively approximate the whole type alias as public without
1417                     // recursing into its components when determining impl publicity.
1418                     // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
1419                     // even if both `Type` and `Trait` are private.
1420                     // Ideally, associated types should be substituted in the same way as
1421                     // free type aliases, but this isn't done yet.
1422                     return false;
1423                 }
1424                 let trait_ref = proj.trait_ref(self.tcx);
1425                 Some(trait_ref.def_id)
1426             }
1427             _ => None
1428         };
1429
1430         if let Some(def_id) = ty_def_id {
1431             // Non-local means public (private items can't leave their crate, modulo bugs)
1432             if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
1433                 let item = self.tcx.hir.expect_item(node_id);
1434                 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1435
1436                 if !vis.is_at_least(self.min_visibility, self.tcx) {
1437                     self.min_visibility = vis;
1438                 }
1439                 if !vis.is_at_least(self.required_visibility, self.tcx) {
1440                     if self.has_pub_restricted || self.has_old_errors {
1441                         let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
1442                             "private type `{}` in public interface", ty);
1443                         err.span_label(self.span, "can't leak private type");
1444                         err.emit();
1445                     } else {
1446                         self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1447                                            node_id,
1448                                            self.span,
1449                                            &format!("private type `{}` in public \
1450                                                      interface (error E0446)", ty));
1451                     }
1452                 }
1453             }
1454         }
1455
1456         ty.super_visit_with(self)
1457     }
1458 }
1459
1460 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1461     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1462     has_pub_restricted: bool,
1463     old_error_set: &'a NodeSet,
1464     inner_visibility: ty::Visibility,
1465 }
1466
1467 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1468     fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1469              -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1470         let mut has_old_errors = false;
1471
1472         // Slow path taken only if there any errors in the crate.
1473         for &id in self.old_error_set {
1474             // Walk up the nodes until we find `item_id` (or we hit a root).
1475             let mut id = id;
1476             loop {
1477                 if id == item_id {
1478                     has_old_errors = true;
1479                     break;
1480                 }
1481                 let parent = self.tcx.hir.get_parent_node(id);
1482                 if parent == id {
1483                     break;
1484                 }
1485                 id = parent;
1486             }
1487
1488             if has_old_errors {
1489                 break;
1490             }
1491         }
1492
1493         SearchInterfaceForPrivateItemsVisitor {
1494             tcx: self.tcx,
1495             item_def_id: self.tcx.hir.local_def_id(item_id),
1496             span: self.tcx.hir.span(item_id),
1497             min_visibility: ty::Visibility::Public,
1498             required_visibility,
1499             has_pub_restricted: self.has_pub_restricted,
1500             has_old_errors,
1501         }
1502     }
1503 }
1504
1505 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1506     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1507         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
1508     }
1509
1510     fn visit_item(&mut self, item: &'tcx hir::Item) {
1511         let tcx = self.tcx;
1512         let min = |vis1: ty::Visibility, vis2| {
1513             if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1514         };
1515
1516         let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1517
1518         match item.node {
1519             // Crates are always public
1520             hir::ItemExternCrate(..) => {}
1521             // All nested items are checked by visit_item
1522             hir::ItemMod(..) => {}
1523             // Checked in resolve
1524             hir::ItemUse(..) => {}
1525             // No subitems
1526             hir::ItemGlobalAsm(..) => {}
1527             // Subitems of these items have inherited publicity
1528             hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1529             hir::ItemTy(..) => {
1530                 self.check(item.id, item_visibility).generics().predicates().ty();
1531
1532                 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1533                 self.inner_visibility = item_visibility;
1534                 intravisit::walk_item(self, item);
1535             }
1536             hir::ItemTrait(.., ref trait_item_refs) => {
1537                 self.check(item.id, item_visibility).generics().predicates();
1538
1539                 for trait_item_ref in trait_item_refs {
1540                     let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1541                     check.generics().predicates();
1542
1543                     if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1544                        !trait_item_ref.defaultness.has_value() {
1545                         // No type to visit.
1546                     } else {
1547                         check.ty();
1548                     }
1549                 }
1550             }
1551             hir::ItemEnum(ref def, _) => {
1552                 self.check(item.id, item_visibility).generics().predicates();
1553
1554                 for variant in &def.variants {
1555                     for field in variant.node.data.fields() {
1556                         self.check(field.id, item_visibility).ty();
1557                     }
1558                 }
1559             }
1560             // Subitems of foreign modules have their own publicity
1561             hir::ItemForeignMod(ref foreign_mod) => {
1562                 for foreign_item in &foreign_mod.items {
1563                     let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1564                     self.check(foreign_item.id, vis).generics().predicates().ty();
1565                 }
1566             }
1567             // Subitems of structs and unions have their own publicity
1568             hir::ItemStruct(ref struct_def, _) |
1569             hir::ItemUnion(ref struct_def, _) => {
1570                 self.check(item.id, item_visibility).generics().predicates();
1571
1572                 for field in struct_def.fields() {
1573                     let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1574                     self.check(field.id, min(item_visibility, field_visibility)).ty();
1575                 }
1576             }
1577             // The interface is empty
1578             hir::ItemDefaultImpl(..) => {}
1579             // An inherent impl is public when its type is public
1580             // Subitems of inherent impls have their own publicity
1581             hir::ItemImpl(.., None, _, ref impl_item_refs) => {
1582                 let ty_vis =
1583                     self.check(item.id, ty::Visibility::Invisible).ty().min_visibility;
1584                 self.check(item.id, ty_vis).generics().predicates();
1585
1586                 for impl_item_ref in impl_item_refs {
1587                     let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1588                     let impl_item_vis =
1589                         ty::Visibility::from_hir(&impl_item.vis, item.id, tcx);
1590                     self.check(impl_item.id, min(impl_item_vis, ty_vis))
1591                         .generics().predicates().ty();
1592
1593                     // Recurse for e.g. `impl Trait` (see `visit_ty`).
1594                     self.inner_visibility = impl_item_vis;
1595                     intravisit::walk_impl_item(self, impl_item);
1596                 }
1597             }
1598             // A trait impl is public when both its type and its trait are public
1599             // Subitems of trait impls have inherited publicity
1600             hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
1601                 let vis = self.check(item.id, ty::Visibility::Invisible)
1602                               .ty().impl_trait_ref().min_visibility;
1603                 self.check(item.id, vis).generics().predicates();
1604                 for impl_item_ref in impl_item_refs {
1605                     let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1606                     self.check(impl_item.id, vis).generics().predicates().ty();
1607
1608                     // Recurse for e.g. `impl Trait` (see `visit_ty`).
1609                     self.inner_visibility = vis;
1610                     intravisit::walk_impl_item(self, impl_item);
1611                 }
1612             }
1613         }
1614     }
1615
1616     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
1617         // handled in `visit_item` above
1618     }
1619
1620     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1621         if let hir::TyImplTrait(..) = ty.node {
1622             // Check the traits being exposed, as they're separate,
1623             // e.g. `impl Iterator<Item=T>` has two predicates,
1624             // `X: Iterator` and `<X as Iterator>::Item == T`,
1625             // where `X` is the `impl Iterator<Item=T>` itself,
1626             // stored in `predicates_of`, not in the `Ty` itself.
1627             self.check(ty.id, self.inner_visibility).predicates();
1628         }
1629
1630         intravisit::walk_ty(self, ty);
1631     }
1632
1633     // Don't recurse into expressions in array sizes or const initializers
1634     fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1635     // Don't recurse into patterns in function arguments
1636     fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
1637 }
1638
1639 pub fn provide(providers: &mut Providers) {
1640     *providers = Providers {
1641         privacy_access_levels,
1642         ..*providers
1643     };
1644 }
1645
1646 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Rc<AccessLevels> {
1647     tcx.dep_graph.with_ignore(|| { // FIXME
1648         tcx.privacy_access_levels(LOCAL_CRATE)
1649     })
1650 }
1651
1652 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1653                                    krate: CrateNum)
1654                                    -> Rc<AccessLevels> {
1655     assert_eq!(krate, LOCAL_CRATE);
1656
1657     let krate = tcx.hir.krate();
1658     let empty_tables = ty::TypeckTables::empty(None);
1659
1660     // Check privacy of names not checked in previous compilation stages.
1661     let mut visitor = NamePrivacyVisitor {
1662         tcx,
1663         tables: &empty_tables,
1664         current_item: CRATE_NODE_ID,
1665         empty_tables: &empty_tables,
1666     };
1667     intravisit::walk_crate(&mut visitor, krate);
1668
1669     // Check privacy of explicitly written types and traits as well as
1670     // inferred types of expressions and patterns.
1671     let mut visitor = TypePrivacyVisitor {
1672         tcx,
1673         tables: &empty_tables,
1674         current_item: DefId::local(CRATE_DEF_INDEX),
1675         span: krate.span,
1676         empty_tables: &empty_tables,
1677     };
1678     intravisit::walk_crate(&mut visitor, krate);
1679
1680     // Build up a set of all exported items in the AST. This is a set of all
1681     // items which are reachable from external crates based on visibility.
1682     let mut visitor = EmbargoVisitor {
1683         tcx,
1684         access_levels: Default::default(),
1685         prev_level: Some(AccessLevel::Public),
1686         changed: false,
1687     };
1688     loop {
1689         intravisit::walk_crate(&mut visitor, krate);
1690         if visitor.changed {
1691             visitor.changed = false;
1692         } else {
1693             break
1694         }
1695     }
1696     visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1697
1698     {
1699         let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1700             tcx,
1701             access_levels: &visitor.access_levels,
1702             in_variant: false,
1703             old_error_set: NodeSet(),
1704         };
1705         intravisit::walk_crate(&mut visitor, krate);
1706
1707
1708         let has_pub_restricted = {
1709             let mut pub_restricted_visitor = PubRestrictedVisitor {
1710                 tcx,
1711                 has_pub_restricted: false
1712             };
1713             intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1714             pub_restricted_visitor.has_pub_restricted
1715         };
1716
1717         // Check for private types and traits in public interfaces
1718         let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1719             tcx,
1720             has_pub_restricted,
1721             old_error_set: &visitor.old_error_set,
1722             inner_visibility: ty::Visibility::Public,
1723         };
1724         krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1725     }
1726
1727     Rc::new(visitor.access_levels)
1728 }
1729
1730 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }