1 use rustc::middle::privacy::{AccessLevels, AccessLevel};
2 use rustc::hir::def::{Res, DefKind};
3 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
4 use rustc::ty::{TyCtxt, Visibility};
5 use rustc::util::nodemap::FxHashSet;
6 use syntax::symbol::sym;
8 use crate::clean::{AttributesExt, NestedAttributesExt};
10 // FIXME: this may not be exhaustive, but is sufficient for rustdocs current uses
12 /// Similar to `librustc_privacy::EmbargoVisitor`, but also takes
13 /// specific rustdoc annotations into account (i.e., `doc(hidden)`)
14 pub struct LibEmbargoVisitor<'a, 'tcx> {
16 // Accessibility levels for reachable nodes
17 access_levels: &'a mut AccessLevels<DefId>,
18 // Previous accessibility level, None means unreachable
19 prev_level: Option<AccessLevel>,
20 // Keeps track of already visited modules, in case a module re-exports its parent
21 visited_mods: FxHashSet<DefId>,
24 impl<'a, 'tcx> LibEmbargoVisitor<'a, 'tcx> {
26 cx: &'a mut crate::core::DocContext<'tcx>
27 ) -> LibEmbargoVisitor<'a, 'tcx> {
30 access_levels: &mut cx.renderinfo.get_mut().access_levels,
31 prev_level: Some(AccessLevel::Public),
32 visited_mods: FxHashSet::default(),
36 pub fn visit_lib(&mut self, cnum: CrateNum) {
37 let did = DefId { krate: cnum, index: CRATE_DEF_INDEX };
38 self.update(did, Some(AccessLevel::Public));
42 // Updates node level and returns the updated level
43 fn update(&mut self, did: DefId, level: Option<AccessLevel>) -> Option<AccessLevel> {
44 let is_hidden = self.tcx.get_attrs(did).lists(sym::doc).has_word(sym::hidden);
46 let old_level = self.access_levels.map.get(&did).cloned();
47 // Accessibility levels can only grow
48 if level > old_level && !is_hidden {
49 self.access_levels.map.insert(did, level.unwrap());
56 pub fn visit_mod(&mut self, def_id: DefId) {
57 if !self.visited_mods.insert(def_id) {
61 for item in self.tcx.item_children(def_id).iter() {
62 if let Some(def_id) = item.res.opt_def_id() {
63 if self.tcx.def_key(def_id).parent.map_or(false, |d| d == def_id.index) ||
64 item.vis == Visibility::Public {
65 self.visit_item(item.res);
71 fn visit_item(&mut self, res: Res) {
72 let def_id = res.def_id();
73 let vis = self.tcx.visibility(def_id);
74 let inherited_item_level = if vis == Visibility::Public {
80 let item_level = self.update(def_id, inherited_item_level);
82 if let Res::Def(DefKind::Mod, _) = res {
83 let orig_level = self.prev_level;
85 self.prev_level = item_level;
86 self.visit_mod(def_id);
87 self.prev_level = orig_level;