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