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