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