]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Merge commit '645ef505da378b6f810b1567806d1bcc2856395f' into clippyup
[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_ast as ast;
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_hir as hir;
7 use rustc_hir::def::{DefKind, Res};
8 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
9 use rustc_hir::Node;
10 use rustc_middle::middle::privacy::AccessLevel;
11 use rustc_middle::ty::TyCtxt;
12 use rustc_span::hygiene::MacroKind;
13 use rustc_span::source_map::Spanned;
14 use rustc_span::symbol::{kw, sym, Ident, Symbol};
15 use rustc_span::{self, Span};
16
17 use std::mem;
18
19 use crate::clean::{self, AttributesExt, NestedAttributesExt};
20 use crate::core;
21 use crate::doctree::*;
22
23 // FIXME: Should this be replaced with tcx.def_path_str?
24 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> {
25     let crate_name = tcx.crate_name(did.krate).to_string();
26     let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| {
27         // extern blocks have an empty name
28         let s = elem.data.to_string();
29         if !s.is_empty() { Some(s) } else { None }
30     });
31     std::iter::once(crate_name).chain(relative).collect()
32 }
33
34 // Also, is there some reason that this doesn't use the 'visit'
35 // framework from syntax?.
36
37 pub struct RustdocVisitor<'a, 'tcx> {
38     cx: &'a mut core::DocContext<'tcx>,
39     view_item_stack: FxHashSet<hir::HirId>,
40     inlining: bool,
41     /// Are the current module and all of its parents public?
42     inside_public_path: bool,
43     exact_paths: FxHashMap<DefId, Vec<String>>,
44 }
45
46 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
47     pub fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
48         // If the root is re-exported, terminate all recursion.
49         let mut stack = FxHashSet::default();
50         stack.insert(hir::CRATE_HIR_ID);
51         RustdocVisitor {
52             cx,
53             view_item_stack: stack,
54             inlining: false,
55             inside_public_path: true,
56             exact_paths: FxHashMap::default(),
57         }
58     }
59
60     fn store_path(&mut self, did: DefId) {
61         let tcx = self.cx.tcx;
62         self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
63     }
64
65     pub fn visit(mut self, krate: &'tcx hir::Crate<'_>) -> Module<'tcx> {
66         let mut module = self.visit_mod_contents(
67             krate.item.span,
68             krate.item.attrs,
69             &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public },
70             hir::CRATE_HIR_ID,
71             &krate.item.module,
72             None,
73         );
74         // Attach the crate's exported macros to the top-level module:
75         module
76             .macros
77             .extend(krate.exported_macros.iter().map(|def| self.visit_local_macro(def, None)));
78         module.is_crate = true;
79
80         self.cx.renderinfo.get_mut().exact_paths = self.exact_paths;
81
82         module
83     }
84
85     fn visit_variant_data(
86         &mut self,
87         item: &'tcx hir::Item<'_>,
88         name: Symbol,
89         sd: &'tcx hir::VariantData<'_>,
90         generics: &'tcx hir::Generics<'_>,
91     ) -> Struct<'tcx> {
92         debug!("visiting struct");
93         let struct_type = struct_type_from_def(&*sd);
94         Struct {
95             id: item.hir_id,
96             struct_type,
97             name,
98             vis: &item.vis,
99             attrs: &item.attrs,
100             generics,
101             fields: sd.fields(),
102             span: item.span,
103         }
104     }
105
106     fn visit_union_data(
107         &mut self,
108         item: &'tcx hir::Item<'_>,
109         name: Symbol,
110         sd: &'tcx hir::VariantData<'_>,
111         generics: &'tcx hir::Generics<'_>,
112     ) -> Union<'tcx> {
113         debug!("visiting union");
114         let struct_type = struct_type_from_def(&*sd);
115         Union {
116             id: item.hir_id,
117             struct_type,
118             name,
119             vis: &item.vis,
120             attrs: &item.attrs,
121             generics,
122             fields: sd.fields(),
123             span: item.span,
124         }
125     }
126
127     fn visit_enum_def(
128         &mut self,
129         it: &'tcx hir::Item<'_>,
130         name: Symbol,
131         def: &'tcx hir::EnumDef<'_>,
132         generics: &'tcx hir::Generics<'_>,
133     ) -> Enum<'tcx> {
134         debug!("visiting enum");
135         Enum {
136             name,
137             variants: def
138                 .variants
139                 .iter()
140                 .map(|v| Variant {
141                     name: v.ident.name,
142                     id: v.id,
143                     attrs: &v.attrs,
144                     def: &v.data,
145                     span: v.span,
146                 })
147                 .collect(),
148             vis: &it.vis,
149             generics,
150             attrs: &it.attrs,
151             id: it.hir_id,
152             span: it.span,
153         }
154     }
155
156     fn visit_fn(
157         &mut self,
158         om: &mut Module<'tcx>,
159         item: &'tcx hir::Item<'_>,
160         name: Symbol,
161         decl: &'tcx hir::FnDecl<'_>,
162         header: hir::FnHeader,
163         generics: &'tcx hir::Generics<'_>,
164         body: hir::BodyId,
165     ) {
166         debug!("visiting fn");
167         let macro_kind = item.attrs.iter().find_map(|a| {
168             if a.has_name(sym::proc_macro) {
169                 Some(MacroKind::Bang)
170             } else if a.has_name(sym::proc_macro_derive) {
171                 Some(MacroKind::Derive)
172             } else if a.has_name(sym::proc_macro_attribute) {
173                 Some(MacroKind::Attr)
174             } else {
175                 None
176             }
177         });
178         match macro_kind {
179             Some(kind) => {
180                 let name = if kind == MacroKind::Derive {
181                     item.attrs
182                         .lists(sym::proc_macro_derive)
183                         .find_map(|mi| mi.ident())
184                         .expect("proc-macro derives require a name")
185                         .name
186                 } else {
187                     name
188                 };
189
190                 let mut helpers = Vec::new();
191                 for mi in item.attrs.lists(sym::proc_macro_derive) {
192                     if !mi.has_name(sym::attributes) {
193                         continue;
194                     }
195
196                     if let Some(list) = mi.meta_item_list() {
197                         for inner_mi in list {
198                             if let Some(ident) = inner_mi.ident() {
199                                 helpers.push(ident.name);
200                             }
201                         }
202                     }
203                 }
204
205                 om.proc_macros.push(ProcMacro {
206                     name,
207                     id: item.hir_id,
208                     kind,
209                     helpers,
210                     attrs: &item.attrs,
211                     span: item.span,
212                 });
213             }
214             None => {
215                 om.fns.push(Function {
216                     id: item.hir_id,
217                     vis: &item.vis,
218                     attrs: &item.attrs,
219                     decl,
220                     name,
221                     span: item.span,
222                     generics,
223                     header,
224                     body,
225                 });
226             }
227         }
228     }
229
230     fn visit_mod_contents(
231         &mut self,
232         span: Span,
233         attrs: &'tcx [ast::Attribute],
234         vis: &'tcx hir::Visibility<'_>,
235         id: hir::HirId,
236         m: &'tcx hir::Mod<'tcx>,
237         name: Option<Symbol>,
238     ) -> Module<'tcx> {
239         let mut om = Module::new(name, attrs, vis);
240         om.where_outer = span;
241         om.where_inner = m.inner;
242         om.id = id;
243         // Keep track of if there were any private modules in the path.
244         let orig_inside_public_path = self.inside_public_path;
245         self.inside_public_path &= vis.node.is_pub();
246         for i in m.item_ids {
247             let item = self.cx.tcx.hir().expect_item(i.id);
248             self.visit_item(item, None, &mut om);
249         }
250         self.inside_public_path = orig_inside_public_path;
251         om
252     }
253
254     /// Tries to resolve the target of a `pub use` statement and inlines the
255     /// target if it is defined locally and would not be documented otherwise,
256     /// or when it is specifically requested with `please_inline`.
257     /// (the latter is the case when the import is marked `doc(inline)`)
258     ///
259     /// Cross-crate inlining occurs later on during crate cleaning
260     /// and follows different rules.
261     ///
262     /// Returns `true` if the target has been inlined.
263     fn maybe_inline_local(
264         &mut self,
265         id: hir::HirId,
266         res: Res,
267         renamed: Option<Ident>,
268         glob: bool,
269         om: &mut Module<'tcx>,
270         please_inline: bool,
271     ) -> bool {
272         fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
273             while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
274                 node = id;
275                 if cx.tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
276                     return true;
277                 }
278                 if node == hir::CRATE_HIR_ID {
279                     break;
280                 }
281             }
282             false
283         }
284
285         debug!("maybe_inline_local res: {:?}", res);
286
287         let tcx = self.cx.tcx;
288         let res_did = if let Some(did) = res.opt_def_id() {
289             did
290         } else {
291             return false;
292         };
293
294         let use_attrs = tcx.hir().attrs(id);
295         // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
296         let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
297             || use_attrs.lists(sym::doc).has_word(sym::hidden);
298
299         // For cross-crate impl inlining we need to know whether items are
300         // reachable in documentation -- a previously nonreachable item can be
301         // made reachable by cross-crate inlining which we're checking here.
302         // (this is done here because we need to know this upfront).
303         if !res_did.is_local() && !is_no_inline {
304             let attrs = clean::inline::load_attrs(self.cx, res_did);
305             let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
306             if !self_is_hidden {
307                 if let Res::Def(kind, did) = res {
308                     if kind == DefKind::Mod {
309                         crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
310                     } else {
311                         // All items need to be handled here in case someone wishes to link
312                         // to them with intra-doc links
313                         self.cx
314                             .renderinfo
315                             .get_mut()
316                             .access_levels
317                             .map
318                             .insert(did, AccessLevel::Public);
319                     }
320                 }
321             }
322             return false;
323         }
324
325         let res_hir_id = match res_did.as_local() {
326             Some(n) => tcx.hir().local_def_id_to_hir_id(n),
327             None => return false,
328         };
329
330         let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
331         let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
332
333         // Only inline if requested or if the item would otherwise be stripped.
334         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
335             return false;
336         }
337
338         if !self.view_item_stack.insert(res_hir_id) {
339             return false;
340         }
341
342         let ret = match tcx.hir().get(res_hir_id) {
343             Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
344                 let prev = mem::replace(&mut self.inlining, true);
345                 for i in m.item_ids {
346                     let i = self.cx.tcx.hir().expect_item(i.id);
347                     self.visit_item(i, None, om);
348                 }
349                 self.inlining = prev;
350                 true
351             }
352             Node::Item(it) if !glob => {
353                 let prev = mem::replace(&mut self.inlining, true);
354                 self.visit_item(it, renamed, om);
355                 self.inlining = prev;
356                 true
357             }
358             Node::ForeignItem(it) if !glob => {
359                 let prev = mem::replace(&mut self.inlining, true);
360                 self.visit_foreign_item(it, renamed, om);
361                 self.inlining = prev;
362                 true
363             }
364             Node::MacroDef(def) if !glob => {
365                 om.macros.push(self.visit_local_macro(def, renamed.map(|i| i.name)));
366                 true
367             }
368             _ => false,
369         };
370         self.view_item_stack.remove(&res_hir_id);
371         ret
372     }
373
374     fn visit_item(
375         &mut self,
376         item: &'tcx hir::Item<'_>,
377         renamed: Option<Ident>,
378         om: &mut Module<'tcx>,
379     ) {
380         debug!("visiting item {:?}", item);
381         let ident = renamed.unwrap_or(item.ident);
382
383         if item.vis.node.is_pub() {
384             let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
385             self.store_path(def_id.to_def_id());
386         }
387
388         match item.kind {
389             hir::ItemKind::ForeignMod(ref fm) => {
390                 for item in fm.items {
391                     self.visit_foreign_item(item, None, om);
392                 }
393             }
394             // If we're inlining, skip private items.
395             _ if self.inlining && !item.vis.node.is_pub() => {}
396             hir::ItemKind::GlobalAsm(..) => {}
397             hir::ItemKind::ExternCrate(orig_name) => {
398                 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
399                 om.extern_crates.push(ExternCrate {
400                     cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE),
401                     name: ident.name,
402                     hir_id: item.hir_id,
403                     path: orig_name.map(|x| x.to_string()),
404                     vis: &item.vis,
405                     attrs: &item.attrs,
406                     span: item.span,
407                 })
408             }
409             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
410             hir::ItemKind::Use(ref path, kind) => {
411                 let is_glob = kind == hir::UseKind::Glob;
412
413                 // Struct and variant constructors and proc macro stubs always show up alongside
414                 // their definitions, we've already processed them so just discard these.
415                 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
416                     return;
417                 }
418
419                 // If there was a private module in the current path then don't bother inlining
420                 // anything as it will probably be stripped anyway.
421                 if item.vis.node.is_pub() && self.inside_public_path {
422                     let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
423                         Some(ref list) if item.has_name(sym::doc) => {
424                             list.iter().any(|i| i.has_name(sym::inline))
425                         }
426                         _ => false,
427                     });
428                     let ident = if is_glob { None } else { Some(ident) };
429                     if self.maybe_inline_local(
430                         item.hir_id,
431                         path.res,
432                         ident,
433                         is_glob,
434                         om,
435                         please_inline,
436                     ) {
437                         return;
438                     }
439                 }
440
441                 om.imports.push(Import {
442                     name: ident.name,
443                     id: item.hir_id,
444                     vis: &item.vis,
445                     attrs: &item.attrs,
446                     path,
447                     glob: is_glob,
448                     span: item.span,
449                 });
450             }
451             hir::ItemKind::Mod(ref m) => {
452                 om.mods.push(self.visit_mod_contents(
453                     item.span,
454                     &item.attrs,
455                     &item.vis,
456                     item.hir_id,
457                     m,
458                     Some(ident.name),
459                 ));
460             }
461             hir::ItemKind::Enum(ref ed, ref gen) => {
462                 om.enums.push(self.visit_enum_def(item, ident.name, ed, gen))
463             }
464             hir::ItemKind::Struct(ref sd, ref gen) => {
465                 om.structs.push(self.visit_variant_data(item, ident.name, sd, gen))
466             }
467             hir::ItemKind::Union(ref sd, ref gen) => {
468                 om.unions.push(self.visit_union_data(item, ident.name, sd, gen))
469             }
470             hir::ItemKind::Fn(ref sig, ref gen, body) => {
471                 self.visit_fn(om, item, ident.name, &sig.decl, sig.header, gen, body)
472             }
473             hir::ItemKind::TyAlias(ty, ref gen) => {
474                 let t = Typedef {
475                     ty,
476                     gen,
477                     name: ident.name,
478                     id: item.hir_id,
479                     attrs: &item.attrs,
480                     span: item.span,
481                     vis: &item.vis,
482                 };
483                 om.typedefs.push(t);
484             }
485             hir::ItemKind::OpaqueTy(ref opaque_ty) => {
486                 let t = OpaqueTy {
487                     opaque_ty,
488                     name: ident.name,
489                     id: item.hir_id,
490                     attrs: &item.attrs,
491                     span: item.span,
492                     vis: &item.vis,
493                 };
494                 om.opaque_tys.push(t);
495             }
496             hir::ItemKind::Static(type_, mutability, expr) => {
497                 let s = Static {
498                     type_,
499                     mutability,
500                     expr,
501                     id: item.hir_id,
502                     name: ident.name,
503                     attrs: &item.attrs,
504                     span: item.span,
505                     vis: &item.vis,
506                 };
507                 om.statics.push(s);
508             }
509             hir::ItemKind::Const(type_, expr) => {
510                 // Underscore constants do not correspond to a nameable item and
511                 // so are never useful in documentation.
512                 if ident.name != kw::Underscore {
513                     let s = Constant {
514                         type_,
515                         expr,
516                         id: item.hir_id,
517                         name: ident.name,
518                         attrs: &item.attrs,
519                         span: item.span,
520                         vis: &item.vis,
521                     };
522                     om.constants.push(s);
523                 }
524             }
525             hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
526                 let items = item_ids.iter().map(|ti| self.cx.tcx.hir().trait_item(ti.id)).collect();
527                 let t = Trait {
528                     is_auto,
529                     unsafety,
530                     name: ident.name,
531                     items,
532                     generics,
533                     bounds,
534                     id: item.hir_id,
535                     attrs: &item.attrs,
536                     span: item.span,
537                     vis: &item.vis,
538                 };
539                 om.traits.push(t);
540             }
541             hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
542                 let t = TraitAlias {
543                     name: ident.name,
544                     generics,
545                     bounds,
546                     id: item.hir_id,
547                     attrs: &item.attrs,
548                     span: item.span,
549                     vis: &item.vis,
550                 };
551                 om.trait_aliases.push(t);
552             }
553
554             hir::ItemKind::Impl {
555                 unsafety,
556                 polarity,
557                 defaultness,
558                 constness,
559                 defaultness_span: _,
560                 ref generics,
561                 ref of_trait,
562                 self_ty,
563                 ref items,
564             } => {
565                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
566                 // them up regardless of where they're located.
567                 if !self.inlining && of_trait.is_none() {
568                     let items =
569                         items.iter().map(|item| self.cx.tcx.hir().impl_item(item.id)).collect();
570                     let i = Impl {
571                         unsafety,
572                         polarity,
573                         defaultness,
574                         constness,
575                         generics,
576                         trait_: of_trait,
577                         for_: self_ty,
578                         items,
579                         attrs: &item.attrs,
580                         id: item.hir_id,
581                         span: item.span,
582                         vis: &item.vis,
583                     };
584                     om.impls.push(i);
585                 }
586             }
587         }
588     }
589
590     fn visit_foreign_item(
591         &mut self,
592         item: &'tcx hir::ForeignItem<'_>,
593         renamed: Option<Ident>,
594         om: &mut Module<'tcx>,
595     ) {
596         // If inlining we only want to include public functions.
597         if self.inlining && !item.vis.node.is_pub() {
598             return;
599         }
600
601         om.foreigns.push(ForeignItem {
602             id: item.hir_id,
603             name: renamed.unwrap_or(item.ident).name,
604             kind: &item.kind,
605             vis: &item.vis,
606             attrs: &item.attrs,
607             span: item.span,
608         });
609     }
610
611     // Convert each `exported_macro` into a doc item.
612     fn visit_local_macro(
613         &self,
614         def: &'tcx hir::MacroDef<'_>,
615         renamed: Option<Symbol>,
616     ) -> Macro<'tcx> {
617         debug!("visit_local_macro: {}", def.ident);
618         let tts = def.ast.body.inner_tokens().trees().collect::<Vec<_>>();
619         // Extract the spans of all matchers. They represent the "interface" of the macro.
620         let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
621
622         Macro {
623             hid: def.hir_id,
624             def_id: self.cx.tcx.hir().local_def_id(def.hir_id).to_def_id(),
625             attrs: &def.attrs,
626             name: renamed.unwrap_or(def.ident.name),
627             span: def.span,
628             matchers,
629             imported_from: None,
630         }
631     }
632 }