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