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