]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Auto merge of #86799 - tlyu:stdio-locked, 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_middle::middle::privacy::AccessLevel;
10 use rustc_middle::ty::TyCtxt;
11 use rustc_span;
12 use rustc_span::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, 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, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> {
75         let span = krate.item.inner;
76         let mut top_level_module = self.visit_mod_contents(
77             &Spanned { span, node: hir::VisibilityKind::Public },
78             hir::CRATE_HIR_ID,
79             &krate.item,
80             self.cx.tcx.crate_name(LOCAL_CRATE),
81         );
82         // Attach the crate's exported macros to the top-level module.
83         // In the case of macros 2.0 (`pub macro`), and for built-in `derive`s or attributes as
84         // well (_e.g._, `Copy`), these are wrongly bundled in there too, so we need to fix that by
85         // moving them back to their correct locations.
86         'exported_macros: for def in krate.exported_macros {
87             // The `def` of a macro in `exported_macros` should correspond to either:
88             //  - a `#[macro_export] macro_rules!` macro,
89             //  - a built-in `derive` (or attribute) macro such as the ones in `::core`,
90             //  - a `pub macro`.
91             // Only the last two need to be fixed, thus:
92             if def.ast.macro_rules {
93                 top_level_module.macros.push((def, None));
94                 continue 'exported_macros;
95             }
96             let tcx = self.cx.tcx;
97             // Note: this is not the same as `.parent_module()`. Indeed, the latter looks
98             // for the closest module _ancestor_, which is not necessarily a direct parent
99             // (since a direct parent isn't necessarily a module, c.f. #77828).
100             let macro_parent_def_id = {
101                 use rustc_middle::ty::DefIdTree;
102                 tcx.parent(def.def_id.to_def_id()).unwrap()
103             };
104             let macro_parent_path = tcx.def_path(macro_parent_def_id);
105             // HACK: rustdoc has no way to lookup `doctree::Module`s by their HirId. Instead,
106             // lookup the module by its name, by looking at each path segment one at a time.
107             let mut cur_mod = &mut top_level_module;
108             for path_segment in macro_parent_path.data {
109                 // Path segments may refer to a module (in which case they belong to the type
110                 // namespace), which is _necessary_ for the macro to be accessible outside it
111                 // (no "associated macros" as of yet). Else we bail with an outer `continue`.
112                 let path_segment_ty_ns = match path_segment.data {
113                     rustc_hir::definitions::DefPathData::TypeNs(symbol) => symbol,
114                     _ => continue 'exported_macros,
115                 };
116                 // Descend into the child module that matches this path segment (if any).
117                 match cur_mod.mods.iter_mut().find(|child| child.name == path_segment_ty_ns) {
118                     Some(child_mod) => cur_mod = &mut *child_mod,
119                     None => continue 'exported_macros,
120                 }
121             }
122             let cur_mod_def_id = tcx.hir().local_def_id(cur_mod.id).to_def_id();
123             assert_eq!(cur_mod_def_id, macro_parent_def_id);
124             cur_mod.macros.push((def, None));
125         }
126         self.cx.cache.exact_paths = self.exact_paths;
127         top_level_module
128     }
129
130     fn visit_mod_contents(
131         &mut self,
132         vis: &hir::Visibility<'_>,
133         id: hir::HirId,
134         m: &'tcx hir::Mod<'tcx>,
135         name: Symbol,
136     ) -> Module<'tcx> {
137         let mut om = Module::new(name, id, m.inner);
138         // Keep track of if there were any private modules in the path.
139         let orig_inside_public_path = self.inside_public_path;
140         self.inside_public_path &= vis.node.is_pub();
141         for &i in m.item_ids {
142             let item = self.cx.tcx.hir().item(i);
143             self.visit_item(item, None, &mut om);
144         }
145         self.inside_public_path = orig_inside_public_path;
146         om
147     }
148
149     /// Tries to resolve the target of a `pub use` statement and inlines the
150     /// target if it is defined locally and would not be documented otherwise,
151     /// or when it is specifically requested with `please_inline`.
152     /// (the latter is the case when the import is marked `doc(inline)`)
153     ///
154     /// Cross-crate inlining occurs later on during crate cleaning
155     /// and follows different rules.
156     ///
157     /// Returns `true` if the target has been inlined.
158     fn maybe_inline_local(
159         &mut self,
160         id: hir::HirId,
161         res: Res,
162         renamed: Option<Symbol>,
163         glob: bool,
164         om: &mut Module<'tcx>,
165         please_inline: bool,
166     ) -> bool {
167         debug!("maybe_inline_local res: {:?}", res);
168
169         let tcx = self.cx.tcx;
170         let res_did = if let Some(did) = res.opt_def_id() {
171             did
172         } else {
173             return false;
174         };
175
176         let use_attrs = tcx.hir().attrs(id);
177         // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
178         let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
179             || use_attrs.lists(sym::doc).has_word(sym::hidden);
180
181         // For cross-crate impl inlining we need to know whether items are
182         // reachable in documentation -- a previously unreachable item can be
183         // made reachable by cross-crate inlining which we're checking here.
184         // (this is done here because we need to know this upfront).
185         if !res_did.is_local() && !is_no_inline {
186             let attrs = clean::inline::load_attrs(self.cx, res_did);
187             let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
188             if !self_is_hidden {
189                 if let Res::Def(kind, did) = res {
190                     if kind == DefKind::Mod {
191                         crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
192                     } else {
193                         // All items need to be handled here in case someone wishes to link
194                         // to them with intra-doc links
195                         self.cx.cache.access_levels.map.insert(did.into(), AccessLevel::Public);
196                     }
197                 }
198             }
199             return false;
200         }
201
202         let res_hir_id = match res_did.as_local() {
203             Some(n) => tcx.hir().local_def_id_to_hir_id(n),
204             None => return false,
205         };
206
207         let is_private = !self.cx.cache.access_levels.is_public(res_did.into());
208         let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id);
209
210         // Only inline if requested or if the item would otherwise be stripped.
211         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
212             return false;
213         }
214
215         if !self.view_item_stack.insert(res_hir_id) {
216             return false;
217         }
218
219         let ret = match tcx.hir().get(res_hir_id) {
220             Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
221                 let prev = mem::replace(&mut self.inlining, true);
222                 for &i in m.item_ids {
223                     let i = self.cx.tcx.hir().item(i);
224                     self.visit_item(i, None, om);
225                 }
226                 self.inlining = prev;
227                 true
228             }
229             Node::Item(it) if !glob => {
230                 let prev = mem::replace(&mut self.inlining, true);
231                 self.visit_item(it, renamed, om);
232                 self.inlining = prev;
233                 true
234             }
235             Node::ForeignItem(it) if !glob => {
236                 let prev = mem::replace(&mut self.inlining, true);
237                 self.visit_foreign_item(it, renamed, om);
238                 self.inlining = prev;
239                 true
240             }
241             Node::MacroDef(def) if !glob => {
242                 om.macros.push((def, renamed));
243                 true
244             }
245             _ => false,
246         };
247         self.view_item_stack.remove(&res_hir_id);
248         ret
249     }
250
251     fn visit_item(
252         &mut self,
253         item: &'tcx hir::Item<'_>,
254         renamed: Option<Symbol>,
255         om: &mut Module<'tcx>,
256     ) {
257         debug!("visiting item {:?}", item);
258         let name = renamed.unwrap_or(item.ident.name);
259
260         if item.vis.node.is_pub() {
261             self.store_path(item.def_id.to_def_id());
262         }
263
264         match item.kind {
265             hir::ItemKind::ForeignMod { items, .. } => {
266                 for item in items {
267                     let item = self.cx.tcx.hir().foreign_item(item.id);
268                     self.visit_foreign_item(item, None, om);
269                 }
270             }
271             // If we're inlining, skip private items.
272             _ if self.inlining && !item.vis.node.is_pub() => {}
273             hir::ItemKind::GlobalAsm(..) => {}
274             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
275             hir::ItemKind::Use(ref path, kind) => {
276                 let is_glob = kind == hir::UseKind::Glob;
277
278                 // Struct and variant constructors and proc macro stubs always show up alongside
279                 // their definitions, we've already processed them so just discard these.
280                 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
281                     return;
282                 }
283
284                 let attrs = self.cx.tcx.hir().attrs(item.hir_id());
285
286                 // If there was a private module in the current path then don't bother inlining
287                 // anything as it will probably be stripped anyway.
288                 if item.vis.node.is_pub() && self.inside_public_path {
289                     let please_inline = attrs.iter().any(|item| match item.meta_item_list() {
290                         Some(ref list) if item.has_name(sym::doc) => {
291                             list.iter().any(|i| i.has_name(sym::inline))
292                         }
293                         _ => false,
294                     });
295                     let ident = if is_glob { None } else { Some(name) };
296                     if self.maybe_inline_local(
297                         item.hir_id(),
298                         path.res,
299                         ident,
300                         is_glob,
301                         om,
302                         please_inline,
303                     ) {
304                         return;
305                     }
306                 }
307
308                 om.items.push((item, renamed))
309             }
310             hir::ItemKind::Mod(ref m) => {
311                 om.mods.push(self.visit_mod_contents(&item.vis, item.hir_id(), m, name));
312             }
313             hir::ItemKind::Fn(..)
314             | hir::ItemKind::ExternCrate(..)
315             | hir::ItemKind::Enum(..)
316             | hir::ItemKind::Struct(..)
317             | hir::ItemKind::Union(..)
318             | hir::ItemKind::TyAlias(..)
319             | hir::ItemKind::OpaqueTy(..)
320             | hir::ItemKind::Static(..)
321             | hir::ItemKind::Trait(..)
322             | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)),
323             hir::ItemKind::Const(..) => {
324                 // Underscore constants do not correspond to a nameable item and
325                 // so are never useful in documentation.
326                 if name != kw::Underscore {
327                     om.items.push((item, renamed));
328                 }
329             }
330             hir::ItemKind::Impl(ref impl_) => {
331                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
332                 // them up regardless of where they're located.
333                 if !self.inlining && impl_.of_trait.is_none() {
334                     om.items.push((item, None));
335                 }
336             }
337         }
338     }
339
340     fn visit_foreign_item(
341         &mut self,
342         item: &'tcx hir::ForeignItem<'_>,
343         renamed: Option<Symbol>,
344         om: &mut Module<'tcx>,
345     ) {
346         // If inlining we only want to include public functions.
347         if !self.inlining || item.vis.node.is_pub() {
348             om.foreigns.push((item, renamed));
349         }
350     }
351 }