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