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