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