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