]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Speed up execution a bit by removing some walks
[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::intravisit::{walk_item, Visitor};
9 use rustc_hir::Node;
10 use rustc_hir::CRATE_HIR_ID;
11 use rustc_middle::hir::map::Map;
12 use rustc_middle::hir::nested_filter;
13 use rustc_middle::ty::TyCtxt;
14 use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
15 use rustc_span::symbol::{kw, sym, Symbol};
16 use rustc_span::Span;
17
18 use std::mem;
19
20 use crate::clean::{cfg::Cfg, AttributesExt, NestedAttributesExt};
21 use crate::core;
22
23 /// This module is used to store stuff from Rust's AST in a more convenient
24 /// manner (and with prettier names) before cleaning.
25 #[derive(Debug)]
26 pub(crate) struct Module<'hir> {
27     pub(crate) name: Symbol,
28     pub(crate) where_inner: Span,
29     pub(crate) mods: Vec<Module<'hir>>,
30     pub(crate) id: hir::HirId,
31     // (item, renamed, import_id)
32     pub(crate) items: Vec<(&'hir hir::Item<'hir>, Option<Symbol>, Option<hir::HirId>)>,
33     pub(crate) foreigns: Vec<(&'hir hir::ForeignItem<'hir>, Option<Symbol>)>,
34 }
35
36 impl Module<'_> {
37     pub(crate) fn new(name: Symbol, id: hir::HirId, where_inner: Span) -> Self {
38         Module { name, id, where_inner, mods: Vec::new(), items: Vec::new(), foreigns: Vec::new() }
39     }
40
41     pub(crate) fn where_outer(&self, tcx: TyCtxt<'_>) -> Span {
42         tcx.hir().span(self.id)
43     }
44 }
45
46 // FIXME: Should this be replaced with tcx.def_path_str?
47 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<Symbol> {
48     let crate_name = tcx.crate_name(did.krate);
49     let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
50     std::iter::once(crate_name).chain(relative).collect()
51 }
52
53 pub(crate) fn inherits_doc_hidden(tcx: TyCtxt<'_>, mut node: hir::HirId) -> bool {
54     while let Some(id) = tcx.hir().get_enclosing_scope(node) {
55         node = id;
56         if tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
57             return true;
58         }
59     }
60     false
61 }
62
63 pub(crate) struct RustdocVisitor<'a, 'tcx> {
64     cx: &'a mut core::DocContext<'tcx>,
65     view_item_stack: FxHashSet<hir::HirId>,
66     inlining: bool,
67     /// Are the current module and all of its parents public?
68     inside_public_path: bool,
69     exact_paths: FxHashMap<DefId, Vec<Symbol>>,
70     modules: Vec<Module<'tcx>>,
71     map: Map<'tcx>,
72 }
73
74 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
75     pub(crate) fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
76         // If the root is re-exported, terminate all recursion.
77         let mut stack = FxHashSet::default();
78         stack.insert(hir::CRATE_HIR_ID);
79         let om = Module::new(
80             cx.tcx.crate_name(LOCAL_CRATE),
81             hir::CRATE_HIR_ID,
82             cx.tcx.hir().root_module().spans.inner_span,
83         );
84         let map = cx.tcx.hir();
85
86         RustdocVisitor {
87             cx,
88             view_item_stack: stack,
89             inlining: false,
90             inside_public_path: true,
91             exact_paths: FxHashMap::default(),
92             modules: vec![om],
93             map,
94         }
95     }
96
97     fn store_path(&mut self, did: DefId) {
98         let tcx = self.cx.tcx;
99         self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
100     }
101
102     /// Tries to resolve the target of a `pub use` statement and inlines the
103     /// target if it is defined locally and would not be documented otherwise,
104     /// or when it is specifically requested with `please_inline`.
105     /// (the latter is the case when the import is marked `doc(inline)`)
106     ///
107     /// Cross-crate inlining occurs later on during crate cleaning
108     /// and follows different rules.
109     ///
110     /// Returns `true` if the target has been inlined.
111     fn maybe_inline_local(
112         &mut self,
113         id: hir::HirId,
114         res: Res,
115         renamed: Option<Symbol>,
116         glob: bool,
117         please_inline: bool,
118     ) -> bool {
119         debug!("maybe_inline_local res: {:?}", res);
120
121         if self.cx.output_format.is_json() {
122             return false;
123         }
124
125         let tcx = self.cx.tcx;
126         let Some(res_did) = res.opt_def_id() else {
127             return false;
128         };
129
130         let use_attrs = tcx.hir().attrs(id);
131         // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
132         let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
133             || use_attrs.lists(sym::doc).has_word(sym::hidden);
134
135         // For cross-crate impl inlining we need to know whether items are
136         // reachable in documentation -- a previously unreachable item can be
137         // made reachable by cross-crate inlining which we're checking here.
138         // (this is done here because we need to know this upfront).
139         if !res_did.is_local() && !is_no_inline {
140             crate::visit_lib::lib_embargo_visit_item(self.cx, res_did);
141             return false;
142         }
143
144         let res_hir_id = match res_did.as_local() {
145             Some(n) => tcx.hir().local_def_id_to_hir_id(n),
146             None => return false,
147         };
148
149         let is_private =
150             !self.cx.cache.effective_visibilities.is_directly_public(self.cx.tcx, res_did);
151         let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id);
152
153         // Only inline if requested or if the item would otherwise be stripped.
154         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
155             return false;
156         }
157
158         if !self.view_item_stack.insert(res_hir_id) {
159             return false;
160         }
161
162         let ret = match tcx.hir().get(res_hir_id) {
163             Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
164                 let prev = mem::replace(&mut self.inlining, true);
165                 for &i in m.item_ids {
166                     let i = self.cx.tcx.hir().item(i);
167                     self.visit_item_inner(i, None, Some(id));
168                 }
169                 self.inlining = prev;
170                 true
171             }
172             Node::Item(it) if !glob => {
173                 let prev = mem::replace(&mut self.inlining, true);
174                 self.visit_item_inner(it, renamed, Some(id));
175                 self.inlining = prev;
176                 true
177             }
178             Node::ForeignItem(it) if !glob => {
179                 let prev = mem::replace(&mut self.inlining, true);
180                 self.visit_foreign_item_inner(it, renamed);
181                 self.inlining = prev;
182                 true
183             }
184             _ => false,
185         };
186         self.view_item_stack.remove(&res_hir_id);
187         ret
188     }
189
190     #[inline]
191     fn add_to_current_mod(
192         &mut self,
193         item: &'tcx hir::Item<'_>,
194         renamed: Option<Symbol>,
195         parent_id: Option<hir::HirId>,
196     ) {
197         self.modules.last_mut().unwrap().items.push((item, renamed, parent_id))
198     }
199
200     fn visit_item_inner(
201         &mut self,
202         item: &'tcx hir::Item<'_>,
203         renamed: Option<Symbol>,
204         parent_id: Option<hir::HirId>,
205     ) -> bool {
206         debug!("visiting item {:?}", item);
207         let name = renamed.unwrap_or(item.ident.name);
208
209         let def_id = item.owner_id.to_def_id();
210         let is_pub = self.cx.tcx.visibility(def_id).is_public();
211
212         if is_pub {
213             self.store_path(item.owner_id.to_def_id());
214         }
215
216         match item.kind {
217             hir::ItemKind::ForeignMod { items, .. } => {
218                 for item in items {
219                     let item = self.cx.tcx.hir().foreign_item(item.id);
220                     self.visit_foreign_item_inner(item, None);
221                 }
222             }
223             // If we're inlining, skip private items or item reexported as "_".
224             _ if self.inlining && (!is_pub || renamed == Some(kw::Underscore)) => {}
225             hir::ItemKind::GlobalAsm(..) => {}
226             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
227             hir::ItemKind::Use(path, kind) => {
228                 for &res in &path.res {
229                     // Struct and variant constructors and proc macro stubs always show up alongside
230                     // their definitions, we've already processed them so just discard these.
231                     if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
232                         continue;
233                     }
234
235                     let attrs = self.cx.tcx.hir().attrs(item.hir_id());
236
237                     // If there was a private module in the current path then don't bother inlining
238                     // anything as it will probably be stripped anyway.
239                     if is_pub && self.inside_public_path {
240                         let please_inline = attrs.iter().any(|item| match item.meta_item_list() {
241                             Some(ref list) if item.has_name(sym::doc) => {
242                                 list.iter().any(|i| i.has_name(sym::inline))
243                             }
244                             _ => false,
245                         });
246                         let is_glob = kind == hir::UseKind::Glob;
247                         let ident = if is_glob { None } else { Some(name) };
248                         if self.maybe_inline_local(
249                             item.hir_id(),
250                             res,
251                             ident,
252                             is_glob,
253                             please_inline,
254                         ) {
255                             continue;
256                         }
257                     }
258
259                     self.add_to_current_mod(item, renamed, parent_id);
260                 }
261             }
262             hir::ItemKind::Macro(ref macro_def, _) => {
263                 // `#[macro_export] macro_rules!` items are handled separately in `visit()`,
264                 // above, since they need to be documented at the module top level. Accordingly,
265                 // we only want to handle macros if one of three conditions holds:
266                 //
267                 // 1. This macro was defined by `macro`, and thus isn't covered by the case
268                 //    above.
269                 // 2. This macro isn't marked with `#[macro_export]`, and thus isn't covered
270                 //    by the case above.
271                 // 3. We're inlining, since a reexport where inlining has been requested
272                 //    should be inlined even if it is also documented at the top level.
273
274                 let def_id = item.owner_id.to_def_id();
275                 let is_macro_2_0 = !macro_def.macro_rules;
276                 let nonexported = !self.cx.tcx.has_attr(def_id, sym::macro_export);
277
278                 if is_macro_2_0 || nonexported || self.inlining {
279                     self.add_to_current_mod(item, renamed, None);
280                 }
281             }
282             hir::ItemKind::Mod(ref m) => {
283                 self.enter_mod(item.hir_id(), m, name);
284             }
285             hir::ItemKind::Fn(..)
286             | hir::ItemKind::ExternCrate(..)
287             | hir::ItemKind::Enum(..)
288             | hir::ItemKind::Struct(..)
289             | hir::ItemKind::Union(..)
290             | hir::ItemKind::TyAlias(..)
291             | hir::ItemKind::OpaqueTy(..)
292             | hir::ItemKind::Static(..)
293             | hir::ItemKind::Trait(..)
294             | hir::ItemKind::TraitAlias(..) => {
295                 self.add_to_current_mod(item, renamed, parent_id);
296             }
297             hir::ItemKind::Const(..) => {
298                 // Underscore constants do not correspond to a nameable item and
299                 // so are never useful in documentation.
300                 if name != kw::Underscore {
301                     self.add_to_current_mod(item, renamed, parent_id);
302                 }
303             }
304             hir::ItemKind::Impl(impl_) => {
305                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
306                 // them up regardless of where they're located.
307                 if !self.inlining && impl_.of_trait.is_none() {
308                     self.add_to_current_mod(item, None, None);
309                 }
310             }
311         }
312         true
313     }
314
315     fn visit_foreign_item_inner(
316         &mut self,
317         item: &'tcx hir::ForeignItem<'_>,
318         renamed: Option<Symbol>,
319     ) {
320         // If inlining we only want to include public functions.
321         if !self.inlining || self.cx.tcx.visibility(item.owner_id).is_public() {
322             self.modules.last_mut().unwrap().foreigns.push((item, renamed));
323         }
324     }
325
326     pub(crate) fn visit(mut self) -> Module<'tcx> {
327         let root_module = self.cx.tcx.hir().root_module();
328         self.visit_mod_contents(CRATE_HIR_ID, root_module);
329
330         let mut top_level_module = self.modules.pop().unwrap();
331
332         // `#[macro_export] macro_rules!` items are reexported at the top level of the
333         // crate, regardless of where they're defined. We want to document the
334         // top level rexport of the macro, not its original definition, since
335         // the rexport defines the path that a user will actually see. Accordingly,
336         // we add the rexport as an item here, and then skip over the original
337         // definition in `visit_item()` below.
338         //
339         // We also skip `#[macro_export] macro_rules!` that have already been inserted,
340         // it can happen if within the same module a `#[macro_export] macro_rules!`
341         // is declared but also a reexport of itself producing two exports of the same
342         // macro in the same module.
343         let mut inserted = FxHashSet::default();
344         for export in self.cx.tcx.module_reexports(CRATE_DEF_ID).unwrap_or(&[]) {
345             if let Res::Def(DefKind::Macro(_), def_id) = export.res &&
346                 let Some(local_def_id) = def_id.as_local() &&
347                 self.cx.tcx.has_attr(def_id, sym::macro_export) &&
348                 inserted.insert(def_id)
349             {
350                     let item = self.cx.tcx.hir().expect_item(local_def_id);
351                     top_level_module.items.push((item, None, None));
352             }
353         }
354
355         self.cx.cache.hidden_cfg = self
356             .cx
357             .tcx
358             .hir()
359             .attrs(CRATE_HIR_ID)
360             .iter()
361             .filter(|attr| attr.has_name(sym::doc))
362             .flat_map(|attr| attr.meta_item_list().into_iter().flatten())
363             .filter(|attr| attr.has_name(sym::cfg_hide))
364             .flat_map(|attr| {
365                 attr.meta_item_list()
366                     .unwrap_or(&[])
367                     .iter()
368                     .filter_map(|attr| {
369                         Cfg::parse(attr.meta_item()?)
370                             .map_err(|e| self.cx.sess().diagnostic().span_err(e.span, e.msg))
371                             .ok()
372                     })
373                     .collect::<Vec<_>>()
374             })
375             .chain(
376                 [Cfg::Cfg(sym::test, None), Cfg::Cfg(sym::doc, None), Cfg::Cfg(sym::doctest, None)]
377                     .into_iter(),
378             )
379             .collect();
380
381         self.cx.cache.exact_paths = self.exact_paths;
382         top_level_module
383     }
384
385     /// This method will create a new module and push it onto the "modules stack" then call
386     /// `visit_mod_contents`. Once done, it'll remove it from the "modules stack" and instead
387     /// add into into the list of modules of the current module.
388     fn enter_mod(&mut self, id: hir::HirId, m: &'tcx hir::Mod<'tcx>, name: Symbol) {
389         self.modules.push(Module::new(name, id, m.spans.inner_span));
390
391         self.visit_mod_contents(id, m);
392
393         let last = self.modules.pop().unwrap();
394         self.modules.last_mut().unwrap().mods.push(last);
395     }
396
397     /// This method will go through the given module items in two passes:
398     /// 1. The items which are not glob imports/reexports.
399     /// 2. The glob imports/reexports.
400     fn visit_mod_contents(&mut self, id: hir::HirId, m: &'tcx hir::Mod<'tcx>) {
401         debug!("Going through module {:?}", m);
402         let def_id = self.cx.tcx.hir().local_def_id(id).to_def_id();
403         // Keep track of if there were any private modules in the path.
404         let orig_inside_public_path = self.inside_public_path;
405         self.inside_public_path &= self.cx.tcx.visibility(def_id).is_public();
406
407         // Reimplementation of `walk_mod`:
408         for &i in m.item_ids {
409             let item = self.cx.tcx.hir().item(i);
410             if !matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
411                 self.visit_item(item);
412             }
413         }
414         for &i in m.item_ids {
415             let item = self.cx.tcx.hir().item(i);
416             // To match the way import precedence works, visit glob imports last.
417             // Later passes in rustdoc will de-duplicate by name and kind, so if glob-
418             // imported items appear last, then they'll be the ones that get discarded.
419             if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
420                 self.visit_item(item);
421             }
422         }
423         self.inside_public_path = orig_inside_public_path;
424     }
425 }
426
427 // We need to implement this visitor so it'll go everywhere and retrieve items we're interested in
428 // such as impl blocks in const blocks.
429 impl<'a, 'tcx> Visitor<'tcx> for RustdocVisitor<'a, 'tcx> {
430     type NestedFilter = nested_filter::All;
431
432     fn nested_visit_map(&mut self) -> Self::Map {
433         self.map
434     }
435
436     fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) {
437         let parent_id = if self.modules.len() > 1 {
438             Some(self.modules[self.modules.len() - 2].id)
439         } else {
440             None
441         };
442         if self.visit_item_inner(i, None, parent_id) {
443             walk_item(self, i);
444         }
445     }
446
447     fn visit_mod(&mut self, _: &hir::Mod<'tcx>, _: Span, _: hir::HirId) {
448         // Handled in `visit_item_inner`
449     }
450
451     fn visit_use(&mut self, _: &hir::UsePath<'tcx>, _: hir::HirId) {
452         // Handled in `visit_item_inner`
453     }
454
455     fn visit_path(&mut self, _: &hir::Path<'tcx>, _: hir::HirId) {
456         // Handled in `visit_item_inner`
457     }
458
459     fn visit_label(&mut self, _: &rustc_ast::Label) {
460         // Unneeded.
461     }
462
463     fn visit_infer(&mut self, _: &hir::InferArg) {
464         // Unneeded.
465     }
466
467     fn visit_lifetime(&mut self, _: &hir::Lifetime) {
468         // Unneeded.
469     }
470 }