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