]> git.lizzy.rs Git - rust.git/blob - src/librustc_privacy/lib.rs
Merge branch 'hide-trait-map' into rollup
[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::TyAnon(def_id, _) => Some(def_id),
451             _ => None
452         };
453
454         if let Some(def_id) = ty_def_id {
455             if let Some(node_id) = self.ev.tcx.hir.as_local_node_id(def_id) {
456                 self.ev.update(node_id, Some(AccessLevel::Reachable));
457             }
458         }
459
460         ty.super_visit_with(self)
461     }
462 }
463
464 //////////////////////////////////////////////////////////////////////////////////////
465 /// Name privacy visitor, checks privacy and reports violations.
466 /// Most of name privacy checks are performed during the main resolution phase,
467 /// or later in type checking when field accesses and associated items are resolved.
468 /// This pass performs remaining checks for fields in struct expressions and patterns.
469 //////////////////////////////////////////////////////////////////////////////////////
470
471 struct NamePrivacyVisitor<'a, 'tcx: 'a> {
472     tcx: TyCtxt<'a, 'tcx, 'tcx>,
473     tables: &'a ty::TypeckTables<'tcx>,
474     current_item: ast::NodeId,
475     empty_tables: &'a ty::TypeckTables<'tcx>,
476 }
477
478 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
479     // Checks that a field is accessible.
480     fn check_field(&mut self, span: Span, def: &'tcx ty::AdtDef, field: &'tcx ty::FieldDef) {
481         let ident = Ident { ctxt: span.ctxt().modern(), ..keywords::Invalid.ident() };
482         let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
483         if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
484             struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
485                              field.name, def.variant_descr(), self.tcx.item_path_str(def.did))
486                 .span_label(span, format!("field `{}` is private", field.name))
487                 .emit();
488         }
489     }
490 }
491
492 // Set the correct TypeckTables for the given `item_id` (or an empty table if
493 // there is no TypeckTables for the item).
494 fn update_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
495                            item_id: ast::NodeId,
496                            tables: &mut &'a ty::TypeckTables<'tcx>,
497                            empty_tables: &'a ty::TypeckTables<'tcx>)
498                            -> &'a ty::TypeckTables<'tcx> {
499     let def_id = tcx.hir.local_def_id(item_id);
500
501     if tcx.has_typeck_tables(def_id) {
502         replace(tables, tcx.typeck_tables_of(def_id))
503     } else {
504         replace(tables, empty_tables)
505     }
506 }
507
508 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
509     /// We want to visit items in the context of their containing
510     /// module and so forth, so supply a crate for doing a deep walk.
511     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
512         NestedVisitorMap::All(&self.tcx.hir)
513     }
514
515     fn visit_nested_body(&mut self, body: hir::BodyId) {
516         let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
517         let body = self.tcx.hir.body(body);
518         self.visit_body(body);
519         self.tables = orig_tables;
520     }
521
522     fn visit_item(&mut self, item: &'tcx hir::Item) {
523         let orig_current_item = replace(&mut self.current_item, item.id);
524         let orig_tables = update_tables(self.tcx, item.id, &mut self.tables, self.empty_tables);
525         intravisit::walk_item(self, item);
526         self.current_item = orig_current_item;
527         self.tables = orig_tables;
528     }
529
530     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
531         let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
532         intravisit::walk_trait_item(self, ti);
533         self.tables = orig_tables;
534     }
535
536     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
537         let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
538         intravisit::walk_impl_item(self, ii);
539         self.tables = orig_tables;
540     }
541
542     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
543         match expr.node {
544             hir::ExprStruct(ref qpath, ref fields, ref base) => {
545                 let def = self.tables.qpath_def(qpath, expr.hir_id);
546                 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
547                 let variant = adt.variant_of_def(def);
548                 if let Some(ref base) = *base {
549                     // If the expression uses FRU we need to make sure all the unmentioned fields
550                     // are checked for privacy (RFC 736). Rather than computing the set of
551                     // unmentioned fields, just check them all.
552                     for variant_field in &variant.fields {
553                         let field = fields.iter().find(|f| f.name.node == variant_field.name);
554                         let span = if let Some(f) = field { f.span } else { base.span };
555                         self.check_field(span, adt, variant_field);
556                     }
557                 } else {
558                     for field in fields {
559                         self.check_field(field.span, adt, variant.field_named(field.name.node));
560                     }
561                 }
562             }
563             _ => {}
564         }
565
566         intravisit::walk_expr(self, expr);
567     }
568
569     fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
570         match pat.node {
571             PatKind::Struct(ref qpath, ref fields, _) => {
572                 let def = self.tables.qpath_def(qpath, pat.hir_id);
573                 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
574                 let variant = adt.variant_of_def(def);
575                 for field in fields {
576                     self.check_field(field.span, adt, variant.field_named(field.node.name));
577                 }
578             }
579             _ => {}
580         }
581
582         intravisit::walk_pat(self, pat);
583     }
584 }
585
586 ////////////////////////////////////////////////////////////////////////////////////////////
587 /// Type privacy visitor, checks types for privacy and reports violations.
588 /// Both explicitly written types and inferred types of expressions and patters are checked.
589 /// Checks are performed on "semantic" types regardless of names and their hygiene.
590 ////////////////////////////////////////////////////////////////////////////////////////////
591
592 struct TypePrivacyVisitor<'a, 'tcx: 'a> {
593     tcx: TyCtxt<'a, 'tcx, 'tcx>,
594     tables: &'a ty::TypeckTables<'tcx>,
595     current_item: DefId,
596     span: Span,
597     empty_tables: &'a ty::TypeckTables<'tcx>,
598 }
599
600 impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
601     fn def_id_visibility(&self, did: DefId) -> ty::Visibility {
602         match self.tcx.hir.as_local_node_id(did) {
603             Some(node_id) => {
604                 let vis = match self.tcx.hir.get(node_id) {
605                     hir::map::NodeItem(item) => &item.vis,
606                     hir::map::NodeForeignItem(foreign_item) => &foreign_item.vis,
607                     hir::map::NodeImplItem(impl_item) => &impl_item.vis,
608                     hir::map::NodeTraitItem(..) |
609                     hir::map::NodeVariant(..) => {
610                         return self.def_id_visibility(self.tcx.hir.get_parent_did(node_id));
611                     }
612                     hir::map::NodeStructCtor(vdata) => {
613                         let struct_node_id = self.tcx.hir.get_parent(node_id);
614                         let struct_vis = match self.tcx.hir.get(struct_node_id) {
615                             hir::map::NodeItem(item) => &item.vis,
616                             node => bug!("unexpected node kind: {:?}", node),
617                         };
618                         let mut ctor_vis
619                             = ty::Visibility::from_hir(struct_vis, struct_node_id, self.tcx);
620                         for field in vdata.fields() {
621                             let field_vis = ty::Visibility::from_hir(&field.vis, node_id, self.tcx);
622                             if ctor_vis.is_at_least(field_vis, self.tcx) {
623                                 ctor_vis = field_vis;
624                             }
625                         }
626                         return ctor_vis;
627                     }
628                     node => bug!("unexpected node kind: {:?}", node)
629                 };
630                 ty::Visibility::from_hir(vis, node_id, self.tcx)
631             }
632             None => self.tcx.sess.cstore.visibility(did),
633         }
634     }
635
636     fn item_is_accessible(&self, did: DefId) -> bool {
637         self.def_id_visibility(did).is_accessible_from(self.current_item, self.tcx)
638     }
639
640     // Take node ID of an expression or pattern and check its type for privacy.
641     fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
642         self.span = span;
643         if let Some(ty) = self.tables.node_id_to_type_opt(id) {
644             if ty.visit_with(self) {
645                 return true;
646             }
647         }
648         if self.tables.node_substs(id).visit_with(self) {
649             return true;
650         }
651         if let Some(adjustments) = self.tables.adjustments().get(id) {
652             for adjustment in adjustments {
653                 if adjustment.target.visit_with(self) {
654                     return true;
655                 }
656             }
657         }
658         false
659     }
660
661     fn check_item(&mut self, item_id: ast::NodeId) -> &mut Self {
662         self.current_item = self.tcx.hir.local_def_id(item_id);
663         self.span = self.tcx.hir.span(item_id);
664         self
665     }
666
667     // Convenience methods for checking item interfaces
668     fn ty(&mut self) -> &mut Self {
669         self.tcx.type_of(self.current_item).visit_with(self);
670         self
671     }
672
673     fn generics(&mut self) -> &mut Self {
674         for def in &self.tcx.generics_of(self.current_item).types {
675             if def.has_default {
676                 self.tcx.type_of(def.def_id).visit_with(self);
677             }
678         }
679         self
680     }
681
682     fn predicates(&mut self) -> &mut Self {
683         let predicates = self.tcx.predicates_of(self.current_item);
684         for predicate in &predicates.predicates {
685             predicate.visit_with(self);
686             match predicate {
687                 &ty::Predicate::Trait(poly_predicate) => {
688                     self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
689                 },
690                 &ty::Predicate::Projection(poly_predicate) => {
691                     let tcx = self.tcx;
692                     self.check_trait_ref(
693                         poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
694                     );
695                 },
696                 _ => (),
697             };
698         }
699         self
700     }
701
702     fn impl_trait_ref(&mut self) -> &mut Self {
703         if let Some(impl_trait_ref) = self.tcx.impl_trait_ref(self.current_item) {
704             self.check_trait_ref(impl_trait_ref);
705         }
706         self.tcx.predicates_of(self.current_item).visit_with(self);
707         self
708     }
709
710     fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
711         if !self.item_is_accessible(trait_ref.def_id) {
712             let msg = format!("trait `{}` is private", trait_ref);
713             self.tcx.sess.span_err(self.span, &msg);
714             return true;
715         }
716
717         trait_ref.super_visit_with(self)
718     }
719 }
720
721 impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
722     /// We want to visit items in the context of their containing
723     /// module and so forth, so supply a crate for doing a deep walk.
724     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
725         NestedVisitorMap::All(&self.tcx.hir)
726     }
727
728     fn visit_nested_body(&mut self, body: hir::BodyId) {
729         let orig_tables = replace(&mut self.tables, self.tcx.body_tables(body));
730         let body = self.tcx.hir.body(body);
731         self.visit_body(body);
732         self.tables = orig_tables;
733     }
734
735     // Check types of expressions
736     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
737         if self.check_expr_pat_type(expr.hir_id, expr.span) {
738             // Do not check nested expressions if the error already happened.
739             return;
740         }
741         match expr.node {
742             hir::ExprAssign(.., ref rhs) | hir::ExprMatch(ref rhs, ..) => {
743                 // Do not report duplicate errors for `x = y` and `match x { ... }`.
744                 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
745                     return;
746                 }
747             }
748             hir::ExprMethodCall(_, span, _) => {
749                 // Method calls have to be checked specially.
750                 let def_id = self.tables.type_dependent_defs()[expr.hir_id].def_id();
751                 self.span = span;
752                 if self.tcx.type_of(def_id).visit_with(self) {
753                     return;
754                 }
755             }
756             _ => {}
757         }
758
759         intravisit::walk_expr(self, expr);
760     }
761
762     fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: ast::NodeId, span: Span) {
763         // Inherent associated constants don't have self type in substs,
764         // we have to check it additionally.
765         if let hir::QPath::TypeRelative(..) = *qpath {
766             let hir_id = self.tcx.hir.node_to_hir_id(id);
767             if let Some(def) = self.tables.type_dependent_defs().get(hir_id).cloned() {
768                 if let Some(assoc_item) = self.tcx.opt_associated_item(def.def_id()) {
769                     if let ty::ImplContainer(impl_def_id) = assoc_item.container {
770                         if self.tcx.type_of(impl_def_id).visit_with(self) {
771                             return;
772                         }
773                     }
774                 }
775             }
776         }
777
778         intravisit::walk_qpath(self, qpath, id, span);
779     }
780
781     // Check types of patterns
782     fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
783         if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
784             // Do not check nested patterns if the error already happened.
785             return;
786         }
787
788         intravisit::walk_pat(self, pattern);
789     }
790
791     fn visit_local(&mut self, local: &'tcx hir::Local) {
792         if let Some(ref init) = local.init {
793             if self.check_expr_pat_type(init.hir_id, init.span) {
794                 // Do not report duplicate errors for `let x = y`.
795                 return;
796             }
797         }
798
799         intravisit::walk_local(self, local);
800     }
801
802     // Check types in item interfaces
803     fn visit_item(&mut self, item: &'tcx hir::Item) {
804         let orig_current_item = self.current_item;
805         let orig_tables = update_tables(self.tcx,
806                                         item.id,
807                                         &mut self.tables,
808                                         self.empty_tables);
809
810         match item.node {
811             hir::ItemExternCrate(..) | hir::ItemMod(..) |
812             hir::ItemUse(..) | hir::ItemGlobalAsm(..) => {}
813             hir::ItemConst(..) | hir::ItemStatic(..) |
814             hir::ItemTy(..) | hir::ItemFn(..) => {
815                 self.check_item(item.id).generics().predicates().ty();
816             }
817             hir::ItemTrait(.., ref trait_item_refs) => {
818                 self.check_item(item.id).generics().predicates();
819                 for trait_item_ref in trait_item_refs {
820                     let check = self.check_item(trait_item_ref.id.node_id);
821                     check.generics().predicates();
822                     if trait_item_ref.kind != hir::AssociatedItemKind::Type ||
823                        trait_item_ref.defaultness.has_value() {
824                         check.ty();
825                     }
826                 }
827             }
828             hir::ItemEnum(ref def, _) => {
829                 self.check_item(item.id).generics().predicates();
830                 for variant in &def.variants {
831                     for field in variant.node.data.fields() {
832                         self.check_item(field.id).ty();
833                     }
834                 }
835             }
836             hir::ItemForeignMod(ref foreign_mod) => {
837                 for foreign_item in &foreign_mod.items {
838                     self.check_item(foreign_item.id).generics().predicates().ty();
839                 }
840             }
841             hir::ItemStruct(ref struct_def, _) |
842             hir::ItemUnion(ref struct_def, _) => {
843                 self.check_item(item.id).generics().predicates();
844                 for field in struct_def.fields() {
845                     self.check_item(field.id).ty();
846                 }
847             }
848             hir::ItemDefaultImpl(..) => {
849                 self.check_item(item.id).impl_trait_ref();
850             }
851             hir::ItemImpl(.., ref trait_ref, _, ref impl_item_refs) => {
852                 {
853                     let check = self.check_item(item.id);
854                     check.ty().generics().predicates();
855                     if trait_ref.is_some() {
856                         check.impl_trait_ref();
857                     }
858                 }
859                 for impl_item_ref in impl_item_refs {
860                     let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
861                     self.check_item(impl_item.id).generics().predicates().ty();
862                 }
863             }
864         }
865
866         self.current_item = self.tcx.hir.local_def_id(item.id);
867         intravisit::walk_item(self, item);
868         self.tables = orig_tables;
869         self.current_item = orig_current_item;
870     }
871
872     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
873         let orig_tables = update_tables(self.tcx, ti.id, &mut self.tables, self.empty_tables);
874         intravisit::walk_trait_item(self, ti);
875         self.tables = orig_tables;
876     }
877
878     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
879         let orig_tables = update_tables(self.tcx, ii.id, &mut self.tables, self.empty_tables);
880         intravisit::walk_impl_item(self, ii);
881         self.tables = orig_tables;
882     }
883 }
884
885 impl<'a, 'tcx> TypeVisitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
886     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
887         match ty.sty {
888             ty::TyAdt(&ty::AdtDef { did: def_id, .. }, ..) | ty::TyFnDef(def_id, ..) => {
889                 if !self.item_is_accessible(def_id) {
890                     let msg = format!("type `{}` is private", ty);
891                     self.tcx.sess.span_err(self.span, &msg);
892                     return true;
893                 }
894                 if let ty::TyFnDef(..) = ty.sty {
895                     if self.tcx.fn_sig(def_id).visit_with(self) {
896                         return true;
897                     }
898                 }
899                 // Inherent static methods don't have self type in substs,
900                 // we have to check it additionally.
901                 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id) {
902                     if let ty::ImplContainer(impl_def_id) = assoc_item.container {
903                         if self.tcx.type_of(impl_def_id).visit_with(self) {
904                             return true;
905                         }
906                     }
907                 }
908             }
909             ty::TyDynamic(ref predicates, ..) => {
910                 let is_private = predicates.skip_binder().iter().any(|predicate| {
911                     let def_id = match *predicate {
912                         ty::ExistentialPredicate::Trait(trait_ref) => trait_ref.def_id,
913                         ty::ExistentialPredicate::Projection(proj) =>
914                             proj.trait_ref(self.tcx).def_id,
915                         ty::ExistentialPredicate::AutoTrait(def_id) => def_id,
916                     };
917                     !self.item_is_accessible(def_id)
918                 });
919                 if is_private {
920                     let msg = format!("type `{}` is private", ty);
921                     self.tcx.sess.span_err(self.span, &msg);
922                     return true;
923                 }
924             }
925             ty::TyProjection(ref proj) => {
926                 let tcx = self.tcx;
927                 if self.check_trait_ref(proj.trait_ref(tcx)) {
928                     return true;
929                 }
930             }
931             ty::TyAnon(def_id, ..) => {
932                 for predicate in &self.tcx.predicates_of(def_id).predicates {
933                     let trait_ref = match *predicate {
934                         ty::Predicate::Trait(ref poly_trait_predicate) => {
935                             Some(poly_trait_predicate.skip_binder().trait_ref)
936                         }
937                         ty::Predicate::Projection(ref poly_projection_predicate) => {
938                             if poly_projection_predicate.skip_binder().ty.visit_with(self) {
939                                 return true;
940                             }
941                             Some(poly_projection_predicate.skip_binder()
942                                                           .projection_ty.trait_ref(self.tcx))
943                         }
944                         ty::Predicate::TypeOutlives(..) => None,
945                         _ => bug!("unexpected predicate: {:?}", predicate),
946                     };
947                     if let Some(trait_ref) = trait_ref {
948                         if !self.item_is_accessible(trait_ref.def_id) {
949                             let msg = format!("trait `{}` is private", trait_ref);
950                             self.tcx.sess.span_err(self.span, &msg);
951                             return true;
952                         }
953                         // `Self` here is the same `TyAnon`, so skip it to avoid infinite recursion
954                         for subst in trait_ref.substs.iter().skip(1) {
955                             if subst.visit_with(self) {
956                                 return true;
957                             }
958                         }
959                     }
960                 }
961             }
962             _ => {}
963         }
964
965         ty.super_visit_with(self)
966     }
967 }
968
969 ///////////////////////////////////////////////////////////////////////////////
970 /// Obsolete visitors for checking for private items in public interfaces.
971 /// These visitors are supposed to be kept in frozen state and produce an
972 /// "old error node set". For backward compatibility the new visitor reports
973 /// warnings instead of hard errors when the erroneous node is not in this old set.
974 ///////////////////////////////////////////////////////////////////////////////
975
976 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
977     tcx: TyCtxt<'a, 'tcx, 'tcx>,
978     access_levels: &'a AccessLevels,
979     in_variant: bool,
980     // set of errors produced by this obsolete visitor
981     old_error_set: NodeSet,
982 }
983
984 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
985     inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
986     /// whether the type refers to private types.
987     contains_private: bool,
988     /// whether we've recurred at all (i.e. if we're pointing at the
989     /// first type on which visit_ty was called).
990     at_outer_type: bool,
991     // whether that first type is a public path.
992     outer_type_is_public_path: bool,
993 }
994
995 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
996     fn path_is_private_type(&self, path: &hir::Path) -> bool {
997         let did = match path.def {
998             Def::PrimTy(..) | Def::SelfTy(..) => return false,
999             def => def.def_id(),
1000         };
1001
1002         // A path can only be private if:
1003         // it's in this crate...
1004         if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
1005             // .. and it corresponds to a private type in the AST (this returns
1006             // None for type parameters)
1007             match self.tcx.hir.find(node_id) {
1008                 Some(hir::map::NodeItem(ref item)) => item.vis != hir::Public,
1009                 Some(_) | None => false,
1010             }
1011         } else {
1012             return false
1013         }
1014     }
1015
1016     fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1017         // FIXME: this would preferably be using `exported_items`, but all
1018         // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1019         self.access_levels.is_public(trait_id)
1020     }
1021
1022     fn check_ty_param_bound(&mut self,
1023                             ty_param_bound: &hir::TyParamBound) {
1024         if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1025             if self.path_is_private_type(&trait_ref.trait_ref.path) {
1026                 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1027             }
1028         }
1029     }
1030
1031     fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
1032         self.access_levels.is_reachable(*id) || *vis == hir::Public
1033     }
1034 }
1035
1036 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1037     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1038         NestedVisitorMap::None
1039     }
1040
1041     fn visit_ty(&mut self, ty: &hir::Ty) {
1042         if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = ty.node {
1043             if self.inner.path_is_private_type(path) {
1044                 self.contains_private = true;
1045                 // found what we're looking for so let's stop
1046                 // working.
1047                 return
1048             }
1049         }
1050         if let hir::TyPath(_) = ty.node {
1051             if self.at_outer_type {
1052                 self.outer_type_is_public_path = true;
1053             }
1054         }
1055         self.at_outer_type = false;
1056         intravisit::walk_ty(self, ty)
1057     }
1058
1059     // don't want to recurse into [, .. expr]
1060     fn visit_expr(&mut self, _: &hir::Expr) {}
1061 }
1062
1063 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1064     /// We want to visit items in the context of their containing
1065     /// module and so forth, so supply a crate for doing a deep walk.
1066     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1067         NestedVisitorMap::All(&self.tcx.hir)
1068     }
1069
1070     fn visit_item(&mut self, item: &'tcx hir::Item) {
1071         match item.node {
1072             // contents of a private mod can be reexported, so we need
1073             // to check internals.
1074             hir::ItemMod(_) => {}
1075
1076             // An `extern {}` doesn't introduce a new privacy
1077             // namespace (the contents have their own privacies).
1078             hir::ItemForeignMod(_) => {}
1079
1080             hir::ItemTrait(.., ref bounds, _) => {
1081                 if !self.trait_is_public(item.id) {
1082                     return
1083                 }
1084
1085                 for bound in bounds.iter() {
1086                     self.check_ty_param_bound(bound)
1087                 }
1088             }
1089
1090             // impls need some special handling to try to offer useful
1091             // error messages without (too many) false positives
1092             // (i.e. we could just return here to not check them at
1093             // all, or some worse estimation of whether an impl is
1094             // publicly visible).
1095             hir::ItemImpl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
1096                 // `impl [... for] Private` is never visible.
1097                 let self_contains_private;
1098                 // impl [... for] Public<...>, but not `impl [... for]
1099                 // Vec<Public>` or `(Public,)` etc.
1100                 let self_is_public_path;
1101
1102                 // check the properties of the Self type:
1103                 {
1104                     let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1105                         inner: self,
1106                         contains_private: false,
1107                         at_outer_type: true,
1108                         outer_type_is_public_path: false,
1109                     };
1110                     visitor.visit_ty(&self_);
1111                     self_contains_private = visitor.contains_private;
1112                     self_is_public_path = visitor.outer_type_is_public_path;
1113                 }
1114
1115                 // miscellaneous info about the impl
1116
1117                 // `true` iff this is `impl Private for ...`.
1118                 let not_private_trait =
1119                     trait_ref.as_ref().map_or(true, // no trait counts as public trait
1120                                               |tr| {
1121                         let did = tr.path.def.def_id();
1122
1123                         if let Some(node_id) = self.tcx.hir.as_local_node_id(did) {
1124                             self.trait_is_public(node_id)
1125                         } else {
1126                             true // external traits must be public
1127                         }
1128                     });
1129
1130                 // `true` iff this is a trait impl or at least one method is public.
1131                 //
1132                 // `impl Public { $( fn ...() {} )* }` is not visible.
1133                 //
1134                 // This is required over just using the methods' privacy
1135                 // directly because we might have `impl<T: Foo<Private>> ...`,
1136                 // and we shouldn't warn about the generics if all the methods
1137                 // are private (because `T` won't be visible externally).
1138                 let trait_or_some_public_method =
1139                     trait_ref.is_some() ||
1140                     impl_item_refs.iter()
1141                                  .any(|impl_item_ref| {
1142                                      let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1143                                      match impl_item.node {
1144                                          hir::ImplItemKind::Const(..) |
1145                                          hir::ImplItemKind::Method(..) => {
1146                                              self.access_levels.is_reachable(impl_item.id)
1147                                          }
1148                                          hir::ImplItemKind::Type(_) => false,
1149                                      }
1150                                  });
1151
1152                 if !self_contains_private &&
1153                         not_private_trait &&
1154                         trait_or_some_public_method {
1155
1156                     intravisit::walk_generics(self, g);
1157
1158                     match *trait_ref {
1159                         None => {
1160                             for impl_item_ref in impl_item_refs {
1161                                 // This is where we choose whether to walk down
1162                                 // further into the impl to check its items. We
1163                                 // should only walk into public items so that we
1164                                 // don't erroneously report errors for private
1165                                 // types in private items.
1166                                 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1167                                 match impl_item.node {
1168                                     hir::ImplItemKind::Const(..) |
1169                                     hir::ImplItemKind::Method(..)
1170                                         if self.item_is_public(&impl_item.id, &impl_item.vis) =>
1171                                     {
1172                                         intravisit::walk_impl_item(self, impl_item)
1173                                     }
1174                                     hir::ImplItemKind::Type(..) => {
1175                                         intravisit::walk_impl_item(self, impl_item)
1176                                     }
1177                                     _ => {}
1178                                 }
1179                             }
1180                         }
1181                         Some(ref tr) => {
1182                             // Any private types in a trait impl fall into three
1183                             // categories.
1184                             // 1. mentioned in the trait definition
1185                             // 2. mentioned in the type params/generics
1186                             // 3. mentioned in the associated types of the impl
1187                             //
1188                             // Those in 1. can only occur if the trait is in
1189                             // this crate and will've been warned about on the
1190                             // trait definition (there's no need to warn twice
1191                             // so we don't check the methods).
1192                             //
1193                             // Those in 2. are warned via walk_generics and this
1194                             // call here.
1195                             intravisit::walk_path(self, &tr.path);
1196
1197                             // Those in 3. are warned with this call.
1198                             for impl_item_ref in impl_item_refs {
1199                                 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1200                                 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1201                                     self.visit_ty(ty);
1202                                 }
1203                             }
1204                         }
1205                     }
1206                 } else if trait_ref.is_none() && self_is_public_path {
1207                     // impl Public<Private> { ... }. Any public static
1208                     // methods will be visible as `Public::foo`.
1209                     let mut found_pub_static = false;
1210                     for impl_item_ref in impl_item_refs {
1211                         if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
1212                             let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1213                             match impl_item_ref.kind {
1214                                 hir::AssociatedItemKind::Const => {
1215                                     found_pub_static = true;
1216                                     intravisit::walk_impl_item(self, impl_item);
1217                                 }
1218                                 hir::AssociatedItemKind::Method { has_self: false } => {
1219                                     found_pub_static = true;
1220                                     intravisit::walk_impl_item(self, impl_item);
1221                                 }
1222                                 _ => {}
1223                             }
1224                         }
1225                     }
1226                     if found_pub_static {
1227                         intravisit::walk_generics(self, g)
1228                     }
1229                 }
1230                 return
1231             }
1232
1233             // `type ... = ...;` can contain private types, because
1234             // we're introducing a new name.
1235             hir::ItemTy(..) => return,
1236
1237             // not at all public, so we don't care
1238             _ if !self.item_is_public(&item.id, &item.vis) => {
1239                 return;
1240             }
1241
1242             _ => {}
1243         }
1244
1245         // We've carefully constructed it so that if we're here, then
1246         // any `visit_ty`'s will be called on things that are in
1247         // public signatures, i.e. things that we're interested in for
1248         // this visitor.
1249         intravisit::walk_item(self, item);
1250     }
1251
1252     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1253         for ty_param in generics.ty_params.iter() {
1254             for bound in ty_param.bounds.iter() {
1255                 self.check_ty_param_bound(bound)
1256             }
1257         }
1258         for predicate in &generics.where_clause.predicates {
1259             match predicate {
1260                 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
1261                     for bound in bound_pred.bounds.iter() {
1262                         self.check_ty_param_bound(bound)
1263                     }
1264                 }
1265                 &hir::WherePredicate::RegionPredicate(_) => {}
1266                 &hir::WherePredicate::EqPredicate(ref eq_pred) => {
1267                     self.visit_ty(&eq_pred.rhs_ty);
1268                 }
1269             }
1270         }
1271     }
1272
1273     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
1274         if self.access_levels.is_reachable(item.id) {
1275             intravisit::walk_foreign_item(self, item)
1276         }
1277     }
1278
1279     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1280         if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = t.node {
1281             if self.path_is_private_type(path) {
1282                 self.old_error_set.insert(t.id);
1283             }
1284         }
1285         intravisit::walk_ty(self, t)
1286     }
1287
1288     fn visit_variant(&mut self,
1289                      v: &'tcx hir::Variant,
1290                      g: &'tcx hir::Generics,
1291                      item_id: ast::NodeId) {
1292         if self.access_levels.is_reachable(v.node.data.id()) {
1293             self.in_variant = true;
1294             intravisit::walk_variant(self, v, g, item_id);
1295             self.in_variant = false;
1296         }
1297     }
1298
1299     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
1300         if s.vis == hir::Public || self.in_variant {
1301             intravisit::walk_struct_field(self, s);
1302         }
1303     }
1304
1305     // we don't need to introspect into these at all: an
1306     // expression/block context can't possibly contain exported things.
1307     // (Making them no-ops stops us from traversing the whole AST without
1308     // having to be super careful about our `walk_...` calls above.)
1309     fn visit_block(&mut self, _: &'tcx hir::Block) {}
1310     fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1311 }
1312
1313 ///////////////////////////////////////////////////////////////////////////////
1314 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1315 /// finds any private components in it.
1316 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1317 /// and traits in public interfaces.
1318 ///////////////////////////////////////////////////////////////////////////////
1319
1320 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1321     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1322     item_def_id: DefId,
1323     span: Span,
1324     /// The visitor checks that each component type is at least this visible
1325     required_visibility: ty::Visibility,
1326     /// The visibility of the least visible component that has been visited
1327     min_visibility: ty::Visibility,
1328     has_pub_restricted: bool,
1329     has_old_errors: bool,
1330 }
1331
1332 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1333     fn generics(&mut self) -> &mut Self {
1334         for def in &self.tcx.generics_of(self.item_def_id).types {
1335             if def.has_default {
1336                 self.tcx.type_of(def.def_id).visit_with(self);
1337             }
1338         }
1339         self
1340     }
1341
1342     fn predicates(&mut self) -> &mut Self {
1343         let predicates = self.tcx.predicates_of(self.item_def_id);
1344         for predicate in &predicates.predicates {
1345             predicate.visit_with(self);
1346             match predicate {
1347                 &ty::Predicate::Trait(poly_predicate) => {
1348                     self.check_trait_ref(poly_predicate.skip_binder().trait_ref);
1349                 },
1350                 &ty::Predicate::Projection(poly_predicate) => {
1351                     let tcx = self.tcx;
1352                     self.check_trait_ref(
1353                         poly_predicate.skip_binder().projection_ty.trait_ref(tcx)
1354                     );
1355                 },
1356                 _ => (),
1357             };
1358         }
1359         self
1360     }
1361
1362     fn ty(&mut self) -> &mut Self {
1363         let ty = self.tcx.type_of(self.item_def_id);
1364         ty.visit_with(self);
1365         if let ty::TyFnDef(def_id, _) = ty.sty {
1366             if def_id == self.item_def_id {
1367                 self.tcx.fn_sig(def_id).visit_with(self);
1368             }
1369         }
1370         self
1371     }
1372
1373     fn impl_trait_ref(&mut self) -> &mut Self {
1374         if let Some(impl_trait_ref) = self.tcx.impl_trait_ref(self.item_def_id) {
1375             self.check_trait_ref(impl_trait_ref);
1376             impl_trait_ref.super_visit_with(self);
1377         }
1378         self
1379     }
1380
1381     fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) {
1382         // Non-local means public (private items can't leave their crate, modulo bugs)
1383         if let Some(node_id) = self.tcx.hir.as_local_node_id(trait_ref.def_id) {
1384             let item = self.tcx.hir.expect_item(node_id);
1385             let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1386             if !vis.is_at_least(self.min_visibility, self.tcx) {
1387                 self.min_visibility = vis;
1388             }
1389             if !vis.is_at_least(self.required_visibility, self.tcx) {
1390                 if self.has_pub_restricted || self.has_old_errors {
1391                     struct_span_err!(self.tcx.sess, self.span, E0445,
1392                                      "private trait `{}` in public interface", trait_ref)
1393                         .span_label(self.span, format!(
1394                                     "private trait can't be public"))
1395                         .emit();
1396                 } else {
1397                     self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1398                                        node_id,
1399                                        self.span,
1400                                        &format!("private trait `{}` in public \
1401                                                  interface (error E0445)", trait_ref));
1402                 }
1403             }
1404         }
1405     }
1406 }
1407
1408 impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1409     fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
1410         let ty_def_id = match ty.sty {
1411             ty::TyAdt(adt, _) => Some(adt.did),
1412             ty::TyDynamic(ref obj, ..) => obj.principal().map(|p| p.def_id()),
1413             ty::TyProjection(ref proj) => {
1414                 if self.required_visibility == ty::Visibility::Invisible {
1415                     // Conservatively approximate the whole type alias as public without
1416                     // recursing into its components when determining impl publicity.
1417                     // For example, `impl <Type as Trait>::Alias {...}` may be a public impl
1418                     // even if both `Type` and `Trait` are private.
1419                     // Ideally, associated types should be substituted in the same way as
1420                     // free type aliases, but this isn't done yet.
1421                     return false;
1422                 }
1423                 let trait_ref = proj.trait_ref(self.tcx);
1424                 Some(trait_ref.def_id)
1425             }
1426             _ => None
1427         };
1428
1429         if let Some(def_id) = ty_def_id {
1430             // Non-local means public (private items can't leave their crate, modulo bugs)
1431             if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
1432                 let item = self.tcx.hir.expect_item(node_id);
1433                 let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx);
1434
1435                 if !vis.is_at_least(self.min_visibility, self.tcx) {
1436                     self.min_visibility = vis;
1437                 }
1438                 if !vis.is_at_least(self.required_visibility, self.tcx) {
1439                     if self.has_pub_restricted || self.has_old_errors {
1440                         let mut err = struct_span_err!(self.tcx.sess, self.span, E0446,
1441                             "private type `{}` in public interface", ty);
1442                         err.span_label(self.span, "can't leak private type");
1443                         err.emit();
1444                     } else {
1445                         self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC,
1446                                            node_id,
1447                                            self.span,
1448                                            &format!("private type `{}` in public \
1449                                                      interface (error E0446)", ty));
1450                     }
1451                 }
1452             }
1453         }
1454
1455         ty.super_visit_with(self)
1456     }
1457 }
1458
1459 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1460     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1461     has_pub_restricted: bool,
1462     old_error_set: &'a NodeSet,
1463     inner_visibility: ty::Visibility,
1464 }
1465
1466 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1467     fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1468              -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1469         let mut has_old_errors = false;
1470
1471         // Slow path taken only if there any errors in the crate.
1472         for &id in self.old_error_set {
1473             // Walk up the nodes until we find `item_id` (or we hit a root).
1474             let mut id = id;
1475             loop {
1476                 if id == item_id {
1477                     has_old_errors = true;
1478                     break;
1479                 }
1480                 let parent = self.tcx.hir.get_parent_node(id);
1481                 if parent == id {
1482                     break;
1483                 }
1484                 id = parent;
1485             }
1486
1487             if has_old_errors {
1488                 break;
1489             }
1490         }
1491
1492         SearchInterfaceForPrivateItemsVisitor {
1493             tcx: self.tcx,
1494             item_def_id: self.tcx.hir.local_def_id(item_id),
1495             span: self.tcx.hir.span(item_id),
1496             min_visibility: ty::Visibility::Public,
1497             required_visibility,
1498             has_pub_restricted: self.has_pub_restricted,
1499             has_old_errors,
1500         }
1501     }
1502 }
1503
1504 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1505     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1506         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
1507     }
1508
1509     fn visit_item(&mut self, item: &'tcx hir::Item) {
1510         let tcx = self.tcx;
1511         let min = |vis1: ty::Visibility, vis2| {
1512             if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
1513         };
1514
1515         let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1516
1517         match item.node {
1518             // Crates are always public
1519             hir::ItemExternCrate(..) => {}
1520             // All nested items are checked by visit_item
1521             hir::ItemMod(..) => {}
1522             // Checked in resolve
1523             hir::ItemUse(..) => {}
1524             // No subitems
1525             hir::ItemGlobalAsm(..) => {}
1526             // Subitems of these items have inherited publicity
1527             hir::ItemConst(..) | hir::ItemStatic(..) | hir::ItemFn(..) |
1528             hir::ItemTy(..) => {
1529                 self.check(item.id, item_visibility).generics().predicates().ty();
1530
1531                 // Recurse for e.g. `impl Trait` (see `visit_ty`).
1532                 self.inner_visibility = item_visibility;
1533                 intravisit::walk_item(self, item);
1534             }
1535             hir::ItemTrait(.., ref trait_item_refs) => {
1536                 self.check(item.id, item_visibility).generics().predicates();
1537
1538                 for trait_item_ref in trait_item_refs {
1539                     let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1540                     check.generics().predicates();
1541
1542                     if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1543                        !trait_item_ref.defaultness.has_value() {
1544                         // No type to visit.
1545                     } else {
1546                         check.ty();
1547                     }
1548                 }
1549             }
1550             hir::ItemEnum(ref def, _) => {
1551                 self.check(item.id, item_visibility).generics().predicates();
1552
1553                 for variant in &def.variants {
1554                     for field in variant.node.data.fields() {
1555                         self.check(field.id, item_visibility).ty();
1556                     }
1557                 }
1558             }
1559             // Subitems of foreign modules have their own publicity
1560             hir::ItemForeignMod(ref foreign_mod) => {
1561                 for foreign_item in &foreign_mod.items {
1562                     let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1563                     self.check(foreign_item.id, vis).generics().predicates().ty();
1564                 }
1565             }
1566             // Subitems of structs and unions have their own publicity
1567             hir::ItemStruct(ref struct_def, _) |
1568             hir::ItemUnion(ref struct_def, _) => {
1569                 self.check(item.id, item_visibility).generics().predicates();
1570
1571                 for field in struct_def.fields() {
1572                     let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1573                     self.check(field.id, min(item_visibility, field_visibility)).ty();
1574                 }
1575             }
1576             // The interface is empty
1577             hir::ItemDefaultImpl(..) => {}
1578             // An inherent impl is public when its type is public
1579             // Subitems of inherent impls have their own publicity
1580             hir::ItemImpl(.., None, _, ref impl_item_refs) => {
1581                 let ty_vis =
1582                     self.check(item.id, ty::Visibility::Invisible).ty().min_visibility;
1583                 self.check(item.id, ty_vis).generics().predicates();
1584
1585                 for impl_item_ref in impl_item_refs {
1586                     let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1587                     let impl_item_vis =
1588                         ty::Visibility::from_hir(&impl_item.vis, item.id, tcx);
1589                     self.check(impl_item.id, min(impl_item_vis, ty_vis))
1590                         .generics().predicates().ty();
1591
1592                     // Recurse for e.g. `impl Trait` (see `visit_ty`).
1593                     self.inner_visibility = impl_item_vis;
1594                     intravisit::walk_impl_item(self, impl_item);
1595                 }
1596             }
1597             // A trait impl is public when both its type and its trait are public
1598             // Subitems of trait impls have inherited publicity
1599             hir::ItemImpl(.., Some(_), _, ref impl_item_refs) => {
1600                 let vis = self.check(item.id, ty::Visibility::Invisible)
1601                               .ty().impl_trait_ref().min_visibility;
1602                 self.check(item.id, vis).generics().predicates();
1603                 for impl_item_ref in impl_item_refs {
1604                     let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
1605                     self.check(impl_item.id, vis).generics().predicates().ty();
1606
1607                     // Recurse for e.g. `impl Trait` (see `visit_ty`).
1608                     self.inner_visibility = vis;
1609                     intravisit::walk_impl_item(self, impl_item);
1610                 }
1611             }
1612         }
1613     }
1614
1615     fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) {
1616         // handled in `visit_item` above
1617     }
1618
1619     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1620         if let hir::TyImplTrait(..) = ty.node {
1621             // Check the traits being exposed, as they're separate,
1622             // e.g. `impl Iterator<Item=T>` has two predicates,
1623             // `X: Iterator` and `<X as Iterator>::Item == T`,
1624             // where `X` is the `impl Iterator<Item=T>` itself,
1625             // stored in `predicates_of`, not in the `Ty` itself.
1626             self.check(ty.id, self.inner_visibility).predicates();
1627         }
1628
1629         intravisit::walk_ty(self, ty);
1630     }
1631
1632     // Don't recurse into expressions in array sizes or const initializers
1633     fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1634     // Don't recurse into patterns in function arguments
1635     fn visit_pat(&mut self, _: &'tcx hir::Pat) {}
1636 }
1637
1638 pub fn provide(providers: &mut Providers) {
1639     *providers = Providers {
1640         privacy_access_levels,
1641         ..*providers
1642     };
1643 }
1644
1645 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Rc<AccessLevels> {
1646     tcx.dep_graph.with_ignore(|| { // FIXME
1647         tcx.privacy_access_levels(LOCAL_CRATE)
1648     })
1649 }
1650
1651 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1652                                    krate: CrateNum)
1653                                    -> Rc<AccessLevels> {
1654     assert_eq!(krate, LOCAL_CRATE);
1655
1656     let krate = tcx.hir.krate();
1657     let empty_tables = ty::TypeckTables::empty(None);
1658
1659     // Check privacy of names not checked in previous compilation stages.
1660     let mut visitor = NamePrivacyVisitor {
1661         tcx,
1662         tables: &empty_tables,
1663         current_item: CRATE_NODE_ID,
1664         empty_tables: &empty_tables,
1665     };
1666     intravisit::walk_crate(&mut visitor, krate);
1667
1668     // Check privacy of explicitly written types and traits as well as
1669     // inferred types of expressions and patterns.
1670     let mut visitor = TypePrivacyVisitor {
1671         tcx,
1672         tables: &empty_tables,
1673         current_item: DefId::local(CRATE_DEF_INDEX),
1674         span: krate.span,
1675         empty_tables: &empty_tables,
1676     };
1677     intravisit::walk_crate(&mut visitor, krate);
1678
1679     // Build up a set of all exported items in the AST. This is a set of all
1680     // items which are reachable from external crates based on visibility.
1681     let mut visitor = EmbargoVisitor {
1682         tcx,
1683         access_levels: Default::default(),
1684         prev_level: Some(AccessLevel::Public),
1685         changed: false,
1686     };
1687     loop {
1688         intravisit::walk_crate(&mut visitor, krate);
1689         if visitor.changed {
1690             visitor.changed = false;
1691         } else {
1692             break
1693         }
1694     }
1695     visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1696
1697     {
1698         let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1699             tcx,
1700             access_levels: &visitor.access_levels,
1701             in_variant: false,
1702             old_error_set: NodeSet(),
1703         };
1704         intravisit::walk_crate(&mut visitor, krate);
1705
1706
1707         let has_pub_restricted = {
1708             let mut pub_restricted_visitor = PubRestrictedVisitor {
1709                 tcx,
1710                 has_pub_restricted: false
1711             };
1712             intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1713             pub_restricted_visitor.has_pub_restricted
1714         };
1715
1716         // Check for private types and traits in public interfaces
1717         let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1718             tcx,
1719             has_pub_restricted,
1720             old_error_set: &visitor.old_error_set,
1721             inner_visibility: ty::Visibility::Public,
1722         };
1723         krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1724     }
1725
1726     Rc::new(visitor.access_levels)
1727 }
1728
1729 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }