]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Auto merge of #58341 - alexreg:cosmetic-2-doc-comments, r=steveklabnik
[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::hir::{self, Node};
5 use rustc::hir::def::Def;
6 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
7 use rustc::middle::privacy::AccessLevel;
8 use rustc::util::nodemap::{FxHashSet, FxHashMap};
9 use syntax::ast;
10 use syntax::attr;
11 use syntax::ext::base::MacroKind;
12 use syntax::source_map::Spanned;
13 use syntax_pos::{self, Span};
14
15 use std::mem;
16
17 use core;
18 use clean::{self, AttributesExt, NestedAttributesExt, def_id_to_path};
19 use doctree::*;
20
21 // Looks to me like the first two of these are actually
22 // output parameters, maybe only mutated once; perhaps
23 // better simply to have the visit method return a tuple
24 // containing them?
25
26 // Also, is there some reason that this doesn't use the 'visit'
27 // framework from syntax?.
28
29 pub struct RustdocVisitor<'a, 'tcx: 'a, 'rcx: 'a> {
30     pub module: Module,
31     pub attrs: hir::HirVec<ast::Attribute>,
32     pub cx: &'a core::DocContext<'a, 'tcx, 'rcx>,
33     view_item_stack: FxHashSet<ast::NodeId>,
34     inlining: bool,
35     /// Are the current module and all of its parents public?
36     inside_public_path: bool,
37     exact_paths: Option<FxHashMap<DefId, Vec<String>>>,
38 }
39
40 impl<'a, 'tcx, 'rcx> RustdocVisitor<'a, 'tcx, 'rcx> {
41     pub fn new(
42         cx: &'a core::DocContext<'a, 'tcx, 'rcx>
43     ) -> RustdocVisitor<'a, 'tcx, 'rcx> {
44         // If the root is re-exported, terminate all recursion.
45         let mut stack = FxHashSet::default();
46         stack.insert(ast::CRATE_NODE_ID);
47         RustdocVisitor {
48             module: Module::new(None),
49             attrs: hir::HirVec::new(),
50             cx,
51             view_item_stack: stack,
52             inlining: false,
53             inside_public_path: true,
54             exact_paths: Some(FxHashMap::default()),
55         }
56     }
57
58     fn store_path(&mut self, did: DefId) {
59         // We can't use the entry API, as that keeps the mutable borrow of `self` active
60         // when we try to use `cx`.
61         let exact_paths = self.exact_paths.as_mut().unwrap();
62         if exact_paths.get(&did).is_none() {
63             let path = def_id_to_path(self.cx, did, self.cx.crate_name.clone());
64             exact_paths.insert(did, path);
65         }
66     }
67
68     fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
69         self.cx.tcx.hir().opt_local_def_id(id)
70             .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
71     }
72
73     fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
74         self.cx.tcx.hir().opt_local_def_id(id)
75             .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
76     }
77
78     pub fn visit(&mut self, krate: &hir::Crate) {
79         self.attrs = krate.attrs.clone();
80
81         self.module = self.visit_mod_contents(krate.span,
82                                               krate.attrs.clone(),
83                                               Spanned { span: syntax_pos::DUMMY_SP,
84                                                         node: hir::VisibilityKind::Public },
85                                               ast::CRATE_NODE_ID,
86                                               &krate.module,
87                                               None);
88         // Attach the crate's exported macros to the top-level module:
89         let macro_exports: Vec<_> =
90             krate.exported_macros.iter().map(|def| self.visit_local_macro(def, None)).collect();
91         self.module.macros.extend(macro_exports);
92         self.module.is_crate = true;
93
94         self.cx.renderinfo.borrow_mut().exact_paths = self.exact_paths.take().unwrap();
95     }
96
97     pub fn visit_variant_data(&mut self, item: &hir::Item,
98                               name: ast::Name, sd: &hir::VariantData,
99                               generics: &hir::Generics) -> Struct {
100         debug!("Visiting struct");
101         let struct_type = struct_type_from_def(&*sd);
102         Struct {
103             id: item.id,
104             struct_type,
105             name,
106             vis: item.vis.clone(),
107             stab: self.stability(item.id),
108             depr: self.deprecation(item.id),
109             attrs: item.attrs.clone(),
110             generics: generics.clone(),
111             fields: sd.fields().iter().cloned().collect(),
112             whence: item.span
113         }
114     }
115
116     pub fn visit_union_data(&mut self, item: &hir::Item,
117                             name: ast::Name, sd: &hir::VariantData,
118                             generics: &hir::Generics) -> Union {
119         debug!("Visiting union");
120         let struct_type = struct_type_from_def(&*sd);
121         Union {
122             id: item.id,
123             struct_type,
124             name,
125             vis: item.vis.clone(),
126             stab: self.stability(item.id),
127             depr: self.deprecation(item.id),
128             attrs: item.attrs.clone(),
129             generics: generics.clone(),
130             fields: sd.fields().iter().cloned().collect(),
131             whence: item.span
132         }
133     }
134
135     pub fn visit_enum_def(&mut self, it: &hir::Item,
136                           name: ast::Name, def: &hir::EnumDef,
137                           params: &hir::Generics) -> Enum {
138         debug!("Visiting enum");
139         Enum {
140             name,
141             variants: def.variants.iter().map(|v| Variant {
142                 name: v.node.ident.name,
143                 attrs: v.node.attrs.clone(),
144                 stab: self.stability(v.node.data.id()),
145                 depr: self.deprecation(v.node.data.id()),
146                 def: v.node.data.clone(),
147                 whence: v.span,
148             }).collect(),
149             vis: it.vis.clone(),
150             stab: self.stability(it.id),
151             depr: self.deprecation(it.id),
152             generics: params.clone(),
153             attrs: it.attrs.clone(),
154             id: it.id,
155             whence: it.span,
156         }
157     }
158
159     pub fn visit_fn(&mut self, om: &mut Module, item: &hir::Item,
160                     name: ast::Name, fd: &hir::FnDecl,
161                     header: hir::FnHeader,
162                     gen: &hir::Generics,
163                     body: hir::BodyId) {
164         debug!("Visiting fn");
165         let macro_kind = item.attrs.iter().filter_map(|a| {
166             if a.check_name("proc_macro") {
167                 Some(MacroKind::Bang)
168             } else if a.check_name("proc_macro_derive") {
169                 Some(MacroKind::Derive)
170             } else if a.check_name("proc_macro_attribute") {
171                 Some(MacroKind::Attr)
172             } else {
173                 None
174             }
175         }).next();
176         match macro_kind {
177             Some(kind) => {
178                 let name = if kind == MacroKind::Derive {
179                     item.attrs.lists("proc_macro_derive")
180                               .filter_map(|mi| mi.name())
181                               .next()
182                               .expect("proc-macro derives require a name")
183                 } else {
184                     name
185                 };
186
187                 let mut helpers = Vec::new();
188                 for mi in item.attrs.lists("proc_macro_derive") {
189                     if !mi.check_name("attributes") {
190                         continue;
191                     }
192
193                     if let Some(list) = mi.meta_item_list() {
194                         for inner_mi in list {
195                             if let Some(name) = inner_mi.name() {
196                                 helpers.push(name);
197                             }
198                         }
199                     }
200                 }
201
202                 om.proc_macros.push(ProcMacro {
203                     name,
204                     id: item.id,
205                     kind,
206                     helpers,
207                     attrs: item.attrs.clone(),
208                     whence: item.span,
209                     stab: self.stability(item.id),
210                     depr: self.deprecation(item.id),
211                 });
212             }
213             None => {
214                 om.fns.push(Function {
215                     id: item.id,
216                     vis: item.vis.clone(),
217                     stab: self.stability(item.id),
218                     depr: self.deprecation(item.id),
219                     attrs: item.attrs.clone(),
220                     decl: fd.clone(),
221                     name,
222                     whence: item.span,
223                     generics: gen.clone(),
224                     header,
225                     body,
226                 });
227             }
228         }
229     }
230
231     pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
232                               vis: hir::Visibility, id: ast::NodeId,
233                               m: &hir::Mod,
234                               name: Option<ast::Name>) -> Module {
235         let mut om = Module::new(name);
236         om.where_outer = span;
237         om.where_inner = m.inner;
238         om.attrs = attrs;
239         om.vis = vis.clone();
240         om.stab = self.stability(id);
241         om.depr = self.deprecation(id);
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(&mut self,
264                           id: ast::NodeId,
265                           def: Def,
266                           renamed: Option<ast::Ident>,
267                           glob: bool,
268                           om: &mut Module,
269                           please_inline: bool) -> bool {
270
271         fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
272             while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
273                 node = id;
274                 if cx.tcx.hir().attrs(node).lists("doc").has_word("hidden") {
275                     return true;
276                 }
277                 if node == ast::CRATE_NODE_ID {
278                     break;
279                 }
280             }
281             false
282         }
283
284         debug!("maybe_inline_local def: {:?}", def);
285
286         let tcx = self.cx.tcx;
287         let def_did = if let Some(did) = def.opt_def_id() {
288             did
289         } else {
290             return false;
291         };
292
293         let use_attrs = tcx.hir().attrs(id);
294         // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
295         let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
296                            use_attrs.lists("doc").has_word("hidden");
297
298         // For cross-crate impl inlining we need to know whether items are
299         // reachable in documentation -- a previously nonreachable item can be
300         // made reachable by cross-crate inlining which we're checking here.
301         // (this is done here because we need to know this upfront).
302         if !def_did.is_local() && !is_no_inline {
303             let attrs = clean::inline::load_attrs(self.cx, def_did);
304             let self_is_hidden = attrs.lists("doc").has_word("hidden");
305             match def {
306                 Def::Trait(did) |
307                 Def::Struct(did) |
308                 Def::Union(did) |
309                 Def::Enum(did) |
310                 Def::ForeignTy(did) |
311                 Def::TyAlias(did) if !self_is_hidden => {
312                     self.cx.renderinfo
313                         .borrow_mut()
314                         .access_levels.map
315                         .insert(did, AccessLevel::Public);
316                 },
317                 Def::Mod(did) => if !self_is_hidden {
318                     ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
319                 },
320                 _ => {},
321             }
322
323             return false
324         }
325
326         let def_node_id = match tcx.hir().as_local_node_id(def_did) {
327             Some(n) => n, None => return false
328         };
329
330         let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(def_did);
331         let is_hidden = inherits_doc_hidden(self.cx, def_node_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(def_node_id) { return false }
339
340         let ret = match tcx.hir().get(def_node_id) {
341             Node::Item(&hir::Item { node: hir::ItemKind::Mod(ref m), .. }) if glob => {
342                 let prev = mem::replace(&mut self.inlining, true);
343                 for i in &m.item_ids {
344                     let i = self.cx.tcx.hir().expect_item(i.id);
345                     self.visit_item(i, None, om);
346                 }
347                 self.inlining = prev;
348                 true
349             }
350             Node::Item(it) if !glob => {
351                 let prev = mem::replace(&mut self.inlining, true);
352                 self.visit_item(it, renamed, om);
353                 self.inlining = prev;
354                 true
355             }
356             Node::ForeignItem(it) if !glob => {
357                 // Generate a fresh `extern {}` block if we want to inline a foreign item.
358                 om.foreigns.push(hir::ForeignMod {
359                     abi: tcx.hir().get_foreign_abi(it.id),
360                     items: vec![hir::ForeignItem {
361                         ident: renamed.unwrap_or(it.ident),
362                         .. it.clone()
363                     }].into(),
364                 });
365                 true
366             }
367             Node::MacroDef(def) if !glob => {
368                 om.macros.push(self.visit_local_macro(def, renamed.map(|i| i.name)));
369                 true
370             }
371             _ => false,
372         };
373         self.view_item_stack.remove(&def_node_id);
374         ret
375     }
376
377     pub fn visit_item(&mut self, item: &hir::Item,
378                       renamed: Option<ast::Ident>, om: &mut Module) {
379         debug!("Visiting item {:?}", item);
380         let ident = renamed.unwrap_or(item.ident);
381
382         if item.vis.node.is_pub() {
383             let def_id = self.cx.tcx.hir().local_def_id(item.id);
384             self.store_path(def_id);
385         }
386
387         match item.node {
388             hir::ItemKind::ForeignMod(ref fm) => {
389                 // If inlining we only want to include public functions.
390                 om.foreigns.push(if self.inlining {
391                     hir::ForeignMod {
392                         abi: fm.abi,
393                         items: fm.items.iter().filter(|i| i.vis.node.is_pub()).cloned().collect(),
394                     }
395                 } else {
396                     fm.clone()
397                 });
398             }
399             // If we're inlining, skip private items.
400             _ if self.inlining && !item.vis.node.is_pub() => {}
401             hir::ItemKind::GlobalAsm(..) => {}
402             hir::ItemKind::ExternCrate(orig_name) => {
403                 let def_id = self.cx.tcx.hir().local_def_id(item.id);
404                 om.extern_crates.push(ExternCrate {
405                     cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
406                                 .unwrap_or(LOCAL_CRATE),
407                     name: ident.name,
408                     path: orig_name.map(|x|x.to_string()),
409                     vis: item.vis.clone(),
410                     attrs: item.attrs.clone(),
411                     whence: item.span,
412                 })
413             }
414             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
415             hir::ItemKind::Use(ref path, kind) => {
416                 let is_glob = kind == hir::UseKind::Glob;
417
418                 // Struct and variant constructors and proc macro stubs always show up alongside
419                 // their definitions, we've already processed them so just discard these.
420                 match path.def {
421                     Def::StructCtor(..) | Def::VariantCtor(..) | Def::SelfCtor(..) |
422                     Def::Macro(_, MacroKind::ProcMacroStub) => return,
423                     _ => {}
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| {
430                         match item.meta_item_list() {
431                             Some(ref list) if item.check_name("doc") => {
432                                 list.iter().any(|i| i.check_name("inline"))
433                             }
434                             _ => false,
435                         }
436                     });
437                     let ident = if is_glob { None } else { Some(ident) };
438                     if self.maybe_inline_local(item.id,
439                                                path.def,
440                                                ident,
441                                                is_glob,
442                                                om,
443                                                please_inline) {
444                         return;
445                     }
446                 }
447
448                 om.imports.push(Import {
449                     name: ident.name,
450                     id: item.id,
451                     vis: item.vis.clone(),
452                     attrs: item.attrs.clone(),
453                     path: (**path).clone(),
454                     glob: is_glob,
455                     whence: item.span,
456                 });
457             }
458             hir::ItemKind::Mod(ref m) => {
459                 om.mods.push(self.visit_mod_contents(item.span,
460                                                      item.attrs.clone(),
461                                                      item.vis.clone(),
462                                                      item.id,
463                                                      m,
464                                                      Some(ident.name)));
465             },
466             hir::ItemKind::Enum(ref ed, ref gen) =>
467                 om.enums.push(self.visit_enum_def(item, ident.name, ed, gen)),
468             hir::ItemKind::Struct(ref sd, ref gen) =>
469                 om.structs.push(self.visit_variant_data(item, ident.name, sd, gen)),
470             hir::ItemKind::Union(ref sd, ref gen) =>
471                 om.unions.push(self.visit_union_data(item, ident.name, sd, gen)),
472             hir::ItemKind::Fn(ref fd, header, ref gen, body) =>
473                 self.visit_fn(om, item, ident.name, &**fd, header, gen, body),
474             hir::ItemKind::Ty(ref ty, ref gen) => {
475                 let t = Typedef {
476                     ty: ty.clone(),
477                     gen: gen.clone(),
478                     name: ident.name,
479                     id: item.id,
480                     attrs: item.attrs.clone(),
481                     whence: item.span,
482                     vis: item.vis.clone(),
483                     stab: self.stability(item.id),
484                     depr: self.deprecation(item.id),
485                 };
486                 om.typedefs.push(t);
487             },
488             hir::ItemKind::Existential(ref exist_ty) => {
489                 let t = Existential {
490                     exist_ty: exist_ty.clone(),
491                     name: ident.name,
492                     id: item.id,
493                     attrs: item.attrs.clone(),
494                     whence: item.span,
495                     vis: item.vis.clone(),
496                     stab: self.stability(item.id),
497                     depr: self.deprecation(item.id),
498                 };
499                 om.existentials.push(t);
500             },
501             hir::ItemKind::Static(ref ty, ref mut_, ref exp) => {
502                 let s = Static {
503                     type_: ty.clone(),
504                     mutability: mut_.clone(),
505                     expr: exp.clone(),
506                     id: item.id,
507                     name: ident.name,
508                     attrs: item.attrs.clone(),
509                     whence: item.span,
510                     vis: item.vis.clone(),
511                     stab: self.stability(item.id),
512                     depr: self.deprecation(item.id),
513                 };
514                 om.statics.push(s);
515             },
516             hir::ItemKind::Const(ref ty, ref exp) => {
517                 let s = Constant {
518                     type_: ty.clone(),
519                     expr: exp.clone(),
520                     id: item.id,
521                     name: ident.name,
522                     attrs: item.attrs.clone(),
523                     whence: item.span,
524                     vis: item.vis.clone(),
525                     stab: self.stability(item.id),
526                     depr: self.deprecation(item.id),
527                 };
528                 om.constants.push(s);
529             },
530             hir::ItemKind::Trait(is_auto, unsafety, ref gen, ref b, ref item_ids) => {
531                 let items = item_ids.iter()
532                                     .map(|ti| self.cx.tcx.hir().trait_item(ti.id).clone())
533                                     .collect();
534                 let t = Trait {
535                     is_auto,
536                     unsafety,
537                     name: ident.name,
538                     items,
539                     generics: gen.clone(),
540                     bounds: b.iter().cloned().collect(),
541                     id: item.id,
542                     attrs: item.attrs.clone(),
543                     whence: item.span,
544                     vis: item.vis.clone(),
545                     stab: self.stability(item.id),
546                     depr: self.deprecation(item.id),
547                 };
548                 om.traits.push(t);
549             },
550             hir::ItemKind::TraitAlias(ref gen, ref b) => {
551                 let t = TraitAlias {
552                     name: ident.name,
553                     generics: gen.clone(),
554                     bounds: b.iter().cloned().collect(),
555                     id: item.id,
556                     attrs: item.attrs.clone(),
557                     whence: item.span,
558                     vis: item.vis.clone(),
559                     stab: self.stability(item.id),
560                     depr: self.deprecation(item.id),
561                 };
562                 om.trait_aliases.push(t);
563             },
564
565             hir::ItemKind::Impl(unsafety,
566                           polarity,
567                           defaultness,
568                           ref gen,
569                           ref tr,
570                           ref ty,
571                           ref item_ids) => {
572                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
573                 // them up regardless of where they're located.
574                 if !self.inlining && tr.is_none() {
575                     let items = item_ids.iter()
576                                         .map(|ii| self.cx.tcx.hir().impl_item(ii.id).clone())
577                                         .collect();
578                     let i = Impl {
579                         unsafety,
580                         polarity,
581                         defaultness,
582                         generics: gen.clone(),
583                         trait_: tr.clone(),
584                         for_: ty.clone(),
585                         items,
586                         attrs: item.attrs.clone(),
587                         id: item.id,
588                         whence: item.span,
589                         vis: item.vis.clone(),
590                         stab: self.stability(item.id),
591                         depr: self.deprecation(item.id),
592                     };
593                     om.impls.push(i);
594                 }
595             },
596         }
597     }
598
599     // Convert each `exported_macro` into a doc item.
600     fn visit_local_macro(
601         &self,
602         def: &hir::MacroDef,
603         renamed: Option<ast::Name>
604     ) -> Macro {
605         debug!("visit_local_macro: {}", def.name);
606         let tts = def.body.trees().collect::<Vec<_>>();
607         // Extract the spans of all matchers. They represent the "interface" of the macro.
608         let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
609
610         Macro {
611             def_id: self.cx.tcx.hir().local_def_id(def.id),
612             attrs: def.attrs.clone(),
613             name: renamed.unwrap_or(def.name),
614             whence: def.span,
615             matchers,
616             stab: self.stability(def.id),
617             depr: self.deprecation(def.id),
618             imported_from: None,
619         }
620     }
621 }