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