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