1 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
2 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
3 html_root_url = "https://doc.rust-lang.org/nightly/")]
6 #![feature(rustc_diagnostic_macros)]
8 #![recursion_limit="256"]
10 #[macro_use] extern crate rustc;
11 #[macro_use] extern crate syntax;
12 extern crate rustc_typeck;
13 extern crate syntax_pos;
14 extern crate rustc_data_structures;
16 use rustc::hir::{self, Node, PatKind};
17 use rustc::hir::def::Def;
18 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
19 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
20 use rustc::hir::itemlikevisit::DeepVisitor;
22 use rustc::middle::privacy::{AccessLevel, AccessLevels};
23 use rustc::ty::{self, TyCtxt, Ty, TraitRef, TypeFoldable, GenericParamDefKind};
24 use rustc::ty::fold::TypeVisitor;
25 use rustc::ty::query::Providers;
26 use rustc::ty::subst::Substs;
27 use rustc::util::nodemap::NodeSet;
28 use rustc_data_structures::fx::FxHashSet;
29 use rustc_data_structures::sync::Lrc;
30 use syntax::ast::{self, CRATE_NODE_ID, Ident};
32 use syntax::symbol::keywords;
35 use std::{cmp, fmt, mem};
36 use std::marker::PhantomData;
40 ////////////////////////////////////////////////////////////////////////////////
41 /// Generic infrastructure used to implement specific visitors below.
42 ////////////////////////////////////////////////////////////////////////////////
44 /// Implemented to visit all `DefId`s in a type.
45 /// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them.
46 /// The idea is to visit "all components of a type", as documented in
47 /// https://github.com/rust-lang/rfcs/blob/master/text/2145-type-privacy.md#how-to-determine-visibility-of-a-type
48 /// Default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings.
49 /// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait def-ids
50 /// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
51 /// in `impl Trait`, see individual commits in `DefIdVisitorSkeleton::visit_ty`.
52 trait DefIdVisitor<'a, 'tcx: 'a> {
53 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx>;
54 fn recurse(&self) -> bool { true }
55 fn recurse_into_assoc_tys(&self) -> bool { true }
56 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool;
58 /// Not overridden, but used to actually visit types and traits.
59 fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'a, 'tcx, Self> {
60 DefIdVisitorSkeleton {
62 visited_opaque_tys: Default::default(),
63 dummy: Default::default(),
66 fn visit(&mut self, ty_fragment: impl TypeFoldable<'tcx>) -> bool {
67 ty_fragment.visit_with(&mut self.skeleton())
69 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> bool {
70 self.skeleton().visit_trait(trait_ref)
72 fn visit_predicates(&mut self, predicates: Lrc<ty::GenericPredicates<'tcx>>) -> bool {
73 self.skeleton().visit_predicates(predicates)
77 struct DefIdVisitorSkeleton<'v, 'a, 'tcx, V>
78 where V: DefIdVisitor<'a, 'tcx> + ?Sized
80 def_id_visitor: &'v mut V,
81 visited_opaque_tys: FxHashSet<DefId>,
82 dummy: PhantomData<TyCtxt<'a, 'tcx, 'tcx>>,
85 impl<'a, 'tcx, V> DefIdVisitorSkeleton<'_, 'a, 'tcx, V>
86 where V: DefIdVisitor<'a, 'tcx> + ?Sized
88 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> bool {
89 let TraitRef { def_id, substs } = trait_ref;
90 self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref) ||
91 self.def_id_visitor.recurse() && substs.visit_with(self)
94 fn visit_predicates(&mut self, predicates: Lrc<ty::GenericPredicates<'tcx>>) -> bool {
95 let ty::GenericPredicates { parent: _, predicates } = &*predicates;
96 for (predicate, _span) in predicates {
98 ty::Predicate::Trait(poly_predicate) => {
99 let ty::TraitPredicate { trait_ref } = *poly_predicate.skip_binder();
100 if self.visit_trait(trait_ref) {
104 ty::Predicate::Projection(poly_predicate) => {
105 let ty::ProjectionPredicate { projection_ty, ty } =
106 *poly_predicate.skip_binder();
107 if ty.visit_with(self) {
110 if self.visit_trait(projection_ty.trait_ref(self.def_id_visitor.tcx())) {
114 ty::Predicate::TypeOutlives(poly_predicate) => {
115 let ty::OutlivesPredicate(ty, _region) = *poly_predicate.skip_binder();
116 if ty.visit_with(self) {
120 ty::Predicate::RegionOutlives(..) => {},
121 _ => bug!("unexpected predicate: {:?}", predicate),
128 impl<'a, 'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'a, 'tcx, V>
129 where V: DefIdVisitor<'a, 'tcx> + ?Sized
131 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
132 let tcx = self.def_id_visitor.tcx();
133 // Substs are not visited here because they are visited below in `super_visit_with`.
135 ty::Adt(&ty::AdtDef { did: def_id, .. }, ..) |
136 ty::Foreign(def_id) |
137 ty::FnDef(def_id, ..) |
138 ty::Closure(def_id, ..) |
139 ty::Generator(def_id, ..) => {
140 if self.def_id_visitor.visit_def_id(def_id, "type", ty) {
143 // Default type visitor doesn't visit signatures of fn types.
144 // Something like `fn() -> Priv {my_func}` is considered a private type even if
145 // `my_func` is public, so we need to visit signatures.
146 if let ty::FnDef(..) = ty.sty {
147 if tcx.fn_sig(def_id).visit_with(self) {
151 // Inherent static methods don't have self type in substs.
152 // Something like `fn() {my_method}` type of the method
153 // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type,
154 // so we need to visit the self type additionally.
155 if let Some(assoc_item) = tcx.opt_associated_item(def_id) {
156 if let ty::ImplContainer(impl_def_id) = assoc_item.container {
157 if tcx.type_of(impl_def_id).visit_with(self) {
163 ty::Projection(proj) | ty::UnnormalizedProjection(proj) => {
164 if !self.def_id_visitor.recurse_into_assoc_tys() {
165 // Visitors searching for minimal visibility/reachability want to
166 // conservatively approximate associated types like `<Type as Trait>::Alias`
167 // as visible/reachable even if both `Type` and `Trait` are private.
168 // Ideally, associated types should be substituted in the same way as
169 // free type aliases, but this isn't done yet.
172 // This will also visit substs if necessary, so we don't need to recurse.
173 return self.visit_trait(proj.trait_ref(tcx));
175 ty::Dynamic(predicates, ..) => {
176 for predicate in *predicates.skip_binder() {
177 let trait_ref = match *predicate {
178 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
179 ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
180 ty::ExistentialPredicate::AutoTrait(def_id) =>
181 ty::ExistentialTraitRef { def_id, substs: Substs::empty() },
183 let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref;
184 if self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref) {
189 ty::Opaque(def_id, ..) => {
190 // Skip repeated `Opaque`s to avoid infinite recursion.
191 if self.visited_opaque_tys.insert(def_id) {
192 // Default type visitor doesn't visit traits in `impl Trait`.
193 // Something like `impl PrivTr` is considered a private type,
194 // so we need to visit the traits additionally.
195 if self.visit_predicates(tcx.predicates_of(def_id)) {
200 // These types don't have their own def-ids (but may have subcomponents
201 // with def-ids that should be visited recursively).
202 ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
203 ty::Float(..) | ty::Str | ty::Never |
204 ty::Array(..) | ty::Slice(..) | ty::Tuple(..) |
205 ty::RawPtr(..) | ty::Ref(..) | ty::FnPtr(..) |
206 ty::Param(..) | ty::Error | ty::GeneratorWitness(..) => {}
207 ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) =>
208 bug!("unexpected type: {:?}", ty),
211 self.def_id_visitor.recurse() && ty.super_visit_with(self)
215 fn def_id_visibility<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
216 -> (ty::Visibility, Span, &'static str) {
217 match tcx.hir().as_local_node_id(def_id) {
219 let vis = match tcx.hir().get(node_id) {
220 Node::Item(item) => &item.vis,
221 Node::ForeignItem(foreign_item) => &foreign_item.vis,
222 Node::TraitItem(..) | Node::Variant(..) => {
223 return def_id_visibility(tcx, tcx.hir().get_parent_did(node_id));
225 Node::ImplItem(impl_item) => {
226 match tcx.hir().get(tcx.hir().get_parent(node_id)) {
227 Node::Item(item) => match &item.node {
228 hir::ItemKind::Impl(.., None, _, _) => &impl_item.vis,
229 hir::ItemKind::Impl(.., Some(trait_ref), _, _)
230 => return def_id_visibility(tcx, trait_ref.path.def.def_id()),
231 kind => bug!("unexpected item kind: {:?}", kind),
233 node => bug!("unexpected node kind: {:?}", node),
236 Node::StructCtor(vdata) => {
237 let struct_node_id = tcx.hir().get_parent(node_id);
238 let item = match tcx.hir().get(struct_node_id) {
239 Node::Item(item) => item,
240 node => bug!("unexpected node kind: {:?}", node),
242 let (mut ctor_vis, mut span, mut descr) =
243 (ty::Visibility::from_hir(&item.vis, struct_node_id, tcx),
244 item.vis.span, item.vis.node.descr());
245 for field in vdata.fields() {
246 let field_vis = ty::Visibility::from_hir(&field.vis, node_id, tcx);
247 if ctor_vis.is_at_least(field_vis, tcx) {
248 ctor_vis = field_vis;
249 span = field.vis.span;
250 descr = field.vis.node.descr();
254 // If the structure is marked as non_exhaustive then lower the
255 // visibility to within the crate.
256 if ctor_vis == ty::Visibility::Public {
257 let adt_def = tcx.adt_def(tcx.hir().get_parent_did(node_id));
258 if adt_def.non_enum_variant().is_field_list_non_exhaustive() {
259 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
260 span = attr::find_by_name(&item.attrs, "non_exhaustive").unwrap().span;
261 descr = "crate-visible";
265 return (ctor_vis, span, descr);
267 Node::Expr(expr) => {
268 return (ty::Visibility::Restricted(tcx.hir().get_module_parent(expr.id)),
269 expr.span, "private")
271 node => bug!("unexpected node kind: {:?}", node)
273 (ty::Visibility::from_hir(vis, node_id, tcx), vis.span, vis.node.descr())
276 let vis = tcx.visibility(def_id);
277 let descr = if vis == ty::Visibility::Public { "public" } else { "private" };
278 (vis, tcx.def_span(def_id), descr)
283 // Set the correct `TypeckTables` for the given `item_id` (or an empty table if
284 // there is no `TypeckTables` for the item).
285 fn item_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
286 node_id: ast::NodeId,
287 empty_tables: &'a ty::TypeckTables<'tcx>)
288 -> &'a ty::TypeckTables<'tcx> {
289 let def_id = tcx.hir().local_def_id(node_id);
290 if tcx.has_typeck_tables(def_id) { tcx.typeck_tables_of(def_id) } else { empty_tables }
293 fn min<'a, 'tcx>(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'a, 'tcx, 'tcx>)
295 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
298 ////////////////////////////////////////////////////////////////////////////////
299 /// Visitor used to determine if pub(restricted) is used anywhere in the crate.
301 /// This is done so that `private_in_public` warnings can be turned into hard errors
302 /// in crates that have been updated to use pub(restricted).
303 ////////////////////////////////////////////////////////////////////////////////
304 struct PubRestrictedVisitor<'a, 'tcx: 'a> {
305 tcx: TyCtxt<'a, 'tcx, 'tcx>,
306 has_pub_restricted: bool,
309 impl<'a, 'tcx> Visitor<'tcx> for PubRestrictedVisitor<'a, 'tcx> {
310 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
311 NestedVisitorMap::All(&self.tcx.hir())
313 fn visit_vis(&mut self, vis: &'tcx hir::Visibility) {
314 self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted();
318 ////////////////////////////////////////////////////////////////////////////////
319 /// Visitor used to determine impl visibility and reachability.
320 ////////////////////////////////////////////////////////////////////////////////
322 struct FindMin<'a, 'tcx, VL: VisibilityLike> {
323 tcx: TyCtxt<'a, 'tcx, 'tcx>,
324 access_levels: &'a AccessLevels,
328 impl<'a, 'tcx, VL: VisibilityLike> DefIdVisitor<'a, 'tcx> for FindMin<'a, 'tcx, VL> {
329 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
330 fn recurse(&self) -> bool { VL::RECURSE }
331 fn recurse_into_assoc_tys(&self) -> bool { false }
332 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) -> bool {
333 self.min = VL::new_min(self, def_id);
338 trait VisibilityLike: Sized {
340 const RECURSE: bool = true;
341 fn new_min<'a, 'tcx>(find: &FindMin<'a, 'tcx, Self>, def_id: DefId) -> Self;
343 // Returns an over-approximation (`recurse_into_assoc_tys` = false) of visibility due to
344 // associated types for which we can't determine visibility precisely.
345 fn of_impl<'a, 'tcx>(node_id: ast::NodeId, tcx: TyCtxt<'a, 'tcx, 'tcx>,
346 access_levels: &'a AccessLevels) -> Self {
347 let mut find = FindMin { tcx, access_levels, min: Self::MAX };
348 let def_id = tcx.hir().local_def_id(node_id);
349 find.visit(tcx.type_of(def_id));
350 if let Some(trait_ref) = tcx.impl_trait_ref(def_id) {
351 find.visit_trait(trait_ref);
356 impl VisibilityLike for ty::Visibility {
357 const MAX: Self = ty::Visibility::Public;
358 fn new_min<'a, 'tcx>(find: &FindMin<'a, 'tcx, Self>, def_id: DefId) -> Self {
359 min(def_id_visibility(find.tcx, def_id).0, find.min, find.tcx)
362 impl VisibilityLike for Option<AccessLevel> {
363 const MAX: Self = Some(AccessLevel::Public);
364 // Type inference is very smart sometimes.
365 // It can make an impl reachable even some components of its type or trait are unreachable.
366 // E.g. methods of `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
367 // can be usable from other crates (#57264). So we skip substs when calculating reachability
368 // and consider an impl reachable if its "primary" type and trait are reachable.
369 const RECURSE: bool = false;
370 fn new_min<'a, 'tcx>(find: &FindMin<'a, 'tcx, Self>, def_id: DefId) -> Self {
371 cmp::min(if let Some(node_id) = find.tcx.hir().as_local_node_id(def_id) {
372 find.access_levels.map.get(&node_id).cloned()
379 ////////////////////////////////////////////////////////////////////////////////
380 /// The embargo visitor, used to determine the exports of the ast
381 ////////////////////////////////////////////////////////////////////////////////
383 struct EmbargoVisitor<'a, 'tcx: 'a> {
384 tcx: TyCtxt<'a, 'tcx, 'tcx>,
386 // Accessibility levels for reachable nodes.
387 access_levels: AccessLevels,
388 // Previous accessibility level; `None` means unreachable.
389 prev_level: Option<AccessLevel>,
390 // Has something changed in the level map?
394 struct ReachEverythingInTheInterfaceVisitor<'b, 'a: 'b, 'tcx: 'a> {
395 access_level: Option<AccessLevel>,
397 ev: &'b mut EmbargoVisitor<'a, 'tcx>,
400 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
401 fn get(&self, id: ast::NodeId) -> Option<AccessLevel> {
402 self.access_levels.map.get(&id).cloned()
405 // Updates node level and returns the updated level.
406 fn update(&mut self, id: ast::NodeId, level: Option<AccessLevel>) -> Option<AccessLevel> {
407 let old_level = self.get(id);
408 // Accessibility levels can only grow.
409 if level > old_level {
410 self.access_levels.map.insert(id, level.unwrap());
418 fn reach(&mut self, item_id: ast::NodeId, access_level: Option<AccessLevel>)
419 -> ReachEverythingInTheInterfaceVisitor<'_, 'a, 'tcx> {
420 ReachEverythingInTheInterfaceVisitor {
421 access_level: cmp::min(access_level, Some(AccessLevel::Reachable)),
422 item_def_id: self.tcx.hir().local_def_id(item_id),
428 impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> {
429 /// We want to visit items in the context of their containing
430 /// module and so forth, so supply a crate for doing a deep walk.
431 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
432 NestedVisitorMap::All(&self.tcx.hir())
435 fn visit_item(&mut self, item: &'tcx hir::Item) {
436 let inherited_item_level = match item.node {
437 hir::ItemKind::Impl(..) =>
438 Option::<AccessLevel>::of_impl(item.id, self.tcx, &self.access_levels),
439 // Foreign modules inherit level from parents.
440 hir::ItemKind::ForeignMod(..) => self.prev_level,
441 // Other `pub` items inherit levels from parents.
442 hir::ItemKind::Const(..) | hir::ItemKind::Enum(..) | hir::ItemKind::ExternCrate(..) |
443 hir::ItemKind::GlobalAsm(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) |
444 hir::ItemKind::Static(..) | hir::ItemKind::Struct(..) |
445 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) |
446 hir::ItemKind::Existential(..) |
447 hir::ItemKind::Ty(..) | hir::ItemKind::Union(..) | hir::ItemKind::Use(..) => {
448 if item.vis.node.is_pub() { self.prev_level } else { None }
452 // Update level of the item itself.
453 let item_level = self.update(item.id, inherited_item_level);
455 // Update levels of nested things.
457 hir::ItemKind::Enum(ref def, _) => {
458 for variant in &def.variants {
459 let variant_level = self.update(variant.node.data.id(), item_level);
460 for field in variant.node.data.fields() {
461 self.update(field.id, variant_level);
465 hir::ItemKind::Impl(.., ref trait_ref, _, ref impl_item_refs) => {
466 for impl_item_ref in impl_item_refs {
467 if trait_ref.is_some() || impl_item_ref.vis.node.is_pub() {
468 self.update(impl_item_ref.id.node_id, item_level);
472 hir::ItemKind::Trait(.., ref trait_item_refs) => {
473 for trait_item_ref in trait_item_refs {
474 self.update(trait_item_ref.id.node_id, item_level);
477 hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
478 if !def.is_struct() {
479 self.update(def.id(), item_level);
481 for field in def.fields() {
482 if field.vis.node.is_pub() {
483 self.update(field.id, item_level);
487 hir::ItemKind::ForeignMod(ref foreign_mod) => {
488 for foreign_item in &foreign_mod.items {
489 if foreign_item.vis.node.is_pub() {
490 self.update(foreign_item.id, item_level);
494 hir::ItemKind::Existential(..) |
495 hir::ItemKind::Use(..) |
496 hir::ItemKind::Static(..) |
497 hir::ItemKind::Const(..) |
498 hir::ItemKind::GlobalAsm(..) |
499 hir::ItemKind::Ty(..) |
500 hir::ItemKind::Mod(..) |
501 hir::ItemKind::TraitAlias(..) |
502 hir::ItemKind::Fn(..) |
503 hir::ItemKind::ExternCrate(..) => {}
506 // Mark all items in interfaces of reachable items as reachable.
508 // The interface is empty.
509 hir::ItemKind::ExternCrate(..) => {}
510 // All nested items are checked by `visit_item`.
511 hir::ItemKind::Mod(..) => {}
512 // Re-exports are handled in `visit_mod`.
513 hir::ItemKind::Use(..) => {}
514 // The interface is empty.
515 hir::ItemKind::GlobalAsm(..) => {}
516 hir::ItemKind::Existential(..) => {
517 // FIXME: This is some serious pessimization intended to workaround deficiencies
518 // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
519 // reachable if they are returned via `impl Trait`, even from private functions.
520 let exist_level = cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait));
521 self.reach(item.id, exist_level).generics().predicates().ty();
524 hir::ItemKind::Const(..) | hir::ItemKind::Static(..) |
525 hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) => {
526 if item_level.is_some() {
527 self.reach(item.id, item_level).generics().predicates().ty();
530 hir::ItemKind::Trait(.., ref trait_item_refs) => {
531 if item_level.is_some() {
532 self.reach(item.id, item_level).generics().predicates();
534 for trait_item_ref in trait_item_refs {
535 let mut reach = self.reach(trait_item_ref.id.node_id, item_level);
536 reach.generics().predicates();
538 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
539 !trait_item_ref.defaultness.has_value() {
547 hir::ItemKind::TraitAlias(..) => {
548 if item_level.is_some() {
549 self.reach(item.id, item_level).generics().predicates();
552 // Visit everything except for private impl items.
553 hir::ItemKind::Impl(.., ref impl_item_refs) => {
554 if item_level.is_some() {
555 self.reach(item.id, item_level).generics().predicates();
557 for impl_item_ref in impl_item_refs {
558 let impl_item_level = self.get(impl_item_ref.id.node_id);
559 if impl_item_level.is_some() {
560 self.reach(impl_item_ref.id.node_id, impl_item_level)
561 .generics().predicates().ty();
567 // Visit everything, but enum variants have their own levels.
568 hir::ItemKind::Enum(ref def, _) => {
569 if item_level.is_some() {
570 self.reach(item.id, item_level).generics().predicates();
572 for variant in &def.variants {
573 let variant_level = self.get(variant.node.data.id());
574 if variant_level.is_some() {
575 for field in variant.node.data.fields() {
576 self.reach(field.id, variant_level).ty();
578 // Corner case: if the variant is reachable, but its
579 // enum is not, make the enum reachable as well.
580 self.update(item.id, variant_level);
584 // Visit everything, but foreign items have their own levels.
585 hir::ItemKind::ForeignMod(ref foreign_mod) => {
586 for foreign_item in &foreign_mod.items {
587 let foreign_item_level = self.get(foreign_item.id);
588 if foreign_item_level.is_some() {
589 self.reach(foreign_item.id, foreign_item_level)
590 .generics().predicates().ty();
594 // Visit everything except for private fields.
595 hir::ItemKind::Struct(ref struct_def, _) |
596 hir::ItemKind::Union(ref struct_def, _) => {
597 if item_level.is_some() {
598 self.reach(item.id, item_level).generics().predicates();
599 for field in struct_def.fields() {
600 let field_level = self.get(field.id);
601 if field_level.is_some() {
602 self.reach(field.id, field_level).ty();
609 let orig_level = mem::replace(&mut self.prev_level, item_level);
610 intravisit::walk_item(self, item);
611 self.prev_level = orig_level;
614 fn visit_block(&mut self, b: &'tcx hir::Block) {
615 // Blocks can have public items, for example impls, but they always
616 // start as completely private regardless of publicity of a function,
617 // constant, type, field, etc., in which this block resides.
618 let orig_level = mem::replace(&mut self.prev_level, None);
619 intravisit::walk_block(self, b);
620 self.prev_level = orig_level;
623 fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
624 // This code is here instead of in visit_item so that the
625 // crate module gets processed as well.
626 if self.prev_level.is_some() {
627 let def_id = self.tcx.hir().local_def_id(id);
628 if let Some(exports) = self.tcx.module_exports(def_id) {
629 for export in exports.iter() {
630 if export.vis == ty::Visibility::Public {
631 if let Some(def_id) = export.def.opt_def_id() {
632 if let Some(node_id) = self.tcx.hir().as_local_node_id(def_id) {
633 self.update(node_id, Some(AccessLevel::Exported));
641 intravisit::walk_mod(self, m, id);
644 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
646 self.update(md.id, Some(AccessLevel::Public));
650 let module_did = ty::DefIdTree::parent(
652 self.tcx.hir().local_def_id(md.id)
654 let mut module_id = self.tcx.hir().as_local_node_id(module_did).unwrap();
655 let level = if md.vis.node.is_pub() { self.get(module_id) } else { None };
656 let level = self.update(md.id, level);
662 let module = if module_id == ast::CRATE_NODE_ID {
663 &self.tcx.hir().krate().module
664 } else if let hir::ItemKind::Mod(ref module) =
665 self.tcx.hir().expect_item(module_id).node {
670 for id in &module.item_ids {
671 self.update(id.id, level);
673 let def_id = self.tcx.hir().local_def_id(module_id);
674 if let Some(exports) = self.tcx.module_exports(def_id) {
675 for export in exports.iter() {
676 if let Some(node_id) = self.tcx.hir().as_local_node_id(export.def.def_id()) {
677 self.update(node_id, level);
682 if module_id == ast::CRATE_NODE_ID {
685 module_id = self.tcx.hir().get_parent_node(module_id);
690 impl<'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'_, 'a, 'tcx> {
691 fn generics(&mut self) -> &mut Self {
692 for param in &self.ev.tcx.generics_of(self.item_def_id).params {
694 GenericParamDefKind::Type { has_default, .. } => {
696 self.visit(self.ev.tcx.type_of(param.def_id));
699 GenericParamDefKind::Lifetime => {}
705 fn predicates(&mut self) -> &mut Self {
706 self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
710 fn ty(&mut self) -> &mut Self {
711 self.visit(self.ev.tcx.type_of(self.item_def_id));
716 impl<'a, 'tcx> DefIdVisitor<'a, 'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'a, 'tcx> {
717 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.ev.tcx }
718 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) -> bool {
719 if let Some(node_id) = self.ev.tcx.hir().as_local_node_id(def_id) {
720 self.ev.update(node_id, self.access_level);
726 //////////////////////////////////////////////////////////////////////////////////////
727 /// Name privacy visitor, checks privacy and reports violations.
728 /// Most of name privacy checks are performed during the main resolution phase,
729 /// or later in type checking when field accesses and associated items are resolved.
730 /// This pass performs remaining checks for fields in struct expressions and patterns.
731 //////////////////////////////////////////////////////////////////////////////////////
733 struct NamePrivacyVisitor<'a, 'tcx: 'a> {
734 tcx: TyCtxt<'a, 'tcx, 'tcx>,
735 tables: &'a ty::TypeckTables<'tcx>,
736 current_item: ast::NodeId,
737 empty_tables: &'a ty::TypeckTables<'tcx>,
740 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
741 // Checks that a field in a struct constructor (expression or pattern) is accessible.
742 fn check_field(&mut self,
743 use_ctxt: Span, // syntax context of the field name at the use site
744 span: Span, // span of the field pattern, e.g., `x: 0`
745 def: &'tcx ty::AdtDef, // definition of the struct or enum
746 field: &'tcx ty::FieldDef) { // definition of the field
747 let ident = Ident::new(keywords::Invalid.name(), use_ctxt);
748 let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
749 if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
750 struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
751 field.ident, def.variant_descr(), self.tcx.item_path_str(def.did))
752 .span_label(span, format!("field `{}` is private", field.ident))
758 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
759 /// We want to visit items in the context of their containing
760 /// module and so forth, so supply a crate for doing a deep walk.
761 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
762 NestedVisitorMap::All(&self.tcx.hir())
765 fn visit_nested_body(&mut self, body: hir::BodyId) {
766 let orig_tables = mem::replace(&mut self.tables, self.tcx.body_tables(body));
767 let body = self.tcx.hir().body(body);
768 self.visit_body(body);
769 self.tables = orig_tables;
772 fn visit_item(&mut self, item: &'tcx hir::Item) {
773 let orig_current_item = mem::replace(&mut self.current_item, item.id);
775 mem::replace(&mut self.tables, item_tables(self.tcx, item.id, self.empty_tables));
776 intravisit::walk_item(self, item);
777 self.current_item = orig_current_item;
778 self.tables = orig_tables;
781 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
783 mem::replace(&mut self.tables, item_tables(self.tcx, ti.id, self.empty_tables));
784 intravisit::walk_trait_item(self, ti);
785 self.tables = orig_tables;
788 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
790 mem::replace(&mut self.tables, item_tables(self.tcx, ii.id, self.empty_tables));
791 intravisit::walk_impl_item(self, ii);
792 self.tables = orig_tables;
795 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
797 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
798 let def = self.tables.qpath_def(qpath, expr.hir_id);
799 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
800 let variant = adt.variant_of_def(def);
801 if let Some(ref base) = *base {
802 // If the expression uses FRU we need to make sure all the unmentioned fields
803 // are checked for privacy (RFC 736). Rather than computing the set of
804 // unmentioned fields, just check them all.
805 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
806 let field = fields.iter().find(|f| {
807 self.tcx.field_index(f.id, self.tables) == vf_index
809 let (use_ctxt, span) = match field {
810 Some(field) => (field.ident.span, field.span),
811 None => (base.span, base.span),
813 self.check_field(use_ctxt, span, adt, variant_field);
816 for field in fields {
817 let use_ctxt = field.ident.span;
818 let index = self.tcx.field_index(field.id, self.tables);
819 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
826 intravisit::walk_expr(self, expr);
829 fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
831 PatKind::Struct(ref qpath, ref fields, _) => {
832 let def = self.tables.qpath_def(qpath, pat.hir_id);
833 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
834 let variant = adt.variant_of_def(def);
835 for field in fields {
836 let use_ctxt = field.node.ident.span;
837 let index = self.tcx.field_index(field.node.id, self.tables);
838 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
844 intravisit::walk_pat(self, pat);
848 ////////////////////////////////////////////////////////////////////////////////////////////
849 /// Type privacy visitor, checks types for privacy and reports violations.
850 /// Both explicitly written types and inferred types of expressions and patters are checked.
851 /// Checks are performed on "semantic" types regardless of names and their hygiene.
852 ////////////////////////////////////////////////////////////////////////////////////////////
854 struct TypePrivacyVisitor<'a, 'tcx: 'a> {
855 tcx: TyCtxt<'a, 'tcx, 'tcx>,
856 tables: &'a ty::TypeckTables<'tcx>,
860 empty_tables: &'a ty::TypeckTables<'tcx>,
863 impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
864 fn item_is_accessible(&self, did: DefId) -> bool {
865 def_id_visibility(self.tcx, did).0.is_accessible_from(self.current_item, self.tcx)
868 // Take node-id of an expression or pattern and check its type for privacy.
869 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
871 if self.visit(self.tables.node_id_to_type(id)) || self.visit(self.tables.node_substs(id)) {
874 if let Some(adjustments) = self.tables.adjustments().get(id) {
875 for adjustment in adjustments {
876 if self.visit(adjustment.target) {
884 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
885 let is_error = !self.item_is_accessible(def_id);
887 self.tcx.sess.span_err(self.span, &format!("{} `{}` is private", kind, descr));
893 impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
894 /// We want to visit items in the context of their containing
895 /// module and so forth, so supply a crate for doing a deep walk.
896 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
897 NestedVisitorMap::All(&self.tcx.hir())
900 fn visit_nested_body(&mut self, body: hir::BodyId) {
901 let orig_tables = mem::replace(&mut self.tables, self.tcx.body_tables(body));
902 let orig_in_body = mem::replace(&mut self.in_body, true);
903 let body = self.tcx.hir().body(body);
904 self.visit_body(body);
905 self.tables = orig_tables;
906 self.in_body = orig_in_body;
909 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty) {
910 self.span = hir_ty.span;
913 if self.visit(self.tables.node_id_to_type(hir_ty.hir_id)) {
917 // Types in signatures.
918 // FIXME: This is very ineffective. Ideally each HIR type should be converted
919 // into a semantic type only once and the result should be cached somehow.
920 if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)) {
925 intravisit::walk_ty(self, hir_ty);
928 fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef) {
929 self.span = trait_ref.path.span;
931 // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
932 // The traits' privacy in bodies is already checked as a part of trait object types.
933 let (principal, projections) =
934 rustc_typeck::hir_trait_to_predicates(self.tcx, trait_ref);
935 if self.visit_trait(*principal.skip_binder()) {
938 for (poly_predicate, _) in projections {
940 if self.visit(poly_predicate.skip_binder().ty) ||
941 self.visit_trait(poly_predicate.skip_binder().projection_ty.trait_ref(tcx)) {
947 intravisit::walk_trait_ref(self, trait_ref);
950 // Check types of expressions
951 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
952 if self.check_expr_pat_type(expr.hir_id, expr.span) {
953 // Do not check nested expressions if the error already happened.
957 hir::ExprKind::Assign(.., ref rhs) | hir::ExprKind::Match(ref rhs, ..) => {
958 // Do not report duplicate errors for `x = y` and `match x { ... }`.
959 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
963 hir::ExprKind::MethodCall(_, span, _) => {
964 // Method calls have to be checked specially.
966 if let Some(def) = self.tables.type_dependent_defs().get(expr.hir_id) {
967 if self.visit(self.tcx.type_of(def.def_id())) {
971 self.tcx.sess.delay_span_bug(expr.span,
972 "no type-dependent def for method call");
978 intravisit::walk_expr(self, expr);
981 // Prohibit access to associated items with insufficient nominal visibility.
983 // Additionally, until better reachability analysis for macros 2.0 is available,
984 // we prohibit access to private statics from other crates, this allows to give
985 // more code internal visibility at link time. (Access to private functions
986 // is already prohibited by type privacy for function types.)
987 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: hir::HirId, span: Span) {
988 let def = match *qpath {
989 hir::QPath::Resolved(_, ref path) => match path.def {
990 Def::Method(..) | Def::AssociatedConst(..) |
991 Def::AssociatedTy(..) | Def::AssociatedExistential(..) |
992 Def::Static(..) => Some(path.def),
995 hir::QPath::TypeRelative(..) => {
996 self.tables.type_dependent_defs().get(id).cloned()
999 if let Some(def) = def {
1000 let def_id = def.def_id();
1001 let is_local_static = if let Def::Static(..) = def { def_id.is_local() } else { false };
1002 if !self.item_is_accessible(def_id) && !is_local_static {
1003 let name = match *qpath {
1004 hir::QPath::Resolved(_, ref path) => path.to_string(),
1005 hir::QPath::TypeRelative(_, ref segment) => segment.ident.to_string(),
1007 let msg = format!("{} `{}` is private", def.kind_name(), name);
1008 self.tcx.sess.span_err(span, &msg);
1013 intravisit::walk_qpath(self, qpath, id, span);
1016 // Check types of patterns.
1017 fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
1018 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1019 // Do not check nested patterns if the error already happened.
1023 intravisit::walk_pat(self, pattern);
1026 fn visit_local(&mut self, local: &'tcx hir::Local) {
1027 if let Some(ref init) = local.init {
1028 if self.check_expr_pat_type(init.hir_id, init.span) {
1029 // Do not report duplicate errors for `let x = y`.
1034 intravisit::walk_local(self, local);
1037 // Check types in item interfaces.
1038 fn visit_item(&mut self, item: &'tcx hir::Item) {
1039 let orig_current_item =
1040 mem::replace(&mut self.current_item, self.tcx.hir().local_def_id(item.id));
1041 let orig_in_body = mem::replace(&mut self.in_body, false);
1043 mem::replace(&mut self.tables, item_tables(self.tcx, item.id, self.empty_tables));
1044 intravisit::walk_item(self, item);
1045 self.tables = orig_tables;
1046 self.in_body = orig_in_body;
1047 self.current_item = orig_current_item;
1050 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
1052 mem::replace(&mut self.tables, item_tables(self.tcx, ti.id, self.empty_tables));
1053 intravisit::walk_trait_item(self, ti);
1054 self.tables = orig_tables;
1057 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
1059 mem::replace(&mut self.tables, item_tables(self.tcx, ii.id, self.empty_tables));
1060 intravisit::walk_impl_item(self, ii);
1061 self.tables = orig_tables;
1065 impl<'a, 'tcx> DefIdVisitor<'a, 'tcx> for TypePrivacyVisitor<'a, 'tcx> {
1066 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
1067 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1068 self.check_def_id(def_id, kind, descr)
1072 ///////////////////////////////////////////////////////////////////////////////
1073 /// Obsolete visitors for checking for private items in public interfaces.
1074 /// These visitors are supposed to be kept in frozen state and produce an
1075 /// "old error node set". For backward compatibility the new visitor reports
1076 /// warnings instead of hard errors when the erroneous node is not in this old set.
1077 ///////////////////////////////////////////////////////////////////////////////
1079 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1080 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1081 access_levels: &'a AccessLevels,
1083 // Set of errors produced by this obsolete visitor.
1084 old_error_set: NodeSet,
1087 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1088 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1089 /// Whether the type refers to private types.
1090 contains_private: bool,
1091 /// Whether we've recurred at all (i.e., if we're pointing at the
1092 /// first type on which `visit_ty` was called).
1093 at_outer_type: bool,
1094 /// Whether that first type is a public path.
1095 outer_type_is_public_path: bool,
1098 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1099 fn path_is_private_type(&self, path: &hir::Path) -> bool {
1100 let did = match path.def {
1101 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => return false,
1102 def => def.def_id(),
1105 // A path can only be private if:
1106 // it's in this crate...
1107 if let Some(node_id) = self.tcx.hir().as_local_node_id(did) {
1108 // .. and it corresponds to a private type in the AST (this returns
1109 // `None` for type parameters).
1110 match self.tcx.hir().find(node_id) {
1111 Some(Node::Item(ref item)) => !item.vis.node.is_pub(),
1112 Some(_) | None => false,
1119 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1120 // FIXME: this would preferably be using `exported_items`, but all
1121 // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1122 self.access_levels.is_public(trait_id)
1125 fn check_generic_bound(&mut self, bound: &hir::GenericBound) {
1126 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1127 if self.path_is_private_type(&trait_ref.trait_ref.path) {
1128 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1133 fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
1134 self.access_levels.is_reachable(*id) || vis.node.is_pub()
1138 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1139 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1140 NestedVisitorMap::None
1143 fn visit_ty(&mut self, ty: &hir::Ty) {
1144 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = ty.node {
1145 if self.inner.path_is_private_type(path) {
1146 self.contains_private = true;
1147 // Found what we're looking for, so let's stop working.
1151 if let hir::TyKind::Path(_) = ty.node {
1152 if self.at_outer_type {
1153 self.outer_type_is_public_path = true;
1156 self.at_outer_type = false;
1157 intravisit::walk_ty(self, ty)
1160 // Don't want to recurse into `[, .. expr]`.
1161 fn visit_expr(&mut self, _: &hir::Expr) {}
1164 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1165 /// We want to visit items in the context of their containing
1166 /// module and so forth, so supply a crate for doing a deep walk.
1167 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1168 NestedVisitorMap::All(&self.tcx.hir())
1171 fn visit_item(&mut self, item: &'tcx hir::Item) {
1173 // Contents of a private mod can be re-exported, so we need
1174 // to check internals.
1175 hir::ItemKind::Mod(_) => {}
1177 // An `extern {}` doesn't introduce a new privacy
1178 // namespace (the contents have their own privacies).
1179 hir::ItemKind::ForeignMod(_) => {}
1181 hir::ItemKind::Trait(.., ref bounds, _) => {
1182 if !self.trait_is_public(item.id) {
1186 for bound in bounds.iter() {
1187 self.check_generic_bound(bound)
1191 // Impls need some special handling to try to offer useful
1192 // error messages without (too many) false positives
1193 // (i.e., we could just return here to not check them at
1194 // all, or some worse estimation of whether an impl is
1195 // publicly visible).
1196 hir::ItemKind::Impl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
1197 // `impl [... for] Private` is never visible.
1198 let self_contains_private;
1199 // `impl [... for] Public<...>`, but not `impl [... for]
1200 // Vec<Public>` or `(Public,)`, etc.
1201 let self_is_public_path;
1203 // Check the properties of the `Self` type:
1205 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1207 contains_private: false,
1208 at_outer_type: true,
1209 outer_type_is_public_path: false,
1211 visitor.visit_ty(&self_);
1212 self_contains_private = visitor.contains_private;
1213 self_is_public_path = visitor.outer_type_is_public_path;
1216 // Miscellaneous info about the impl:
1218 // `true` iff this is `impl Private for ...`.
1219 let not_private_trait =
1220 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1222 let did = tr.path.def.def_id();
1224 if let Some(node_id) = self.tcx.hir().as_local_node_id(did) {
1225 self.trait_is_public(node_id)
1227 true // external traits must be public
1231 // `true` iff this is a trait impl or at least one method is public.
1233 // `impl Public { $( fn ...() {} )* }` is not visible.
1235 // This is required over just using the methods' privacy
1236 // directly because we might have `impl<T: Foo<Private>> ...`,
1237 // and we shouldn't warn about the generics if all the methods
1238 // are private (because `T` won't be visible externally).
1239 let trait_or_some_public_method =
1240 trait_ref.is_some() ||
1241 impl_item_refs.iter()
1242 .any(|impl_item_ref| {
1243 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1244 match impl_item.node {
1245 hir::ImplItemKind::Const(..) |
1246 hir::ImplItemKind::Method(..) => {
1247 self.access_levels.is_reachable(impl_item.id)
1249 hir::ImplItemKind::Existential(..) |
1250 hir::ImplItemKind::Type(_) => false,
1254 if !self_contains_private &&
1255 not_private_trait &&
1256 trait_or_some_public_method {
1258 intravisit::walk_generics(self, g);
1262 for impl_item_ref in impl_item_refs {
1263 // This is where we choose whether to walk down
1264 // further into the impl to check its items. We
1265 // should only walk into public items so that we
1266 // don't erroneously report errors for private
1267 // types in private items.
1268 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1269 match impl_item.node {
1270 hir::ImplItemKind::Const(..) |
1271 hir::ImplItemKind::Method(..)
1272 if self.item_is_public(&impl_item.id, &impl_item.vis) =>
1274 intravisit::walk_impl_item(self, impl_item)
1276 hir::ImplItemKind::Type(..) => {
1277 intravisit::walk_impl_item(self, impl_item)
1284 // Any private types in a trait impl fall into three
1286 // 1. mentioned in the trait definition
1287 // 2. mentioned in the type params/generics
1288 // 3. mentioned in the associated types of the impl
1290 // Those in 1. can only occur if the trait is in
1291 // this crate and will've been warned about on the
1292 // trait definition (there's no need to warn twice
1293 // so we don't check the methods).
1295 // Those in 2. are warned via walk_generics and this
1297 intravisit::walk_path(self, &tr.path);
1299 // Those in 3. are warned with this call.
1300 for impl_item_ref in impl_item_refs {
1301 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1302 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1308 } else if trait_ref.is_none() && self_is_public_path {
1309 // `impl Public<Private> { ... }`. Any public static
1310 // methods will be visible as `Public::foo`.
1311 let mut found_pub_static = false;
1312 for impl_item_ref in impl_item_refs {
1313 if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
1314 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1315 match impl_item_ref.kind {
1316 hir::AssociatedItemKind::Const => {
1317 found_pub_static = true;
1318 intravisit::walk_impl_item(self, impl_item);
1320 hir::AssociatedItemKind::Method { has_self: false } => {
1321 found_pub_static = true;
1322 intravisit::walk_impl_item(self, impl_item);
1328 if found_pub_static {
1329 intravisit::walk_generics(self, g)
1335 // `type ... = ...;` can contain private types, because
1336 // we're introducing a new name.
1337 hir::ItemKind::Ty(..) => return,
1339 // Not at all public, so we don't care.
1340 _ if !self.item_is_public(&item.id, &item.vis) => {
1347 // We've carefully constructed it so that if we're here, then
1348 // any `visit_ty`'s will be called on things that are in
1349 // public signatures, i.e., things that we're interested in for
1351 intravisit::walk_item(self, item);
1354 fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1355 for param in &generics.params {
1356 for bound in ¶m.bounds {
1357 self.check_generic_bound(bound);
1360 for predicate in &generics.where_clause.predicates {
1362 hir::WherePredicate::BoundPredicate(bound_pred) => {
1363 for bound in bound_pred.bounds.iter() {
1364 self.check_generic_bound(bound)
1367 hir::WherePredicate::RegionPredicate(_) => {}
1368 hir::WherePredicate::EqPredicate(eq_pred) => {
1369 self.visit_ty(&eq_pred.rhs_ty);
1375 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
1376 if self.access_levels.is_reachable(item.id) {
1377 intravisit::walk_foreign_item(self, item)
1381 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1382 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = t.node {
1383 if self.path_is_private_type(path) {
1384 self.old_error_set.insert(t.id);
1387 intravisit::walk_ty(self, t)
1390 fn visit_variant(&mut self,
1391 v: &'tcx hir::Variant,
1392 g: &'tcx hir::Generics,
1393 item_id: ast::NodeId) {
1394 if self.access_levels.is_reachable(v.node.data.id()) {
1395 self.in_variant = true;
1396 intravisit::walk_variant(self, v, g, item_id);
1397 self.in_variant = false;
1401 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
1402 if s.vis.node.is_pub() || self.in_variant {
1403 intravisit::walk_struct_field(self, s);
1407 // We don't need to introspect into these at all: an
1408 // expression/block context can't possibly contain exported things.
1409 // (Making them no-ops stops us from traversing the whole AST without
1410 // having to be super careful about our `walk_...` calls above.)
1411 fn visit_block(&mut self, _: &'tcx hir::Block) {}
1412 fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1415 ///////////////////////////////////////////////////////////////////////////////
1416 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1417 /// finds any private components in it.
1418 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1419 /// and traits in public interfaces.
1420 ///////////////////////////////////////////////////////////////////////////////
1422 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1423 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1426 /// The visitor checks that each component type is at least this visible.
1427 required_visibility: ty::Visibility,
1428 has_pub_restricted: bool,
1429 has_old_errors: bool,
1433 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1434 fn generics(&mut self) -> &mut Self {
1435 for param in &self.tcx.generics_of(self.item_def_id).params {
1437 GenericParamDefKind::Type { has_default, .. } => {
1439 self.visit(self.tcx.type_of(param.def_id));
1442 GenericParamDefKind::Lifetime => {}
1448 fn predicates(&mut self) -> &mut Self {
1449 // N.B., we use `explicit_predicates_of` and not `predicates_of`
1450 // because we don't want to report privacy errors due to where
1451 // clauses that the compiler inferred. We only want to
1452 // consider the ones that the user wrote. This is important
1453 // for the inferred outlives rules; see
1454 // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1455 self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1459 fn ty(&mut self) -> &mut Self {
1460 self.visit(self.tcx.type_of(self.item_def_id));
1464 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1465 let node_id = match self.tcx.hir().as_local_node_id(def_id) {
1466 Some(node_id) => node_id,
1467 None => return false,
1470 let (vis, vis_span, vis_descr) = def_id_visibility(self.tcx, def_id);
1471 if !vis.is_at_least(self.required_visibility, self.tcx) {
1472 let msg = format!("{} {} `{}` in public interface", vis_descr, kind, descr);
1473 if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1474 let mut err = if kind == "trait" {
1475 struct_span_err!(self.tcx.sess, self.span, E0445, "{}", msg)
1477 struct_span_err!(self.tcx.sess, self.span, E0446, "{}", msg)
1479 err.span_label(self.span, format!("can't leak {} {}", vis_descr, kind));
1480 err.span_label(vis_span, format!("`{}` declared as {}", descr, vis_descr));
1483 let err_code = if kind == "trait" { "E0445" } else { "E0446" };
1484 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC, node_id, self.span,
1485 &format!("{} (error {})", msg, err_code));
1492 impl<'a, 'tcx> DefIdVisitor<'a, 'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1493 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
1494 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1495 self.check_def_id(def_id, kind, descr)
1499 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1500 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1501 has_pub_restricted: bool,
1502 old_error_set: &'a NodeSet,
1505 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1506 fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1507 -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1508 let mut has_old_errors = false;
1510 // Slow path taken only if there any errors in the crate.
1511 for &id in self.old_error_set {
1512 // Walk up the nodes until we find `item_id` (or we hit a root).
1516 has_old_errors = true;
1519 let parent = self.tcx.hir().get_parent_node(id);
1531 SearchInterfaceForPrivateItemsVisitor {
1533 item_def_id: self.tcx.hir().local_def_id(item_id),
1534 span: self.tcx.hir().span(item_id),
1535 required_visibility,
1536 has_pub_restricted: self.has_pub_restricted,
1543 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1544 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1545 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1548 fn visit_item(&mut self, item: &'tcx hir::Item) {
1550 let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1553 // Crates are always public.
1554 hir::ItemKind::ExternCrate(..) => {}
1555 // All nested items are checked by `visit_item`.
1556 hir::ItemKind::Mod(..) => {}
1557 // Checked in resolve.
1558 hir::ItemKind::Use(..) => {}
1560 hir::ItemKind::GlobalAsm(..) => {}
1561 // Subitems of these items have inherited publicity.
1562 hir::ItemKind::Const(..) | hir::ItemKind::Static(..) | hir::ItemKind::Fn(..) |
1563 hir::ItemKind::Existential(..) | hir::ItemKind::Ty(..) => {
1564 self.check(item.id, item_visibility).generics().predicates().ty();
1566 hir::ItemKind::Trait(.., ref trait_item_refs) => {
1567 self.check(item.id, item_visibility).generics().predicates();
1569 for trait_item_ref in trait_item_refs {
1570 let mut check = self.check(trait_item_ref.id.node_id, item_visibility);
1571 check.in_assoc_ty = trait_item_ref.kind == hir::AssociatedItemKind::Type;
1572 check.generics().predicates();
1574 if trait_item_ref.kind == hir::AssociatedItemKind::Type &&
1575 !trait_item_ref.defaultness.has_value() {
1576 // No type to visit.
1582 hir::ItemKind::TraitAlias(..) => {
1583 self.check(item.id, item_visibility).generics().predicates();
1585 hir::ItemKind::Enum(ref def, _) => {
1586 self.check(item.id, item_visibility).generics().predicates();
1588 for variant in &def.variants {
1589 for field in variant.node.data.fields() {
1590 self.check(field.id, item_visibility).ty();
1594 // Subitems of foreign modules have their own publicity.
1595 hir::ItemKind::ForeignMod(ref foreign_mod) => {
1596 for foreign_item in &foreign_mod.items {
1597 let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1598 self.check(foreign_item.id, vis).generics().predicates().ty();
1601 // Subitems of structs and unions have their own publicity.
1602 hir::ItemKind::Struct(ref struct_def, _) |
1603 hir::ItemKind::Union(ref struct_def, _) => {
1604 self.check(item.id, item_visibility).generics().predicates();
1606 for field in struct_def.fields() {
1607 let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1608 self.check(field.id, min(item_visibility, field_visibility, tcx)).ty();
1611 // An inherent impl is public when its type is public
1612 // Subitems of inherent impls have their own publicity.
1613 // A trait impl is public when both its type and its trait are public
1614 // Subitems of trait impls have inherited publicity.
1615 hir::ItemKind::Impl(.., ref trait_ref, _, ref impl_item_refs) => {
1616 let impl_vis = ty::Visibility::of_impl(item.id, tcx, &Default::default());
1617 self.check(item.id, impl_vis).generics().predicates();
1618 for impl_item_ref in impl_item_refs {
1619 let impl_item = tcx.hir().impl_item(impl_item_ref.id);
1620 let impl_item_vis = if trait_ref.is_none() {
1621 min(ty::Visibility::from_hir(&impl_item.vis, item.id, tcx), impl_vis, tcx)
1625 let mut check = self.check(impl_item.id, impl_item_vis);
1626 check.in_assoc_ty = impl_item_ref.kind == hir::AssociatedItemKind::Type;
1627 check.generics().predicates().ty();
1634 pub fn provide(providers: &mut Providers) {
1635 *providers = Providers {
1636 privacy_access_levels,
1641 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Lrc<AccessLevels> {
1642 tcx.privacy_access_levels(LOCAL_CRATE)
1645 fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1647 -> Lrc<AccessLevels> {
1648 assert_eq!(krate, LOCAL_CRATE);
1650 let krate = tcx.hir().krate();
1651 let empty_tables = ty::TypeckTables::empty(None);
1653 // Check privacy of names not checked in previous compilation stages.
1654 let mut visitor = NamePrivacyVisitor {
1656 tables: &empty_tables,
1657 current_item: CRATE_NODE_ID,
1658 empty_tables: &empty_tables,
1660 intravisit::walk_crate(&mut visitor, krate);
1662 // Check privacy of explicitly written types and traits as well as
1663 // inferred types of expressions and patterns.
1664 let mut visitor = TypePrivacyVisitor {
1666 tables: &empty_tables,
1667 current_item: DefId::local(CRATE_DEF_INDEX),
1670 empty_tables: &empty_tables,
1672 intravisit::walk_crate(&mut visitor, krate);
1674 // Build up a set of all exported items in the AST. This is a set of all
1675 // items which are reachable from external crates based on visibility.
1676 let mut visitor = EmbargoVisitor {
1678 access_levels: Default::default(),
1679 prev_level: Some(AccessLevel::Public),
1683 intravisit::walk_crate(&mut visitor, krate);
1684 if visitor.changed {
1685 visitor.changed = false;
1690 visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1693 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1695 access_levels: &visitor.access_levels,
1697 old_error_set: Default::default(),
1699 intravisit::walk_crate(&mut visitor, krate);
1702 let has_pub_restricted = {
1703 let mut pub_restricted_visitor = PubRestrictedVisitor {
1705 has_pub_restricted: false
1707 intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1708 pub_restricted_visitor.has_pub_restricted
1711 // Check for private types and traits in public interfaces.
1712 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1715 old_error_set: &visitor.old_error_set,
1717 krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1720 Lrc::new(visitor.access_levels)
1723 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }