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