]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
bootstrap: convert rls to use Tarball
[rust.git] / src / librustdoc / visit_ast.rs
1 //! The Rust AST Visitor. Extracts useful information and massages it into a form
2 //! usable for `clean`.
3
4 use rustc_ast as ast;
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_hir as hir;
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::def_id::DefId;
9 use rustc_hir::Node;
10 use rustc_middle::middle::privacy::AccessLevel;
11 use rustc_middle::ty::TyCtxt;
12 use rustc_span::source_map::Spanned;
13 use rustc_span::symbol::{kw, sym, Symbol};
14 use rustc_span::{self, Span};
15
16 use std::mem;
17
18 use crate::clean::{self, AttributesExt, NestedAttributesExt};
19 use crate::core;
20 use crate::doctree::*;
21
22 // FIXME: Should this be replaced with tcx.def_path_str?
23 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> {
24     let crate_name = tcx.crate_name(did.krate).to_string();
25     let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| {
26         // extern blocks have an empty name
27         let s = elem.data.to_string();
28         if !s.is_empty() { Some(s) } else { None }
29     });
30     std::iter::once(crate_name).chain(relative).collect()
31 }
32
33 // Also, is there some reason that this doesn't use the 'visit'
34 // framework from syntax?.
35
36 crate struct RustdocVisitor<'a, 'tcx> {
37     cx: &'a mut core::DocContext<'tcx>,
38     view_item_stack: FxHashSet<hir::HirId>,
39     inlining: bool,
40     /// Are the current module and all of its parents public?
41     inside_public_path: bool,
42     exact_paths: FxHashMap<DefId, Vec<String>>,
43 }
44
45 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
46     crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
47         // If the root is re-exported, terminate all recursion.
48         let mut stack = FxHashSet::default();
49         stack.insert(hir::CRATE_HIR_ID);
50         RustdocVisitor {
51             cx,
52             view_item_stack: stack,
53             inlining: false,
54             inside_public_path: true,
55             exact_paths: FxHashMap::default(),
56         }
57     }
58
59     fn store_path(&mut self, did: DefId) {
60         let tcx = self.cx.tcx;
61         self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
62     }
63
64     crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> {
65         let mut module = self.visit_mod_contents(
66             krate.item.span,
67             krate.item.attrs,
68             &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public },
69             hir::CRATE_HIR_ID,
70             &krate.item.module,
71             None,
72         );
73         // Attach the crate's exported macros to the top-level module:
74         module.macros.extend(krate.exported_macros.iter().map(|def| (def, None)));
75         module.is_crate = true;
76
77         self.cx.renderinfo.get_mut().exact_paths = self.exact_paths;
78
79         module
80     }
81
82     fn visit_mod_contents(
83         &mut self,
84         span: Span,
85         attrs: &'tcx [ast::Attribute],
86         vis: &'tcx hir::Visibility<'_>,
87         id: hir::HirId,
88         m: &'tcx hir::Mod<'tcx>,
89         name: Option<Symbol>,
90     ) -> Module<'tcx> {
91         let mut om = Module::new(name, attrs);
92         om.where_outer = span;
93         om.where_inner = m.inner;
94         om.id = id;
95         // Keep track of if there were any private modules in the path.
96         let orig_inside_public_path = self.inside_public_path;
97         self.inside_public_path &= vis.node.is_pub();
98         for i in m.item_ids {
99             let item = self.cx.tcx.hir().expect_item(i.id);
100             self.visit_item(item, None, &mut om);
101         }
102         self.inside_public_path = orig_inside_public_path;
103         om
104     }
105
106     /// Tries to resolve the target of a `crate use` statement and inlines the
107     /// target if it is defined locally and would not be documented otherwise,
108     /// or when it is specifically requested with `please_inline`.
109     /// (the latter is the case when the import is marked `doc(inline)`)
110     ///
111     /// Cross-crate inlining occurs later on during crate cleaning
112     /// and follows different rules.
113     ///
114     /// Returns `true` if the target has been inlined.
115     fn maybe_inline_local(
116         &mut self,
117         id: hir::HirId,
118         res: Res,
119         renamed: Option<Symbol>,
120         glob: bool,
121         om: &mut Module<'tcx>,
122         please_inline: bool,
123     ) -> bool {
124         fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
125             while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
126                 node = id;
127                 if cx.tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
128                     return true;
129                 }
130                 if node == hir::CRATE_HIR_ID {
131                     break;
132                 }
133             }
134             false
135         }
136
137         debug!("maybe_inline_local res: {:?}", res);
138
139         let tcx = self.cx.tcx;
140         let res_did = if let Some(did) = res.opt_def_id() {
141             did
142         } else {
143             return false;
144         };
145
146         let use_attrs = tcx.hir().attrs(id);
147         // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
148         let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
149             || use_attrs.lists(sym::doc).has_word(sym::hidden);
150
151         // For cross-crate impl inlining we need to know whether items are
152         // reachable in documentation -- a previously nonreachable item can be
153         // made reachable by cross-crate inlining which we're checking here.
154         // (this is done here because we need to know this upfront).
155         if !res_did.is_local() && !is_no_inline {
156             let attrs = clean::inline::load_attrs(self.cx, res_did);
157             let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
158             if !self_is_hidden {
159                 if let Res::Def(kind, did) = res {
160                     if kind == DefKind::Mod {
161                         crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
162                     } else {
163                         // All items need to be handled here in case someone wishes to link
164                         // to them with intra-doc links
165                         self.cx
166                             .renderinfo
167                             .get_mut()
168                             .access_levels
169                             .map
170                             .insert(did, AccessLevel::Public);
171                     }
172                 }
173             }
174             return false;
175         }
176
177         let res_hir_id = match res_did.as_local() {
178             Some(n) => tcx.hir().local_def_id_to_hir_id(n),
179             None => return false,
180         };
181
182         let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
183         let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
184
185         // Only inline if requested or if the item would otherwise be stripped.
186         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
187             return false;
188         }
189
190         if !self.view_item_stack.insert(res_hir_id) {
191             return false;
192         }
193
194         let ret = match tcx.hir().get(res_hir_id) {
195             Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
196                 let prev = mem::replace(&mut self.inlining, true);
197                 for i in m.item_ids {
198                     let i = self.cx.tcx.hir().expect_item(i.id);
199                     self.visit_item(i, None, om);
200                 }
201                 self.inlining = prev;
202                 true
203             }
204             Node::Item(it) if !glob => {
205                 let prev = mem::replace(&mut self.inlining, true);
206                 self.visit_item(it, renamed, om);
207                 self.inlining = prev;
208                 true
209             }
210             Node::ForeignItem(it) if !glob => {
211                 let prev = mem::replace(&mut self.inlining, true);
212                 self.visit_foreign_item(it, renamed, om);
213                 self.inlining = prev;
214                 true
215             }
216             Node::MacroDef(def) if !glob => {
217                 om.macros.push((def, renamed));
218                 true
219             }
220             _ => false,
221         };
222         self.view_item_stack.remove(&res_hir_id);
223         ret
224     }
225
226     fn visit_item(
227         &mut self,
228         item: &'tcx hir::Item<'_>,
229         renamed: Option<Symbol>,
230         om: &mut Module<'tcx>,
231     ) {
232         debug!("visiting item {:?}", item);
233         let name = renamed.unwrap_or(item.ident.name);
234
235         if item.vis.node.is_pub() {
236             let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
237             self.store_path(def_id.to_def_id());
238         }
239
240         match item.kind {
241             hir::ItemKind::ForeignMod { items, .. } => {
242                 for item in items {
243                     let item = self.cx.tcx.hir().foreign_item(item.id);
244                     self.visit_foreign_item(item, None, om);
245                 }
246             }
247             // If we're inlining, skip private items.
248             _ if self.inlining && !item.vis.node.is_pub() => {}
249             hir::ItemKind::GlobalAsm(..) => {}
250             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
251             hir::ItemKind::Use(ref path, kind) => {
252                 let is_glob = kind == hir::UseKind::Glob;
253
254                 // Struct and variant constructors and proc macro stubs always show up alongside
255                 // their definitions, we've already processed them so just discard these.
256                 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
257                     return;
258                 }
259
260                 // If there was a private module in the current path then don't bother inlining
261                 // anything as it will probably be stripped anyway.
262                 if item.vis.node.is_pub() && self.inside_public_path {
263                     let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
264                         Some(ref list) if item.has_name(sym::doc) => {
265                             list.iter().any(|i| i.has_name(sym::inline))
266                         }
267                         _ => false,
268                     });
269                     let ident = if is_glob { None } else { Some(name) };
270                     if self.maybe_inline_local(
271                         item.hir_id,
272                         path.res,
273                         ident,
274                         is_glob,
275                         om,
276                         please_inline,
277                     ) {
278                         return;
279                     }
280                 }
281
282                 om.imports.push(Import {
283                     name,
284                     id: item.hir_id,
285                     vis: &item.vis,
286                     attrs: &item.attrs,
287                     path,
288                     glob: is_glob,
289                     span: item.span,
290                 });
291             }
292             hir::ItemKind::Mod(ref m) => {
293                 om.mods.push(self.visit_mod_contents(
294                     item.span,
295                     &item.attrs,
296                     &item.vis,
297                     item.hir_id,
298                     m,
299                     Some(name),
300                 ));
301             }
302             hir::ItemKind::Fn(..)
303             | hir::ItemKind::ExternCrate(..)
304             | hir::ItemKind::Enum(..)
305             | hir::ItemKind::Struct(..)
306             | hir::ItemKind::Union(..)
307             | hir::ItemKind::TyAlias(..)
308             | hir::ItemKind::OpaqueTy(..)
309             | hir::ItemKind::Static(..)
310             | hir::ItemKind::Trait(..)
311             | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)),
312             hir::ItemKind::Const(..) => {
313                 // Underscore constants do not correspond to a nameable item and
314                 // so are never useful in documentation.
315                 if name != kw::Underscore {
316                     om.items.push((item, renamed));
317                 }
318             }
319             hir::ItemKind::Impl { ref of_trait, .. } => {
320                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
321                 // them up regardless of where they're located.
322                 if !self.inlining && of_trait.is_none() {
323                     om.items.push((item, None));
324                 }
325             }
326         }
327     }
328
329     fn visit_foreign_item(
330         &mut self,
331         item: &'tcx hir::ForeignItem<'_>,
332         renamed: Option<Symbol>,
333         om: &mut Module<'tcx>,
334     ) {
335         // If inlining we only want to include public functions.
336         if !self.inlining || item.vis.node.is_pub() {
337             om.foreigns.push((item, renamed));
338         }
339     }
340 }