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