]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Fix rebase and clean up some code.
[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             /* Because of #77828 we cannot do the simpler:
88             let macro_parent_module = tcx.def_path(tcx.parent_module(def.hir_id).to_def_id());
89             // and instead have to do: */
90             let macro_parent_module = tcx.def_path({
91                 use rustc_middle::ty::DefIdTree;
92                 tcx.parent(tcx.hir().local_def_id(def.hir_id).to_def_id()).unwrap()
93             });
94             // HACK: rustdoc has no way to lookup `doctree::Module`s by their HirId. Instead,
95             // lookup the module by its name, by looking at each path segment one at a time.
96             let mut cur_mod = &mut top_level_module;
97             for path_segment in macro_parent_module.data {
98                 // Path segments may refer to a module (in which case they belong to the type
99                 // namespace), which is _necessary_ for the macro to be accessible outside it
100                 // (no "associated macros" as of yet). Else we bail with an outer `continue`.
101                 let path_segment_ty_ns = match path_segment.data {
102                     rustc_hir::definitions::DefPathData::TypeNs(symbol) => symbol,
103                     _ => continue 'exported_macros,
104                 };
105                 // Descend into the child module that matches this path segment (if any).
106                 match cur_mod.mods.iter_mut().find(|child| child.name == Some(path_segment_ty_ns)) {
107                     Some(child_mod) => cur_mod = &mut *child_mod,
108                     None => continue 'exported_macros,
109                 }
110             }
111             cur_mod.macros.push((def, None));
112         }
113         self.cx.renderinfo.get_mut().exact_paths = self.exact_paths;
114         top_level_module
115     }
116
117     fn visit_mod_contents(
118         &mut self,
119         span: Span,
120         vis: &'tcx hir::Visibility<'_>,
121         id: hir::HirId,
122         m: &'tcx hir::Mod<'tcx>,
123         name: Option<Symbol>,
124     ) -> Module<'tcx> {
125         let mut om = Module::new(name);
126         om.where_outer = span;
127         om.where_inner = m.inner;
128         om.id = id;
129         // Keep track of if there were any private modules in the path.
130         let orig_inside_public_path = self.inside_public_path;
131         self.inside_public_path &= vis.node.is_pub();
132         for i in m.item_ids {
133             let item = self.cx.tcx.hir().expect_item(i.id);
134             self.visit_item(item, None, &mut om);
135         }
136         self.inside_public_path = orig_inside_public_path;
137         om
138     }
139
140     /// Tries to resolve the target of a `crate use` statement and inlines the
141     /// target if it is defined locally and would not be documented otherwise,
142     /// or when it is specifically requested with `please_inline`.
143     /// (the latter is the case when the import is marked `doc(inline)`)
144     ///
145     /// Cross-crate inlining occurs later on during crate cleaning
146     /// and follows different rules.
147     ///
148     /// Returns `true` if the target has been inlined.
149     fn maybe_inline_local(
150         &mut self,
151         id: hir::HirId,
152         res: Res,
153         renamed: Option<Symbol>,
154         glob: bool,
155         om: &mut Module<'tcx>,
156         please_inline: bool,
157     ) -> bool {
158         fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
159             while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
160                 node = id;
161                 if cx.tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
162                     return true;
163                 }
164                 if node == hir::CRATE_HIR_ID {
165                     break;
166                 }
167             }
168             false
169         }
170
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
200                             .renderinfo
201                             .get_mut()
202                             .access_levels
203                             .map
204                             .insert(did, AccessLevel::Public);
205                     }
206                 }
207             }
208             return false;
209         }
210
211         let res_hir_id = match res_did.as_local() {
212             Some(n) => tcx.hir().local_def_id_to_hir_id(n),
213             None => return false,
214         };
215
216         let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
217         let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
218
219         // Only inline if requested or if the item would otherwise be stripped.
220         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
221             return false;
222         }
223
224         if !self.view_item_stack.insert(res_hir_id) {
225             return false;
226         }
227
228         let ret = match tcx.hir().get(res_hir_id) {
229             Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
230                 let prev = mem::replace(&mut self.inlining, true);
231                 for i in m.item_ids {
232                     let i = self.cx.tcx.hir().expect_item(i.id);
233                     self.visit_item(i, None, om);
234                 }
235                 self.inlining = prev;
236                 true
237             }
238             Node::Item(it) if !glob => {
239                 let prev = mem::replace(&mut self.inlining, true);
240                 self.visit_item(it, renamed, om);
241                 self.inlining = prev;
242                 true
243             }
244             Node::ForeignItem(it) if !glob => {
245                 let prev = mem::replace(&mut self.inlining, true);
246                 self.visit_foreign_item(it, renamed, om);
247                 self.inlining = prev;
248                 true
249             }
250             Node::MacroDef(def) if !glob => {
251                 om.macros.push((def, renamed));
252                 true
253             }
254             _ => false,
255         };
256         self.view_item_stack.remove(&res_hir_id);
257         ret
258     }
259
260     fn visit_item(
261         &mut self,
262         item: &'tcx hir::Item<'_>,
263         renamed: Option<Symbol>,
264         om: &mut Module<'tcx>,
265     ) {
266         debug!("visiting item {:?}", item);
267         let name = renamed.unwrap_or(item.ident.name);
268
269         if item.vis.node.is_pub() {
270             let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
271             self.store_path(def_id.to_def_id());
272         }
273
274         match item.kind {
275             hir::ItemKind::ForeignMod { items, .. } => {
276                 for item in items {
277                     let item = self.cx.tcx.hir().foreign_item(item.id);
278                     self.visit_foreign_item(item, None, om);
279                 }
280             }
281             // If we're inlining, skip private items.
282             _ if self.inlining && !item.vis.node.is_pub() => {}
283             hir::ItemKind::GlobalAsm(..) => {}
284             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
285             hir::ItemKind::Use(ref path, kind) => {
286                 let is_glob = kind == hir::UseKind::Glob;
287
288                 // Struct and variant constructors and proc macro stubs always show up alongside
289                 // their definitions, we've already processed them so just discard these.
290                 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
291                     return;
292                 }
293
294                 // If there was a private module in the current path then don't bother inlining
295                 // anything as it will probably be stripped anyway.
296                 if item.vis.node.is_pub() && self.inside_public_path {
297                     let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
298                         Some(ref list) if item.has_name(sym::doc) => {
299                             list.iter().any(|i| i.has_name(sym::inline))
300                         }
301                         _ => false,
302                     });
303                     let ident = if is_glob { None } else { Some(name) };
304                     if self.maybe_inline_local(
305                         item.hir_id,
306                         path.res,
307                         ident,
308                         is_glob,
309                         om,
310                         please_inline,
311                     ) {
312                         return;
313                     }
314                 }
315
316                 om.imports.push(Import {
317                     name,
318                     id: item.hir_id,
319                     vis: &item.vis,
320                     attrs: &item.attrs,
321                     path,
322                     glob: is_glob,
323                     span: item.span,
324                 });
325             }
326             hir::ItemKind::Mod(ref m) => {
327                 om.mods.push(self.visit_mod_contents(
328                     item.span,
329                     &item.vis,
330                     item.hir_id,
331                     m,
332                     Some(name),
333                 ));
334             }
335             hir::ItemKind::Fn(..)
336             | hir::ItemKind::ExternCrate(..)
337             | hir::ItemKind::Enum(..)
338             | hir::ItemKind::Struct(..)
339             | hir::ItemKind::Union(..)
340             | hir::ItemKind::TyAlias(..)
341             | hir::ItemKind::OpaqueTy(..)
342             | hir::ItemKind::Static(..)
343             | hir::ItemKind::Trait(..)
344             | hir::ItemKind::TraitAlias(..) => om.items.push((item, renamed)),
345             hir::ItemKind::Const(..) => {
346                 // Underscore constants do not correspond to a nameable item and
347                 // so are never useful in documentation.
348                 if name != kw::Underscore {
349                     om.items.push((item, renamed));
350                 }
351             }
352             hir::ItemKind::Impl { ref of_trait, .. } => {
353                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
354                 // them up regardless of where they're located.
355                 if !self.inlining && of_trait.is_none() {
356                     om.items.push((item, None));
357                 }
358             }
359         }
360     }
361
362     fn visit_foreign_item(
363         &mut self,
364         item: &'tcx hir::ForeignItem<'_>,
365         renamed: Option<Symbol>,
366         om: &mut Module<'tcx>,
367     ) {
368         // If inlining we only want to include public functions.
369         if !self.inlining || item.vis.node.is_pub() {
370             om.foreigns.push((item, renamed));
371         }
372     }
373 }