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