]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Auto merge of #80746 - ehuss:update-cargo, r=ehuss
[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_middle::middle::privacy::AccessLevel;
10 use rustc_middle::ty::TyCtxt;
11 use rustc_span::source_map::Spanned;
12 use rustc_span::symbol::{kw, sym, Symbol};
13 use rustc_span::{self, Span};
14
15 use std::mem;
16
17 use crate::clean::{self, 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 // Also, is there some reason that this doesn't use the 'visit'
33 // framework from syntax?.
34
35 crate struct RustdocVisitor<'a, 'tcx> {
36     cx: &'a mut core::DocContext<'tcx>,
37     view_item_stack: FxHashSet<hir::HirId>,
38     inlining: bool,
39     /// Are the current module and all of its parents public?
40     inside_public_path: bool,
41     exact_paths: FxHashMap<DefId, Vec<String>>,
42 }
43
44 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
45     crate fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
46         // If the root is re-exported, terminate all recursion.
47         let mut stack = FxHashSet::default();
48         stack.insert(hir::CRATE_HIR_ID);
49         RustdocVisitor {
50             cx,
51             view_item_stack: stack,
52             inlining: false,
53             inside_public_path: true,
54             exact_paths: FxHashMap::default(),
55         }
56     }
57
58     fn store_path(&mut self, did: DefId) {
59         let tcx = self.cx.tcx;
60         self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
61     }
62
63     crate fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> {
64         let mut module = self.visit_mod_contents(
65             krate.item.span,
66             &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public },
67             hir::CRATE_HIR_ID,
68             &krate.item.module,
69             None,
70         );
71         // Attach the crate's exported macros to the top-level module:
72         module.macros.extend(krate.exported_macros.iter().map(|def| (def, None)));
73         module.is_crate = true;
74
75         self.cx.renderinfo.get_mut().exact_paths = self.exact_paths;
76
77         module
78     }
79
80     fn visit_mod_contents(
81         &mut self,
82         span: Span,
83         vis: &'tcx hir::Visibility<'_>,
84         id: hir::HirId,
85         m: &'tcx hir::Mod<'tcx>,
86         name: Option<Symbol>,
87     ) -> Module<'tcx> {
88         let mut om = Module::new(name);
89         om.where_outer = span;
90         om.where_inner = m.inner;
91         om.id = id;
92         // Keep track of if there were any private modules in the path.
93         let orig_inside_public_path = self.inside_public_path;
94         self.inside_public_path &= vis.node.is_pub();
95         for i in m.item_ids {
96             let item = self.cx.tcx.hir().expect_item(i.id);
97             self.visit_item(item, None, &mut om);
98         }
99         self.inside_public_path = orig_inside_public_path;
100         om
101     }
102
103     /// Tries to resolve the target of a `crate use` statement and inlines the
104     /// target if it is defined locally and would not be documented otherwise,
105     /// or when it is specifically requested with `please_inline`.
106     /// (the latter is the case when the import is marked `doc(inline)`)
107     ///
108     /// Cross-crate inlining occurs later on during crate cleaning
109     /// and follows different rules.
110     ///
111     /// Returns `true` if the target has been inlined.
112     fn maybe_inline_local(
113         &mut self,
114         id: hir::HirId,
115         res: Res,
116         renamed: Option<Symbol>,
117         glob: bool,
118         om: &mut Module<'tcx>,
119         please_inline: bool,
120     ) -> bool {
121         fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
122             while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
123                 node = id;
124                 if cx.tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
125                     return true;
126                 }
127                 if node == hir::CRATE_HIR_ID {
128                     break;
129                 }
130             }
131             false
132         }
133
134         debug!("maybe_inline_local res: {:?}", res);
135
136         let tcx = self.cx.tcx;
137         let res_did = if let Some(did) = res.opt_def_id() {
138             did
139         } else {
140             return false;
141         };
142
143         let use_attrs = tcx.hir().attrs(id);
144         // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
145         let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
146             || use_attrs.lists(sym::doc).has_word(sym::hidden);
147
148         // For cross-crate impl inlining we need to know whether items are
149         // reachable in documentation -- a previously nonreachable item can be
150         // made reachable by cross-crate inlining which we're checking here.
151         // (this is done here because we need to know this upfront).
152         if !res_did.is_local() && !is_no_inline {
153             let attrs = clean::inline::load_attrs(self.cx, res_did);
154             let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
155             if !self_is_hidden {
156                 if let Res::Def(kind, did) = res {
157                     if kind == DefKind::Mod {
158                         crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
159                     } else {
160                         // All items need to be handled here in case someone wishes to link
161                         // to them with intra-doc links
162                         self.cx
163                             .renderinfo
164                             .get_mut()
165                             .access_levels
166                             .map
167                             .insert(did, AccessLevel::Public);
168                     }
169                 }
170             }
171             return false;
172         }
173
174         let res_hir_id = match res_did.as_local() {
175             Some(n) => tcx.hir().local_def_id_to_hir_id(n),
176             None => return false,
177         };
178
179         let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
180         let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
181
182         // Only inline if requested or if the item would otherwise be stripped.
183         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
184             return false;
185         }
186
187         if !self.view_item_stack.insert(res_hir_id) {
188             return false;
189         }
190
191         let ret = match tcx.hir().get(res_hir_id) {
192             Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
193                 let prev = mem::replace(&mut self.inlining, true);
194                 for i in m.item_ids {
195                     let i = self.cx.tcx.hir().expect_item(i.id);
196                     self.visit_item(i, None, om);
197                 }
198                 self.inlining = prev;
199                 true
200             }
201             Node::Item(it) if !glob => {
202                 let prev = mem::replace(&mut self.inlining, true);
203                 self.visit_item(it, renamed, om);
204                 self.inlining = prev;
205                 true
206             }
207             Node::ForeignItem(it) if !glob => {
208                 let prev = mem::replace(&mut self.inlining, true);
209                 self.visit_foreign_item(it, renamed, om);
210                 self.inlining = prev;
211                 true
212             }
213             Node::MacroDef(def) if !glob => {
214                 om.macros.push((def, renamed));
215                 true
216             }
217             _ => false,
218         };
219         self.view_item_stack.remove(&res_hir_id);
220         ret
221     }
222
223     fn visit_item(
224         &mut self,
225         item: &'tcx hir::Item<'_>,
226         renamed: Option<Symbol>,
227         om: &mut Module<'tcx>,
228     ) {
229         debug!("visiting item {:?}", item);
230         let name = renamed.unwrap_or(item.ident.name);
231
232         if item.vis.node.is_pub() {
233             let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
234             self.store_path(def_id.to_def_id());
235         }
236
237         match item.kind {
238             hir::ItemKind::ForeignMod { items, .. } => {
239                 for item in items {
240                     let item = self.cx.tcx.hir().foreign_item(item.id);
241                     self.visit_foreign_item(item, None, om);
242                 }
243             }
244             // If we're inlining, skip private items.
245             _ if self.inlining && !item.vis.node.is_pub() => {}
246             hir::ItemKind::GlobalAsm(..) => {}
247             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
248             hir::ItemKind::Use(ref path, kind) => {
249                 let is_glob = kind == hir::UseKind::Glob;
250
251                 // Struct and variant constructors and proc macro stubs always show up alongside
252                 // their definitions, we've already processed them so just discard these.
253                 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
254                     return;
255                 }
256
257                 // If there was a private module in the current path then don't bother inlining
258                 // anything as it will probably be stripped anyway.
259                 if item.vis.node.is_pub() && self.inside_public_path {
260                     let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
261                         Some(ref list) if item.has_name(sym::doc) => {
262                             list.iter().any(|i| i.has_name(sym::inline))
263                         }
264                         _ => false,
265                     });
266                     let ident = if is_glob { None } else { Some(name) };
267                     if self.maybe_inline_local(
268                         item.hir_id,
269                         path.res,
270                         ident,
271                         is_glob,
272                         om,
273                         please_inline,
274                     ) {
275                         return;
276                     }
277                 }
278
279                 om.imports.push(Import {
280                     name,
281                     id: item.hir_id,
282                     vis: &item.vis,
283                     attrs: &item.attrs,
284                     path,
285                     glob: is_glob,
286                     span: item.span,
287                 });
288             }
289             hir::ItemKind::Mod(ref m) => {
290                 om.mods.push(self.visit_mod_contents(
291                     item.span,
292                     &item.vis,
293                     item.hir_id,
294                     m,
295                     Some(name),
296                 ));
297             }
298             hir::ItemKind::Fn(..)
299             | hir::ItemKind::ExternCrate(..)
300             | hir::ItemKind::Enum(..)
301             | hir::ItemKind::Struct(..)
302             | hir::ItemKind::Union(..)
303             | hir::ItemKind::TyAlias(..)
304             | hir::ItemKind::OpaqueTy(..)
305             | hir::ItemKind::Static(..)
306             | hir::ItemKind::Trait(..)
307             | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)),
308             hir::ItemKind::Const(..) => {
309                 // Underscore constants do not correspond to a nameable item and
310                 // so are never useful in documentation.
311                 if name != kw::Underscore {
312                     om.items.push((item, renamed));
313                 }
314             }
315             hir::ItemKind::Impl { ref of_trait, .. } => {
316                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
317                 // them up regardless of where they're located.
318                 if !self.inlining && of_trait.is_none() {
319                     om.items.push((item, None));
320                 }
321             }
322         }
323     }
324
325     fn visit_foreign_item(
326         &mut self,
327         item: &'tcx hir::ForeignItem<'_>,
328         renamed: Option<Symbol>,
329         om: &mut Module<'tcx>,
330     ) {
331         // If inlining we only want to include public functions.
332         if !self.inlining || item.vis.node.is_pub() {
333             om.foreigns.push((item, renamed));
334         }
335     }
336 }