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