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