]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
rustdoc-json: Rename `Import.span` to `Import.source`
[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 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 mut top_level_module = self.visit_mod_contents(
75             krate.item.span,
76             &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public },
77             hir::CRATE_HIR_ID,
78             &krate.item.module,
79             None,
80         );
81         top_level_module.is_crate = true;
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 == Some(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         span: Span,
133         vis: &'tcx hir::Visibility<'_>,
134         id: hir::HirId,
135         m: &'tcx hir::Mod<'tcx>,
136         name: Option<Symbol>,
137     ) -> Module<'tcx> {
138         let mut om = Module::new(name);
139         om.where_outer = span;
140         om.where_inner = m.inner;
141         om.id = id;
142         // Keep track of if there were any private modules in the path.
143         let orig_inside_public_path = self.inside_public_path;
144         self.inside_public_path &= vis.node.is_pub();
145         for &i in m.item_ids {
146             let item = self.cx.tcx.hir().item(i);
147             self.visit_item(item, None, &mut om);
148         }
149         self.inside_public_path = orig_inside_public_path;
150         om
151     }
152
153     /// Tries to resolve the target of a `crate use` statement and inlines the
154     /// target if it is defined locally and would not be documented otherwise,
155     /// or when it is specifically requested with `please_inline`.
156     /// (the latter is the case when the import is marked `doc(inline)`)
157     ///
158     /// Cross-crate inlining occurs later on during crate cleaning
159     /// and follows different rules.
160     ///
161     /// Returns `true` if the target has been inlined.
162     fn maybe_inline_local(
163         &mut self,
164         id: hir::HirId,
165         res: Res,
166         renamed: Option<Symbol>,
167         glob: bool,
168         om: &mut Module<'tcx>,
169         please_inline: bool,
170     ) -> bool {
171         debug!("maybe_inline_local res: {:?}", res);
172
173         let tcx = self.cx.tcx;
174         let res_did = if let Some(did) = res.opt_def_id() {
175             did
176         } else {
177             return false;
178         };
179
180         let use_attrs = tcx.hir().attrs(id);
181         // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
182         let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
183             || use_attrs.lists(sym::doc).has_word(sym::hidden);
184
185         // For cross-crate impl inlining we need to know whether items are
186         // reachable in documentation -- a previously nonreachable item can be
187         // made reachable by cross-crate inlining which we're checking here.
188         // (this is done here because we need to know this upfront).
189         if !res_did.is_local() && !is_no_inline {
190             let attrs = clean::inline::load_attrs(self.cx, res_did);
191             let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
192             if !self_is_hidden {
193                 if let Res::Def(kind, did) = res {
194                     if kind == DefKind::Mod {
195                         crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
196                     } else {
197                         // All items need to be handled here in case someone wishes to link
198                         // to them with intra-doc links
199                         self.cx.cache.access_levels.map.insert(did, AccessLevel::Public);
200                     }
201                 }
202             }
203             return false;
204         }
205
206         let res_hir_id = match res_did.as_local() {
207             Some(n) => tcx.hir().local_def_id_to_hir_id(n),
208             None => return false,
209         };
210
211         let is_private = !self.cx.cache.access_levels.is_public(res_did);
212         let is_hidden = inherits_doc_hidden(self.cx.tcx, res_hir_id);
213
214         // Only inline if requested or if the item would otherwise be stripped.
215         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
216             return false;
217         }
218
219         if !self.view_item_stack.insert(res_hir_id) {
220             return false;
221         }
222
223         let ret = match tcx.hir().get(res_hir_id) {
224             Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
225                 let prev = mem::replace(&mut self.inlining, true);
226                 for &i in m.item_ids {
227                     let i = self.cx.tcx.hir().item(i);
228                     self.visit_item(i, None, om);
229                 }
230                 self.inlining = prev;
231                 true
232             }
233             Node::Item(it) if !glob => {
234                 let prev = mem::replace(&mut self.inlining, true);
235                 self.visit_item(it, renamed, om);
236                 self.inlining = prev;
237                 true
238             }
239             Node::ForeignItem(it) if !glob => {
240                 let prev = mem::replace(&mut self.inlining, true);
241                 self.visit_foreign_item(it, renamed, om);
242                 self.inlining = prev;
243                 true
244             }
245             Node::MacroDef(def) if !glob => {
246                 om.macros.push((def, renamed));
247                 true
248             }
249             _ => false,
250         };
251         self.view_item_stack.remove(&res_hir_id);
252         ret
253     }
254
255     fn visit_item(
256         &mut self,
257         item: &'tcx hir::Item<'_>,
258         renamed: Option<Symbol>,
259         om: &mut Module<'tcx>,
260     ) {
261         debug!("visiting item {:?}", item);
262         let name = renamed.unwrap_or(item.ident.name);
263
264         if item.vis.node.is_pub() {
265             self.store_path(item.def_id.to_def_id());
266         }
267
268         match item.kind {
269             hir::ItemKind::ForeignMod { items, .. } => {
270                 for item in items {
271                     let item = self.cx.tcx.hir().foreign_item(item.id);
272                     self.visit_foreign_item(item, None, om);
273                 }
274             }
275             // If we're inlining, skip private items.
276             _ if self.inlining && !item.vis.node.is_pub() => {}
277             hir::ItemKind::GlobalAsm(..) => {}
278             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
279             hir::ItemKind::Use(ref path, kind) => {
280                 let is_glob = kind == hir::UseKind::Glob;
281
282                 // Struct and variant constructors and proc macro stubs always show up alongside
283                 // their definitions, we've already processed them so just discard these.
284                 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
285                     return;
286                 }
287
288                 let attrs = self.cx.tcx.hir().attrs(item.hir_id());
289
290                 // If there was a private module in the current path then don't bother inlining
291                 // anything as it will probably be stripped anyway.
292                 if item.vis.node.is_pub() && self.inside_public_path {
293                     let please_inline = attrs.iter().any(|item| match item.meta_item_list() {
294                         Some(ref list) if item.has_name(sym::doc) => {
295                             list.iter().any(|i| i.has_name(sym::inline))
296                         }
297                         _ => false,
298                     });
299                     let ident = if is_glob { None } else { Some(name) };
300                     if self.maybe_inline_local(
301                         item.hir_id(),
302                         path.res,
303                         ident,
304                         is_glob,
305                         om,
306                         please_inline,
307                     ) {
308                         return;
309                     }
310                 }
311
312                 om.items.push((item, renamed))
313             }
314             hir::ItemKind::Mod(ref m) => {
315                 om.mods.push(self.visit_mod_contents(
316                     item.span,
317                     &item.vis,
318                     item.hir_id(),
319                     m,
320                     Some(name),
321                 ));
322             }
323             hir::ItemKind::Fn(..)
324             | hir::ItemKind::ExternCrate(..)
325             | hir::ItemKind::Enum(..)
326             | hir::ItemKind::Struct(..)
327             | hir::ItemKind::Union(..)
328             | hir::ItemKind::TyAlias(..)
329             | hir::ItemKind::OpaqueTy(..)
330             | hir::ItemKind::Static(..)
331             | hir::ItemKind::Trait(..)
332             | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)),
333             hir::ItemKind::Const(..) => {
334                 // Underscore constants do not correspond to a nameable item and
335                 // so are never useful in documentation.
336                 if name != kw::Underscore {
337                     om.items.push((item, renamed));
338                 }
339             }
340             hir::ItemKind::Impl(ref impl_) => {
341                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
342                 // them up regardless of where they're located.
343                 if !self.inlining && impl_.of_trait.is_none() {
344                     om.items.push((item, None));
345                 }
346             }
347         }
348     }
349
350     fn visit_foreign_item(
351         &mut self,
352         item: &'tcx hir::ForeignItem<'_>,
353         renamed: Option<Symbol>,
354         om: &mut Module<'tcx>,
355     ) {
356         // If inlining we only want to include public functions.
357         if !self.inlining || item.vis.node.is_pub() {
358             om.foreigns.push((item, renamed));
359         }
360     }
361 }