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