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