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