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