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