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