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