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