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