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