]> git.proxmox.com Git - rustc.git/blob - src/librustc_privacy/lib.rs
Imported Upstream version 1.1.0+dfsg1
[rustc.git] / src / librustc_privacy / lib.rs
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
11 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustc_privacy"]
14 #![unstable(feature = "rustc_private")]
15 #![staged_api]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
20 html_root_url = "http://doc.rust-lang.org/nightly/")]
21
22 #![feature(rustc_diagnostic_macros)]
23 #![feature(rustc_private)]
24 #![feature(staged_api)]
25
26 #[macro_use] extern crate log;
27 #[macro_use] extern crate syntax;
28
29 extern crate rustc;
30
31 use self::PrivacyResult::*;
32 use self::FieldName::*;
33
34 use std::mem::replace;
35
36 use rustc::metadata::csearch;
37 use rustc::middle::def;
38 use rustc::middle::privacy::ImportUse::*;
39 use rustc::middle::privacy::LastPrivate::*;
40 use rustc::middle::privacy::PrivateDep::*;
41 use rustc::middle::privacy::{ExternalExports, ExportedItems, PublicItems};
42 use rustc::middle::ty::{MethodTypeParam, MethodStatic};
43 use rustc::middle::ty::{MethodCall, MethodMap, MethodOrigin, MethodParam};
44 use rustc::middle::ty::{MethodStaticClosure, MethodObject};
45 use rustc::middle::ty::MethodTraitObject;
46 use rustc::middle::ty::{self, Ty};
47 use rustc::util::nodemap::{NodeMap, NodeSet};
48
49 use syntax::{ast, ast_map};
50 use syntax::ast_util::{is_local, local_def};
51 use syntax::codemap::Span;
52 use syntax::parse::token;
53 use syntax::visit::{self, Visitor};
54
55 type Context<'a, 'tcx> = (&'a MethodMap<'tcx>, &'a def::ExportMap);
56
57 /// Result of a checking operation - None => no errors were found. Some => an
58 /// error and contains the span and message for reporting that error and
59 /// optionally the same for a note about the error.
60 type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
61
62 ////////////////////////////////////////////////////////////////////////////////
63 /// The parent visitor, used to determine what's the parent of what (node-wise)
64 ////////////////////////////////////////////////////////////////////////////////
65
66 struct ParentVisitor {
67 parents: NodeMap<ast::NodeId>,
68 curparent: ast::NodeId,
69 }
70
71 impl<'v> Visitor<'v> for ParentVisitor {
72 fn visit_item(&mut self, item: &ast::Item) {
73 self.parents.insert(item.id, self.curparent);
74
75 let prev = self.curparent;
76 match item.node {
77 ast::ItemMod(..) => { self.curparent = item.id; }
78 // Enum variants are parented to the enum definition itself because
79 // they inherit privacy
80 ast::ItemEnum(ref def, _) => {
81 for variant in &def.variants {
82 // The parent is considered the enclosing enum because the
83 // enum will dictate the privacy visibility of this variant
84 // instead.
85 self.parents.insert(variant.node.id, item.id);
86 }
87 }
88
89 // Trait methods are always considered "public", but if the trait is
90 // private then we need some private item in the chain from the
91 // method to the root. In this case, if the trait is private, then
92 // parent all the methods to the trait to indicate that they're
93 // private.
94 ast::ItemTrait(_, _, _, ref trait_items) if item.vis != ast::Public => {
95 for trait_item in trait_items {
96 self.parents.insert(trait_item.id, item.id);
97 }
98 }
99
100 _ => {}
101 }
102 visit::walk_item(self, item);
103 self.curparent = prev;
104 }
105
106 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
107 self.parents.insert(a.id, self.curparent);
108 visit::walk_foreign_item(self, a);
109 }
110
111 fn visit_fn(&mut self, a: visit::FnKind<'v>, b: &'v ast::FnDecl,
112 c: &'v ast::Block, d: Span, id: ast::NodeId) {
113 // We already took care of some trait methods above, otherwise things
114 // like impl methods and pub trait methods are parented to the
115 // containing module, not the containing trait.
116 if !self.parents.contains_key(&id) {
117 self.parents.insert(id, self.curparent);
118 }
119 visit::walk_fn(self, a, b, c, d);
120 }
121
122 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
123 // visit_fn handles methods, but associated consts have to be handled
124 // here.
125 if !self.parents.contains_key(&ii.id) {
126 self.parents.insert(ii.id, self.curparent);
127 }
128 visit::walk_impl_item(self, ii);
129 }
130
131 fn visit_struct_def(&mut self, s: &ast::StructDef, _: ast::Ident,
132 _: &'v ast::Generics, n: ast::NodeId) {
133 // Struct constructors are parented to their struct definitions because
134 // they essentially are the struct definitions.
135 match s.ctor_id {
136 Some(id) => { self.parents.insert(id, n); }
137 None => {}
138 }
139
140 // While we have the id of the struct definition, go ahead and parent
141 // all the fields.
142 for field in &s.fields {
143 self.parents.insert(field.node.id, self.curparent);
144 }
145 visit::walk_struct_def(self, s)
146 }
147 }
148
149 ////////////////////////////////////////////////////////////////////////////////
150 /// The embargo visitor, used to determine the exports of the ast
151 ////////////////////////////////////////////////////////////////////////////////
152
153 struct EmbargoVisitor<'a, 'tcx: 'a> {
154 tcx: &'a ty::ctxt<'tcx>,
155 export_map: &'a def::ExportMap,
156
157 // This flag is an indicator of whether the previous item in the
158 // hierarchical chain was exported or not. This is the indicator of whether
159 // children should be exported as well. Note that this can flip from false
160 // to true if a reexported module is entered (or an action similar).
161 prev_exported: bool,
162
163 // This is a list of all exported items in the AST. An exported item is any
164 // function/method/item which is usable by external crates. This essentially
165 // means that the result is "public all the way down", but the "path down"
166 // may jump across private boundaries through reexport statements.
167 exported_items: ExportedItems,
168
169 // This sets contains all the destination nodes which are publicly
170 // re-exported. This is *not* a set of all reexported nodes, only a set of
171 // all nodes which are reexported *and* reachable from external crates. This
172 // means that the destination of the reexport is exported, and hence the
173 // destination must also be exported.
174 reexports: NodeSet,
175
176 // These two fields are closely related to one another in that they are only
177 // used for generation of the 'PublicItems' set, not for privacy checking at
178 // all
179 public_items: PublicItems,
180 prev_public: bool,
181 }
182
183 impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> {
184 // There are checks inside of privacy which depend on knowing whether a
185 // trait should be exported or not. The two current consumers of this are:
186 //
187 // 1. Should default methods of a trait be exported?
188 // 2. Should the methods of an implementation of a trait be exported?
189 //
190 // The answer to both of these questions partly rely on whether the trait
191 // itself is exported or not. If the trait is somehow exported, then the
192 // answers to both questions must be yes. Right now this question involves
193 // more analysis than is currently done in rustc, so we conservatively
194 // answer "yes" so that all traits need to be exported.
195 fn exported_trait(&self, _id: ast::NodeId) -> bool {
196 true
197 }
198 }
199
200 impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
201 fn visit_item(&mut self, item: &ast::Item) {
202 let orig_all_pub = self.prev_public;
203 self.prev_public = orig_all_pub && item.vis == ast::Public;
204 if self.prev_public {
205 self.public_items.insert(item.id);
206 }
207
208 let orig_all_exported = self.prev_exported;
209 match item.node {
210 // impls/extern blocks do not break the "public chain" because they
211 // cannot have visibility qualifiers on them anyway
212 ast::ItemImpl(..) | ast::ItemDefaultImpl(..) | ast::ItemForeignMod(..) => {}
213
214 // Traits are a little special in that even if they themselves are
215 // not public they may still be exported.
216 ast::ItemTrait(..) => {
217 self.prev_exported = self.exported_trait(item.id);
218 }
219
220 // Private by default, hence we only retain the "public chain" if
221 // `pub` is explicitly listed.
222 _ => {
223 self.prev_exported =
224 (orig_all_exported && item.vis == ast::Public) ||
225 self.reexports.contains(&item.id);
226 }
227 }
228
229 let public_first = self.prev_exported &&
230 self.exported_items.insert(item.id);
231
232 match item.node {
233 // Enum variants inherit from their parent, so if the enum is
234 // public all variants are public unless they're explicitly priv
235 ast::ItemEnum(ref def, _) if public_first => {
236 for variant in &def.variants {
237 self.exported_items.insert(variant.node.id);
238 self.public_items.insert(variant.node.id);
239 }
240 }
241
242 // Implementations are a little tricky to determine what's exported
243 // out of them. Here's a few cases which are currently defined:
244 //
245 // * Impls for private types do not need to export their methods
246 // (either public or private methods)
247 //
248 // * Impls for public types only have public methods exported
249 //
250 // * Public trait impls for public types must have all methods
251 // exported.
252 //
253 // * Private trait impls for public types can be ignored
254 //
255 // * Public trait impls for private types have their methods
256 // exported. I'm not entirely certain that this is the correct
257 // thing to do, but I have seen use cases of where this will cause
258 // undefined symbols at linkage time if this case is not handled.
259 //
260 // * Private trait impls for private types can be completely ignored
261 ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
262 let public_ty = match ty.node {
263 ast::TyPath(..) => {
264 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
265 def::DefPrimTy(..) => true,
266 def => {
267 let did = def.def_id();
268 !is_local(did) ||
269 self.exported_items.contains(&did.node)
270 }
271 }
272 }
273 _ => true,
274 };
275 let tr = ty::impl_trait_ref(self.tcx, local_def(item.id));
276 let public_trait = tr.clone().map_or(false, |tr| {
277 !is_local(tr.def_id) ||
278 self.exported_items.contains(&tr.def_id.node)
279 });
280
281 if public_ty || public_trait {
282 for impl_item in impl_items {
283 match impl_item.node {
284 ast::ConstImplItem(..) => {
285 if (public_ty && impl_item.vis == ast::Public)
286 || tr.is_some() {
287 self.exported_items.insert(impl_item.id);
288 }
289 }
290 ast::MethodImplItem(ref sig, _) => {
291 let meth_public = match sig.explicit_self.node {
292 ast::SelfStatic => public_ty,
293 _ => true,
294 } && impl_item.vis == ast::Public;
295 if meth_public || tr.is_some() {
296 self.exported_items.insert(impl_item.id);
297 }
298 }
299 ast::TypeImplItem(_) |
300 ast::MacImplItem(_) => {}
301 }
302 }
303 }
304 }
305
306 // Default methods on traits are all public so long as the trait
307 // is public
308 ast::ItemTrait(_, _, _, ref trait_items) if public_first => {
309 for trait_item in trait_items {
310 debug!("trait item {}", trait_item.id);
311 self.exported_items.insert(trait_item.id);
312 }
313 }
314
315 // Struct constructors are public if the struct is all public.
316 ast::ItemStruct(ref def, _) if public_first => {
317 match def.ctor_id {
318 Some(id) => { self.exported_items.insert(id); }
319 None => {}
320 }
321 // fields can be public or private, so lets check
322 for field in &def.fields {
323 let vis = match field.node.kind {
324 ast::NamedField(_, vis) | ast::UnnamedField(vis) => vis
325 };
326 if vis == ast::Public {
327 self.public_items.insert(field.node.id);
328 }
329 }
330 }
331
332 ast::ItemTy(ref ty, _) if public_first => {
333 if let ast::TyPath(..) = ty.node {
334 match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
335 def::DefPrimTy(..) | def::DefTyParam(..) => {},
336 def => {
337 let did = def.def_id();
338 if is_local(did) {
339 self.exported_items.insert(did.node);
340 }
341 }
342 }
343 }
344 }
345
346 _ => {}
347 }
348
349 visit::walk_item(self, item);
350
351 self.prev_exported = orig_all_exported;
352 self.prev_public = orig_all_pub;
353 }
354
355 fn visit_foreign_item(&mut self, a: &ast::ForeignItem) {
356 if (self.prev_exported && a.vis == ast::Public) || self.reexports.contains(&a.id) {
357 self.exported_items.insert(a.id);
358 }
359 }
360
361 fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId) {
362 // This code is here instead of in visit_item so that the
363 // crate module gets processed as well.
364 if self.prev_exported {
365 assert!(self.export_map.contains_key(&id), "wut {}", id);
366 for export in self.export_map.get(&id).unwrap() {
367 if is_local(export.def_id) {
368 self.reexports.insert(export.def_id.node);
369 }
370 }
371 }
372 visit::walk_mod(self, m)
373 }
374 }
375
376 ////////////////////////////////////////////////////////////////////////////////
377 /// The privacy visitor, where privacy checks take place (violations reported)
378 ////////////////////////////////////////////////////////////////////////////////
379
380 struct PrivacyVisitor<'a, 'tcx: 'a> {
381 tcx: &'a ty::ctxt<'tcx>,
382 curitem: ast::NodeId,
383 in_foreign: bool,
384 parents: NodeMap<ast::NodeId>,
385 external_exports: ExternalExports,
386 }
387
388 enum PrivacyResult {
389 Allowable,
390 ExternallyDenied,
391 DisallowedBy(ast::NodeId),
392 }
393
394 enum FieldName {
395 UnnamedField(usize), // index
396 // (Name, not Ident, because struct fields are not macro-hygienic)
397 NamedField(ast::Name),
398 }
399
400 impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
401 // used when debugging
402 fn nodestr(&self, id: ast::NodeId) -> String {
403 self.tcx.map.node_to_string(id).to_string()
404 }
405
406 // Determines whether the given definition is public from the point of view
407 // of the current item.
408 fn def_privacy(&self, did: ast::DefId) -> PrivacyResult {
409 if !is_local(did) {
410 if self.external_exports.contains(&did) {
411 debug!("privacy - {:?} was externally exported", did);
412 return Allowable;
413 }
414 debug!("privacy - is {:?} a public method", did);
415
416 return match self.tcx.impl_or_trait_items.borrow().get(&did) {
417 Some(&ty::ConstTraitItem(ref ac)) => {
418 debug!("privacy - it's a const: {:?}", *ac);
419 match ac.container {
420 ty::TraitContainer(id) => {
421 debug!("privacy - recursing on trait {:?}", id);
422 self.def_privacy(id)
423 }
424 ty::ImplContainer(id) => {
425 match ty::impl_trait_ref(self.tcx, id) {
426 Some(t) => {
427 debug!("privacy - impl of trait {:?}", id);
428 self.def_privacy(t.def_id)
429 }
430 None => {
431 debug!("privacy - found inherent \
432 associated constant {:?}",
433 ac.vis);
434 if ac.vis == ast::Public {
435 Allowable
436 } else {
437 ExternallyDenied
438 }
439 }
440 }
441 }
442 }
443 }
444 Some(&ty::MethodTraitItem(ref meth)) => {
445 debug!("privacy - well at least it's a method: {:?}",
446 *meth);
447 match meth.container {
448 ty::TraitContainer(id) => {
449 debug!("privacy - recursing on trait {:?}", id);
450 self.def_privacy(id)
451 }
452 ty::ImplContainer(id) => {
453 match ty::impl_trait_ref(self.tcx, id) {
454 Some(t) => {
455 debug!("privacy - impl of trait {:?}", id);
456 self.def_privacy(t.def_id)
457 }
458 None => {
459 debug!("privacy - found a method {:?}",
460 meth.vis);
461 if meth.vis == ast::Public {
462 Allowable
463 } else {
464 ExternallyDenied
465 }
466 }
467 }
468 }
469 }
470 }
471 Some(&ty::TypeTraitItem(ref typedef)) => {
472 match typedef.container {
473 ty::TraitContainer(id) => {
474 debug!("privacy - recursing on trait {:?}", id);
475 self.def_privacy(id)
476 }
477 ty::ImplContainer(id) => {
478 match ty::impl_trait_ref(self.tcx, id) {
479 Some(t) => {
480 debug!("privacy - impl of trait {:?}", id);
481 self.def_privacy(t.def_id)
482 }
483 None => {
484 debug!("privacy - found a typedef {:?}",
485 typedef.vis);
486 if typedef.vis == ast::Public {
487 Allowable
488 } else {
489 ExternallyDenied
490 }
491 }
492 }
493 }
494 }
495 }
496 None => {
497 debug!("privacy - nope, not even a method");
498 ExternallyDenied
499 }
500 };
501 }
502
503 debug!("privacy - local {} not public all the way down",
504 self.tcx.map.node_to_string(did.node));
505 // return quickly for things in the same module
506 if self.parents.get(&did.node) == self.parents.get(&self.curitem) {
507 debug!("privacy - same parent, we're done here");
508 return Allowable;
509 }
510
511 // We now know that there is at least one private member between the
512 // destination and the root.
513 let mut closest_private_id = did.node;
514 loop {
515 debug!("privacy - examining {}", self.nodestr(closest_private_id));
516 let vis = match self.tcx.map.find(closest_private_id) {
517 // If this item is a method, then we know for sure that it's an
518 // actual method and not a static method. The reason for this is
519 // that these cases are only hit in the ExprMethodCall
520 // expression, and ExprCall will have its path checked later
521 // (the path of the trait/impl) if it's a static method.
522 //
523 // With this information, then we can completely ignore all
524 // trait methods. The privacy violation would be if the trait
525 // couldn't get imported, not if the method couldn't be used
526 // (all trait methods are public).
527 //
528 // However, if this is an impl method, then we dictate this
529 // decision solely based on the privacy of the method
530 // invocation.
531 // FIXME(#10573) is this the right behavior? Why not consider
532 // where the method was defined?
533 Some(ast_map::NodeImplItem(ii)) => {
534 match ii.node {
535 ast::ConstImplItem(..) |
536 ast::MethodImplItem(..) => {
537 let imp = self.tcx.map
538 .get_parent_did(closest_private_id);
539 match ty::impl_trait_ref(self.tcx, imp) {
540 Some(..) => return Allowable,
541 _ if ii.vis == ast::Public => {
542 return Allowable
543 }
544 _ => ii.vis
545 }
546 }
547 ast::TypeImplItem(_) |
548 ast::MacImplItem(_) => return Allowable,
549 }
550 }
551 Some(ast_map::NodeTraitItem(_)) => {
552 return Allowable;
553 }
554
555 // This is not a method call, extract the visibility as one
556 // would normally look at it
557 Some(ast_map::NodeItem(it)) => it.vis,
558 Some(ast_map::NodeForeignItem(_)) => {
559 self.tcx.map.get_foreign_vis(closest_private_id)
560 }
561 Some(ast_map::NodeVariant(..)) => {
562 ast::Public // need to move up a level (to the enum)
563 }
564 _ => ast::Public,
565 };
566 if vis != ast::Public { break }
567 // if we've reached the root, then everything was allowable and this
568 // access is public.
569 if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
570 closest_private_id = *self.parents.get(&closest_private_id).unwrap();
571
572 // If we reached the top, then we were public all the way down and
573 // we can allow this access.
574 if closest_private_id == ast::DUMMY_NODE_ID { return Allowable }
575 }
576 debug!("privacy - closest priv {}", self.nodestr(closest_private_id));
577 if self.private_accessible(closest_private_id) {
578 Allowable
579 } else {
580 DisallowedBy(closest_private_id)
581 }
582 }
583
584 /// For a local private node in the AST, this function will determine
585 /// whether the node is accessible by the current module that iteration is
586 /// inside.
587 fn private_accessible(&self, id: ast::NodeId) -> bool {
588 let parent = *self.parents.get(&id).unwrap();
589 debug!("privacy - accessible parent {}", self.nodestr(parent));
590
591 // After finding `did`'s closest private member, we roll ourselves back
592 // to see if this private member's parent is anywhere in our ancestry.
593 // By the privacy rules, we can access all of our ancestor's private
594 // members, so that's why we test the parent, and not the did itself.
595 let mut cur = self.curitem;
596 loop {
597 debug!("privacy - questioning {}, {}", self.nodestr(cur), cur);
598 match cur {
599 // If the relevant parent is in our history, then we're allowed
600 // to look inside any of our ancestor's immediate private items,
601 // so this access is valid.
602 x if x == parent => return true,
603
604 // If we've reached the root, then we couldn't access this item
605 // in the first place
606 ast::DUMMY_NODE_ID => return false,
607
608 // Keep going up
609 _ => {}
610 }
611
612 cur = *self.parents.get(&cur).unwrap();
613 }
614 }
615
616 fn report_error(&self, result: CheckResult) -> bool {
617 match result {
618 None => true,
619 Some((span, msg, note)) => {
620 self.tcx.sess.span_err(span, &msg[..]);
621 match note {
622 Some((span, msg)) => {
623 self.tcx.sess.span_note(span, &msg[..])
624 }
625 None => {},
626 }
627 false
628 },
629 }
630 }
631
632 /// Guarantee that a particular definition is public. Returns a CheckResult
633 /// which contains any errors found. These can be reported using `report_error`.
634 /// If the result is `None`, no errors were found.
635 fn ensure_public(&self, span: Span, to_check: ast::DefId,
636 source_did: Option<ast::DefId>, msg: &str) -> CheckResult {
637 let id = match self.def_privacy(to_check) {
638 ExternallyDenied => {
639 return Some((span, format!("{} is private", msg), None))
640 }
641 Allowable => return None,
642 DisallowedBy(id) => id,
643 };
644
645 // If we're disallowed by a particular id, then we attempt to give a
646 // nice error message to say why it was disallowed. It was either
647 // because the item itself is private or because its parent is private
648 // and its parent isn't in our ancestry.
649 let (err_span, err_msg) = if id == source_did.unwrap_or(to_check).node {
650 return Some((span, format!("{} is private", msg), None));
651 } else {
652 (span, format!("{} is inaccessible", msg))
653 };
654 let item = match self.tcx.map.find(id) {
655 Some(ast_map::NodeItem(item)) => {
656 match item.node {
657 // If an impl disallowed this item, then this is resolve's
658 // way of saying that a struct/enum's static method was
659 // invoked, and the struct/enum itself is private. Crawl
660 // back up the chains to find the relevant struct/enum that
661 // was private.
662 ast::ItemImpl(_, _, _, _, ref ty, _) => {
663 match ty.node {
664 ast::TyPath(..) => {}
665 _ => return Some((err_span, err_msg, None)),
666 };
667 let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
668 let did = def.def_id();
669 assert!(is_local(did));
670 match self.tcx.map.get(did.node) {
671 ast_map::NodeItem(item) => item,
672 _ => self.tcx.sess.span_bug(item.span,
673 "path is not an item")
674 }
675 }
676 _ => item
677 }
678 }
679 Some(..) | None => return Some((err_span, err_msg, None)),
680 };
681 let desc = match item.node {
682 ast::ItemMod(..) => "module",
683 ast::ItemTrait(..) => "trait",
684 ast::ItemStruct(..) => "struct",
685 ast::ItemEnum(..) => "enum",
686 _ => return Some((err_span, err_msg, None))
687 };
688 let msg = format!("{} `{}` is private", desc,
689 token::get_ident(item.ident));
690 Some((err_span, err_msg, Some((span, msg))))
691 }
692
693 // Checks that a field is in scope.
694 fn check_field(&mut self,
695 span: Span,
696 id: ast::DefId,
697 name: FieldName) {
698 let fields = ty::lookup_struct_fields(self.tcx, id);
699 let field = match name {
700 NamedField(f_name) => {
701 debug!("privacy - check named field {} in struct {:?}", f_name, id);
702 fields.iter().find(|f| f.name == f_name).unwrap()
703 }
704 UnnamedField(idx) => &fields[idx]
705 };
706 if field.vis == ast::Public ||
707 (is_local(field.id) && self.private_accessible(field.id.node)) {
708 return
709 }
710
711 let struct_type = ty::lookup_item_type(self.tcx, id).ty;
712 let struct_desc = match struct_type.sty {
713 ty::ty_struct(_, _) =>
714 format!("struct `{}`", ty::item_path_str(self.tcx, id)),
715 // struct variant fields have inherited visibility
716 ty::ty_enum(..) => return,
717 _ => self.tcx.sess.span_bug(span, "can't find struct for field")
718 };
719 let msg = match name {
720 NamedField(name) => format!("field `{}` of {} is private",
721 token::get_name(name), struct_desc),
722 UnnamedField(idx) => format!("field #{} of {} is private",
723 idx + 1, struct_desc),
724 };
725 self.tcx.sess.span_err(span, &msg[..]);
726 }
727
728 // Given the ID of a method, checks to ensure it's in scope.
729 fn check_static_method(&mut self,
730 span: Span,
731 method_id: ast::DefId,
732 name: ast::Name) {
733 // If the method is a default method, we need to use the def_id of
734 // the default implementation.
735 let method_id = match ty::impl_or_trait_item(self.tcx, method_id) {
736 ty::MethodTraitItem(method_type) => {
737 method_type.provided_source.unwrap_or(method_id)
738 }
739 _ => {
740 self.tcx.sess
741 .span_bug(span,
742 "got non-method item in check_static_method")
743 }
744 };
745
746 let string = token::get_name(name);
747 self.report_error(self.ensure_public(span,
748 method_id,
749 None,
750 &format!("method `{}`",
751 string)));
752 }
753
754 // Checks that a path is in scope.
755 fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Name) {
756 debug!("privacy - path {}", self.nodestr(path_id));
757 let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap();
758 let ck = |tyname: &str| {
759 let ck_public = |def: ast::DefId| {
760 debug!("privacy - ck_public {:?}", def);
761 let name = token::get_name(last);
762 let origdid = path_res.def_id();
763 self.ensure_public(span,
764 def,
765 Some(origdid),
766 &format!("{} `{}`", tyname, name))
767 };
768
769 match path_res.last_private {
770 LastMod(AllPublic) => {},
771 LastMod(DependsOn(def)) => {
772 self.report_error(ck_public(def));
773 },
774 LastImport { value_priv,
775 value_used: check_value,
776 type_priv,
777 type_used: check_type } => {
778 // This dance with found_error is because we don't want to
779 // report a privacy error twice for the same directive.
780 let found_error = match (type_priv, check_type) {
781 (Some(DependsOn(def)), Used) => {
782 !self.report_error(ck_public(def))
783 },
784 _ => false,
785 };
786 if !found_error {
787 match (value_priv, check_value) {
788 (Some(DependsOn(def)), Used) => {
789 self.report_error(ck_public(def));
790 },
791 _ => {},
792 }
793 }
794 // If an import is not used in either namespace, we still
795 // want to check that it could be legal. Therefore we check
796 // in both namespaces and only report an error if both would
797 // be illegal. We only report one error, even if it is
798 // illegal to import from both namespaces.
799 match (value_priv, check_value, type_priv, check_type) {
800 (Some(p), Unused, None, _) |
801 (None, _, Some(p), Unused) => {
802 let p = match p {
803 AllPublic => None,
804 DependsOn(def) => ck_public(def),
805 };
806 if p.is_some() {
807 self.report_error(p);
808 }
809 },
810 (Some(v), Unused, Some(t), Unused) => {
811 let v = match v {
812 AllPublic => None,
813 DependsOn(def) => ck_public(def),
814 };
815 let t = match t {
816 AllPublic => None,
817 DependsOn(def) => ck_public(def),
818 };
819 if let (Some(_), Some(t)) = (v, t) {
820 self.report_error(Some(t));
821 }
822 },
823 _ => {},
824 }
825 },
826 }
827 };
828 // FIXME(#12334) Imports can refer to definitions in both the type and
829 // value namespaces. The privacy information is aware of this, but the
830 // def map is not. Therefore the names we work out below will not always
831 // be accurate and we can get slightly wonky error messages (but type
832 // checking is always correct).
833 match path_res.full_def() {
834 def::DefFn(..) => ck("function"),
835 def::DefStatic(..) => ck("static"),
836 def::DefConst(..) => ck("const"),
837 def::DefAssociatedConst(..) => ck("associated const"),
838 def::DefVariant(..) => ck("variant"),
839 def::DefTy(_, false) => ck("type"),
840 def::DefTy(_, true) => ck("enum"),
841 def::DefTrait(..) => ck("trait"),
842 def::DefStruct(..) => ck("struct"),
843 def::DefMethod(..) => ck("method"),
844 def::DefMod(..) => ck("module"),
845 _ => {}
846 }
847 }
848
849 // Checks that a method is in scope.
850 fn check_method(&mut self, span: Span, origin: &MethodOrigin,
851 name: ast::Name) {
852 match *origin {
853 MethodStatic(method_id) => {
854 self.check_static_method(span, method_id, name)
855 }
856 MethodStaticClosure(_) => {}
857 // Trait methods are always all public. The only controlling factor
858 // is whether the trait itself is accessible or not.
859 MethodTypeParam(MethodParam { ref trait_ref, .. }) |
860 MethodTraitObject(MethodObject { ref trait_ref, .. }) => {
861 self.report_error(self.ensure_public(span, trait_ref.def_id,
862 None, "source trait"));
863 }
864 }
865 }
866 }
867
868 impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> {
869 fn visit_item(&mut self, item: &ast::Item) {
870 if let ast::ItemUse(ref vpath) = item.node {
871 if let ast::ViewPathList(ref prefix, ref list) = vpath.node {
872 for pid in list {
873 match pid.node {
874 ast::PathListIdent { id, name } => {
875 debug!("privacy - ident item {}", id);
876 self.check_path(pid.span, id, name.name);
877 }
878 ast::PathListMod { id } => {
879 debug!("privacy - mod item {}", id);
880 let name = prefix.segments.last().unwrap().identifier.name;
881 self.check_path(pid.span, id, name);
882 }
883 }
884 }
885 }
886 }
887 let orig_curitem = replace(&mut self.curitem, item.id);
888 visit::walk_item(self, item);
889 self.curitem = orig_curitem;
890 }
891
892 fn visit_expr(&mut self, expr: &ast::Expr) {
893 match expr.node {
894 ast::ExprField(ref base, ident) => {
895 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
896 self.check_field(expr.span, id, NamedField(ident.node.name));
897 }
898 }
899 ast::ExprTupField(ref base, idx) => {
900 if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty {
901 self.check_field(expr.span, id, UnnamedField(idx.node));
902 }
903 }
904 ast::ExprMethodCall(ident, _, _) => {
905 let method_call = MethodCall::expr(expr.id);
906 match self.tcx.method_map.borrow().get(&method_call) {
907 None => {
908 self.tcx.sess.span_bug(expr.span,
909 "method call not in \
910 method map");
911 }
912 Some(method) => {
913 debug!("(privacy checking) checking impl method");
914 self.check_method(expr.span, &method.origin, ident.node.name);
915 }
916 }
917 }
918 ast::ExprStruct(_, ref fields, _) => {
919 match ty::expr_ty(self.tcx, expr).sty {
920 ty::ty_struct(ctor_id, _) => {
921 // RFC 736: ensure all unmentioned fields are visible.
922 // Rather than computing the set of unmentioned fields
923 // (i.e. `all_fields - fields`), just check them all.
924 let all_fields = ty::lookup_struct_fields(self.tcx, ctor_id);
925 for field in all_fields {
926 self.check_field(expr.span, ctor_id,
927 NamedField(field.name));
928 }
929 }
930 ty::ty_enum(_, _) => {
931 match self.tcx.def_map.borrow().get(&expr.id).unwrap().full_def() {
932 def::DefVariant(_, variant_id, _) => {
933 for field in fields {
934 self.check_field(expr.span, variant_id,
935 NamedField(field.ident.node.name));
936 }
937 }
938 _ => self.tcx.sess.span_bug(expr.span,
939 "resolve didn't \
940 map enum struct \
941 constructor to a \
942 variant def"),
943 }
944 }
945 _ => self.tcx.sess.span_bug(expr.span, "struct expr \
946 didn't have \
947 struct type?!"),
948 }
949 }
950 ast::ExprPath(..) => {
951 let guard = |did: ast::DefId| {
952 let fields = ty::lookup_struct_fields(self.tcx, did);
953 let any_priv = fields.iter().any(|f| {
954 f.vis != ast::Public && (
955 !is_local(f.id) ||
956 !self.private_accessible(f.id.node))
957 });
958 if any_priv {
959 self.tcx.sess.span_err(expr.span,
960 "cannot invoke tuple struct constructor \
961 with private fields");
962 }
963 };
964 match self.tcx.def_map.borrow().get(&expr.id).map(|d| d.full_def()) {
965 Some(def::DefStruct(did)) => {
966 guard(if is_local(did) {
967 local_def(self.tcx.map.get_parent(did.node))
968 } else {
969 // "tuple structs" with zero fields (such as
970 // `pub struct Foo;`) don't have a ctor_id, hence
971 // the unwrap_or to the same struct id.
972 let maybe_did =
973 csearch::get_tuple_struct_definition_if_ctor(
974 &self.tcx.sess.cstore, did);
975 maybe_did.unwrap_or(did)
976 })
977 }
978 _ => {}
979 }
980 }
981 _ => {}
982 }
983
984 visit::walk_expr(self, expr);
985 }
986
987 fn visit_pat(&mut self, pattern: &ast::Pat) {
988 // Foreign functions do not have their patterns mapped in the def_map,
989 // and there's nothing really relevant there anyway, so don't bother
990 // checking privacy. If you can name the type then you can pass it to an
991 // external C function anyway.
992 if self.in_foreign { return }
993
994 match pattern.node {
995 ast::PatStruct(_, ref fields, _) => {
996 match ty::pat_ty(self.tcx, pattern).sty {
997 ty::ty_struct(id, _) => {
998 for field in fields {
999 self.check_field(pattern.span, id,
1000 NamedField(field.node.ident.name));
1001 }
1002 }
1003 ty::ty_enum(_, _) => {
1004 match self.tcx.def_map.borrow().get(&pattern.id).map(|d| d.full_def()) {
1005 Some(def::DefVariant(_, variant_id, _)) => {
1006 for field in fields {
1007 self.check_field(pattern.span, variant_id,
1008 NamedField(field.node.ident.name));
1009 }
1010 }
1011 _ => self.tcx.sess.span_bug(pattern.span,
1012 "resolve didn't \
1013 map enum struct \
1014 pattern to a \
1015 variant def"),
1016 }
1017 }
1018 _ => self.tcx.sess.span_bug(pattern.span,
1019 "struct pattern didn't have \
1020 struct type?!"),
1021 }
1022 }
1023
1024 // Patterns which bind no fields are allowable (the path is check
1025 // elsewhere).
1026 ast::PatEnum(_, Some(ref fields)) => {
1027 match ty::pat_ty(self.tcx, pattern).sty {
1028 ty::ty_struct(id, _) => {
1029 for (i, field) in fields.iter().enumerate() {
1030 if let ast::PatWild(..) = field.node {
1031 continue
1032 }
1033 self.check_field(field.span, id, UnnamedField(i));
1034 }
1035 }
1036 ty::ty_enum(..) => {
1037 // enum fields have no privacy at this time
1038 }
1039 _ => {}
1040 }
1041
1042 }
1043 _ => {}
1044 }
1045
1046 visit::walk_pat(self, pattern);
1047 }
1048
1049 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
1050 self.in_foreign = true;
1051 visit::walk_foreign_item(self, fi);
1052 self.in_foreign = false;
1053 }
1054
1055 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
1056 self.check_path(path.span, id, path.segments.last().unwrap().identifier.name);
1057 visit::walk_path(self, path);
1058 }
1059 }
1060
1061 ////////////////////////////////////////////////////////////////////////////////
1062 /// The privacy sanity check visitor, ensures unnecessary visibility isn't here
1063 ////////////////////////////////////////////////////////////////////////////////
1064
1065 struct SanePrivacyVisitor<'a, 'tcx: 'a> {
1066 tcx: &'a ty::ctxt<'tcx>,
1067 in_fn: bool,
1068 }
1069
1070 impl<'a, 'tcx, 'v> Visitor<'v> for SanePrivacyVisitor<'a, 'tcx> {
1071 fn visit_item(&mut self, item: &ast::Item) {
1072 if self.in_fn {
1073 self.check_all_inherited(item);
1074 } else {
1075 self.check_sane_privacy(item);
1076 }
1077
1078 let in_fn = self.in_fn;
1079 let orig_in_fn = replace(&mut self.in_fn, match item.node {
1080 ast::ItemMod(..) => false, // modules turn privacy back on
1081 _ => in_fn, // otherwise we inherit
1082 });
1083 visit::walk_item(self, item);
1084 self.in_fn = orig_in_fn;
1085 }
1086
1087 fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
1088 b: &'v ast::Block, s: Span, _: ast::NodeId) {
1089 // This catches both functions and methods
1090 let orig_in_fn = replace(&mut self.in_fn, true);
1091 visit::walk_fn(self, fk, fd, b, s);
1092 self.in_fn = orig_in_fn;
1093 }
1094 }
1095
1096 impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
1097 /// Validates all of the visibility qualifiers placed on the item given. This
1098 /// ensures that there are no extraneous qualifiers that don't actually do
1099 /// anything. In theory these qualifiers wouldn't parse, but that may happen
1100 /// later on down the road...
1101 fn check_sane_privacy(&self, item: &ast::Item) {
1102 let tcx = self.tcx;
1103 let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
1104 if vis != ast::Inherited {
1105 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
1106 if !note.is_empty() {
1107 tcx.sess.span_note(sp, note);
1108 }
1109 }
1110 };
1111 match item.node {
1112 // implementations of traits don't need visibility qualifiers because
1113 // that's controlled by having the trait in scope.
1114 ast::ItemImpl(_, _, _, Some(..), _, ref impl_items) => {
1115 check_inherited(item.span, item.vis,
1116 "visibility qualifiers have no effect on trait \
1117 impls");
1118 for impl_item in impl_items {
1119 check_inherited(impl_item.span, impl_item.vis, "");
1120 }
1121 }
1122
1123 ast::ItemImpl(..) => {
1124 check_inherited(item.span, item.vis,
1125 "place qualifiers on individual methods instead");
1126 }
1127 ast::ItemForeignMod(..) => {
1128 check_inherited(item.span, item.vis,
1129 "place qualifiers on individual functions \
1130 instead");
1131 }
1132
1133 ast::ItemEnum(ref def, _) => {
1134 for v in &def.variants {
1135 match v.node.vis {
1136 ast::Public => {
1137 if item.vis == ast::Public {
1138 tcx.sess.span_err(v.span, "unnecessary `pub` \
1139 visibility");
1140 }
1141 }
1142 ast::Inherited => {}
1143 }
1144 }
1145 }
1146
1147 ast::ItemTrait(..) | ast::ItemDefaultImpl(..) |
1148 ast::ItemConst(..) | ast::ItemStatic(..) | ast::ItemStruct(..) |
1149 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1150 ast::ItemExternCrate(_) | ast::ItemUse(_) | ast::ItemMac(..) => {}
1151 }
1152 }
1153
1154 /// When inside of something like a function or a method, visibility has no
1155 /// control over anything so this forbids any mention of any visibility
1156 fn check_all_inherited(&self, item: &ast::Item) {
1157 let tcx = self.tcx;
1158 fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
1159 if vis != ast::Inherited {
1160 tcx.sess.span_err(sp, "visibility has no effect inside functions");
1161 }
1162 }
1163 let check_struct = |def: &ast::StructDef| {
1164 for f in &def.fields {
1165 match f.node.kind {
1166 ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
1167 ast::UnnamedField(..) => {}
1168 }
1169 }
1170 };
1171 check_inherited(tcx, item.span, item.vis);
1172 match item.node {
1173 ast::ItemImpl(_, _, _, _, _, ref impl_items) => {
1174 for impl_item in impl_items {
1175 match impl_item.node {
1176 ast::MethodImplItem(..) => {
1177 check_inherited(tcx, impl_item.span, impl_item.vis);
1178 }
1179 _ => {}
1180 }
1181 }
1182 }
1183 ast::ItemForeignMod(ref fm) => {
1184 for i in &fm.items {
1185 check_inherited(tcx, i.span, i.vis);
1186 }
1187 }
1188 ast::ItemEnum(ref def, _) => {
1189 for v in &def.variants {
1190 check_inherited(tcx, v.span, v.node.vis);
1191 }
1192 }
1193
1194 ast::ItemStruct(ref def, _) => check_struct(&**def),
1195
1196 ast::ItemExternCrate(_) | ast::ItemUse(_) |
1197 ast::ItemTrait(..) | ast::ItemDefaultImpl(..) |
1198 ast::ItemStatic(..) | ast::ItemConst(..) |
1199 ast::ItemFn(..) | ast::ItemMod(..) | ast::ItemTy(..) |
1200 ast::ItemMac(..) => {}
1201 }
1202 }
1203 }
1204
1205 struct VisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1206 tcx: &'a ty::ctxt<'tcx>,
1207 exported_items: &'a ExportedItems,
1208 public_items: &'a PublicItems,
1209 in_variant: bool,
1210 }
1211
1212 struct CheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1213 inner: &'a VisiblePrivateTypesVisitor<'b, 'tcx>,
1214 /// whether the type refers to private types.
1215 contains_private: bool,
1216 /// whether we've recurred at all (i.e. if we're pointing at the
1217 /// first type on which visit_ty was called).
1218 at_outer_type: bool,
1219 // whether that first type is a public path.
1220 outer_type_is_public_path: bool,
1221 }
1222
1223 impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> {
1224 fn path_is_private_type(&self, path_id: ast::NodeId) -> bool {
1225 let did = match self.tcx.def_map.borrow().get(&path_id).map(|d| d.full_def()) {
1226 // `int` etc. (None doesn't seem to occur.)
1227 None | Some(def::DefPrimTy(..)) => return false,
1228 Some(def) => def.def_id(),
1229 };
1230 // A path can only be private if:
1231 // it's in this crate...
1232 if !is_local(did) {
1233 return false
1234 }
1235
1236 // .. and it corresponds to a private type in the AST (this returns
1237 // None for type parameters)
1238 match self.tcx.map.find(did.node) {
1239 Some(ast_map::NodeItem(ref item)) => item.vis != ast::Public,
1240 Some(_) | None => false,
1241 }
1242 }
1243
1244 fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1245 // FIXME: this would preferably be using `exported_items`, but all
1246 // traits are exported currently (see `EmbargoVisitor.exported_trait`)
1247 self.public_items.contains(&trait_id)
1248 }
1249
1250 fn check_ty_param_bound(&self,
1251 ty_param_bound: &ast::TyParamBound) {
1252 if let ast::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
1253 if !self.tcx.sess.features.borrow().visible_private_types &&
1254 self.path_is_private_type(trait_ref.trait_ref.ref_id) {
1255 let span = trait_ref.trait_ref.path.span;
1256 self.tcx.sess.span_err(span, "private trait in exported type \
1257 parameter bound");
1258 }
1259 }
1260 }
1261
1262 fn item_is_public(&self, id: &ast::NodeId, vis: ast::Visibility) -> bool {
1263 self.exported_items.contains(id) || vis == ast::Public
1264 }
1265 }
1266
1267 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for CheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1268 fn visit_ty(&mut self, ty: &ast::Ty) {
1269 if let ast::TyPath(..) = ty.node {
1270 if self.inner.path_is_private_type(ty.id) {
1271 self.contains_private = true;
1272 // found what we're looking for so let's stop
1273 // working.
1274 return
1275 } else if self.at_outer_type {
1276 self.outer_type_is_public_path = true;
1277 }
1278 }
1279 self.at_outer_type = false;
1280 visit::walk_ty(self, ty)
1281 }
1282
1283 // don't want to recurse into [, .. expr]
1284 fn visit_expr(&mut self, _: &ast::Expr) {}
1285 }
1286
1287 impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> {
1288 fn visit_item(&mut self, item: &ast::Item) {
1289 match item.node {
1290 // contents of a private mod can be reexported, so we need
1291 // to check internals.
1292 ast::ItemMod(_) => {}
1293
1294 // An `extern {}` doesn't introduce a new privacy
1295 // namespace (the contents have their own privacies).
1296 ast::ItemForeignMod(_) => {}
1297
1298 ast::ItemTrait(_, _, ref bounds, _) => {
1299 if !self.trait_is_public(item.id) {
1300 return
1301 }
1302
1303 for bound in &**bounds {
1304 self.check_ty_param_bound(bound)
1305 }
1306 }
1307
1308 // impls need some special handling to try to offer useful
1309 // error messages without (too many) false positives
1310 // (i.e. we could just return here to not check them at
1311 // all, or some worse estimation of whether an impl is
1312 // publicly visible).
1313 ast::ItemImpl(_, _, ref g, ref trait_ref, ref self_, ref impl_items) => {
1314 // `impl [... for] Private` is never visible.
1315 let self_contains_private;
1316 // impl [... for] Public<...>, but not `impl [... for]
1317 // Vec<Public>` or `(Public,)` etc.
1318 let self_is_public_path;
1319
1320 // check the properties of the Self type:
1321 {
1322 let mut visitor = CheckTypeForPrivatenessVisitor {
1323 inner: self,
1324 contains_private: false,
1325 at_outer_type: true,
1326 outer_type_is_public_path: false,
1327 };
1328 visitor.visit_ty(&**self_);
1329 self_contains_private = visitor.contains_private;
1330 self_is_public_path = visitor.outer_type_is_public_path;
1331 }
1332
1333 // miscellaneous info about the impl
1334
1335 // `true` iff this is `impl Private for ...`.
1336 let not_private_trait =
1337 trait_ref.as_ref().map_or(true, // no trait counts as public trait
1338 |tr| {
1339 let did = ty::trait_ref_to_def_id(self.tcx, tr);
1340
1341 !is_local(did) || self.trait_is_public(did.node)
1342 });
1343
1344 // `true` iff this is a trait impl or at least one method is public.
1345 //
1346 // `impl Public { $( fn ...() {} )* }` is not visible.
1347 //
1348 // This is required over just using the methods' privacy
1349 // directly because we might have `impl<T: Foo<Private>> ...`,
1350 // and we shouldn't warn about the generics if all the methods
1351 // are private (because `T` won't be visible externally).
1352 let trait_or_some_public_method =
1353 trait_ref.is_some() ||
1354 impl_items.iter()
1355 .any(|impl_item| {
1356 match impl_item.node {
1357 ast::ConstImplItem(..) |
1358 ast::MethodImplItem(..) => {
1359 self.exported_items.contains(&impl_item.id)
1360 }
1361 ast::TypeImplItem(_) |
1362 ast::MacImplItem(_) => false,
1363 }
1364 });
1365
1366 if !self_contains_private &&
1367 not_private_trait &&
1368 trait_or_some_public_method {
1369
1370 visit::walk_generics(self, g);
1371
1372 match *trait_ref {
1373 None => {
1374 for impl_item in impl_items {
1375 // This is where we choose whether to walk down
1376 // further into the impl to check its items. We
1377 // should only walk into public items so that we
1378 // don't erroneously report errors for private
1379 // types in private items.
1380 match impl_item.node {
1381 ast::ConstImplItem(..) |
1382 ast::MethodImplItem(..)
1383 if self.item_is_public(&impl_item.id, impl_item.vis) =>
1384 {
1385 visit::walk_impl_item(self, impl_item)
1386 }
1387 ast::TypeImplItem(..) => {
1388 visit::walk_impl_item(self, impl_item)
1389 }
1390 _ => {}
1391 }
1392 }
1393 }
1394 Some(ref tr) => {
1395 // Any private types in a trait impl fall into three
1396 // categories.
1397 // 1. mentioned in the trait definition
1398 // 2. mentioned in the type params/generics
1399 // 3. mentioned in the associated types of the impl
1400 //
1401 // Those in 1. can only occur if the trait is in
1402 // this crate and will've been warned about on the
1403 // trait definition (there's no need to warn twice
1404 // so we don't check the methods).
1405 //
1406 // Those in 2. are warned via walk_generics and this
1407 // call here.
1408 visit::walk_path(self, &tr.path);
1409
1410 // Those in 3. are warned with this call.
1411 for impl_item in impl_items {
1412 if let ast::TypeImplItem(ref ty) = impl_item.node {
1413 self.visit_ty(ty);
1414 }
1415 }
1416 }
1417 }
1418 } else if trait_ref.is_none() && self_is_public_path {
1419 // impl Public<Private> { ... }. Any public static
1420 // methods will be visible as `Public::foo`.
1421 let mut found_pub_static = false;
1422 for impl_item in impl_items {
1423 match impl_item.node {
1424 ast::ConstImplItem(..) => {
1425 if self.item_is_public(&impl_item.id, impl_item.vis) {
1426 found_pub_static = true;
1427 visit::walk_impl_item(self, impl_item);
1428 }
1429 }
1430 ast::MethodImplItem(ref sig, _) => {
1431 if sig.explicit_self.node == ast::SelfStatic &&
1432 self.item_is_public(&impl_item.id, impl_item.vis) {
1433 found_pub_static = true;
1434 visit::walk_impl_item(self, impl_item);
1435 }
1436 }
1437 _ => {}
1438 }
1439 }
1440 if found_pub_static {
1441 visit::walk_generics(self, g)
1442 }
1443 }
1444 return
1445 }
1446
1447 // `type ... = ...;` can contain private types, because
1448 // we're introducing a new name.
1449 ast::ItemTy(..) => return,
1450
1451 // not at all public, so we don't care
1452 _ if !self.item_is_public(&item.id, item.vis) => {
1453 return;
1454 }
1455
1456 _ => {}
1457 }
1458
1459 // We've carefully constructed it so that if we're here, then
1460 // any `visit_ty`'s will be called on things that are in
1461 // public signatures, i.e. things that we're interested in for
1462 // this visitor.
1463 debug!("VisiblePrivateTypesVisitor entering item {:?}", item);
1464 visit::walk_item(self, item);
1465 }
1466
1467 fn visit_generics(&mut self, generics: &ast::Generics) {
1468 for ty_param in &*generics.ty_params {
1469 for bound in &*ty_param.bounds {
1470 self.check_ty_param_bound(bound)
1471 }
1472 }
1473 for predicate in &generics.where_clause.predicates {
1474 match predicate {
1475 &ast::WherePredicate::BoundPredicate(ref bound_pred) => {
1476 for bound in &*bound_pred.bounds {
1477 self.check_ty_param_bound(bound)
1478 }
1479 }
1480 &ast::WherePredicate::RegionPredicate(_) => {}
1481 &ast::WherePredicate::EqPredicate(ref eq_pred) => {
1482 self.visit_ty(&*eq_pred.ty);
1483 }
1484 }
1485 }
1486 }
1487
1488 fn visit_foreign_item(&mut self, item: &ast::ForeignItem) {
1489 if self.exported_items.contains(&item.id) {
1490 visit::walk_foreign_item(self, item)
1491 }
1492 }
1493
1494 fn visit_ty(&mut self, t: &ast::Ty) {
1495 debug!("VisiblePrivateTypesVisitor checking ty {:?}", t);
1496 if let ast::TyPath(_, ref p) = t.node {
1497 if !self.tcx.sess.features.borrow().visible_private_types &&
1498 self.path_is_private_type(t.id) {
1499 self.tcx.sess.span_err(p.span, "private type in exported type signature");
1500 }
1501 }
1502 visit::walk_ty(self, t)
1503 }
1504
1505 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
1506 if self.exported_items.contains(&v.node.id) {
1507 self.in_variant = true;
1508 visit::walk_variant(self, v, g);
1509 self.in_variant = false;
1510 }
1511 }
1512
1513 fn visit_struct_field(&mut self, s: &ast::StructField) {
1514 match s.node.kind {
1515 ast::NamedField(_, vis) if vis == ast::Public || self.in_variant => {
1516 visit::walk_struct_field(self, s);
1517 }
1518 _ => {}
1519 }
1520 }
1521
1522
1523 // we don't need to introspect into these at all: an
1524 // expression/block context can't possibly contain exported things.
1525 // (Making them no-ops stops us from traversing the whole AST without
1526 // having to be super careful about our `walk_...` calls above.)
1527 fn visit_block(&mut self, _: &ast::Block) {}
1528 fn visit_expr(&mut self, _: &ast::Expr) {}
1529 }
1530
1531 pub fn check_crate(tcx: &ty::ctxt,
1532 export_map: &def::ExportMap,
1533 external_exports: ExternalExports)
1534 -> (ExportedItems, PublicItems) {
1535 let krate = tcx.map.krate();
1536
1537 // Figure out who everyone's parent is
1538 let mut visitor = ParentVisitor {
1539 parents: NodeMap(),
1540 curparent: ast::DUMMY_NODE_ID,
1541 };
1542 visit::walk_crate(&mut visitor, krate);
1543
1544 // Use the parent map to check the privacy of everything
1545 let mut visitor = PrivacyVisitor {
1546 curitem: ast::DUMMY_NODE_ID,
1547 in_foreign: false,
1548 tcx: tcx,
1549 parents: visitor.parents,
1550 external_exports: external_exports,
1551 };
1552 visit::walk_crate(&mut visitor, krate);
1553
1554 // Sanity check to make sure that all privacy usage and controls are
1555 // reasonable.
1556 let mut visitor = SanePrivacyVisitor {
1557 in_fn: false,
1558 tcx: tcx,
1559 };
1560 visit::walk_crate(&mut visitor, krate);
1561
1562 tcx.sess.abort_if_errors();
1563
1564 // Build up a set of all exported items in the AST. This is a set of all
1565 // items which are reachable from external crates based on visibility.
1566 let mut visitor = EmbargoVisitor {
1567 tcx: tcx,
1568 exported_items: NodeSet(),
1569 public_items: NodeSet(),
1570 reexports: NodeSet(),
1571 export_map: export_map,
1572 prev_exported: true,
1573 prev_public: true,
1574 };
1575 loop {
1576 let before = visitor.exported_items.len();
1577 visit::walk_crate(&mut visitor, krate);
1578 if before == visitor.exported_items.len() {
1579 break
1580 }
1581 }
1582
1583 let EmbargoVisitor { exported_items, public_items, .. } = visitor;
1584
1585 {
1586 let mut visitor = VisiblePrivateTypesVisitor {
1587 tcx: tcx,
1588 exported_items: &exported_items,
1589 public_items: &public_items,
1590 in_variant: false,
1591 };
1592 visit::walk_crate(&mut visitor, krate);
1593 }
1594 return (exported_items, public_items);
1595 }