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