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