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