]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
fc7e8d72d6997f045176258bb3bd8ca6b6405d71
[rust.git] / src / librustdoc / visit_ast.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Rust AST Visitor. Extracts useful information and massages it into a form
12 //! usable for clean
13
14 use std::mem;
15
16 use syntax::ast;
17 use syntax::attr;
18 use syntax::ext::base::MacroKind;
19 use syntax::source_map::Spanned;
20 use syntax_pos::{self, Span};
21
22 use rustc::hir::Node;
23 use rustc::hir::def::Def;
24 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
25 use rustc::middle::privacy::AccessLevel;
26 use rustc::util::nodemap::{FxHashSet, FxHashMap};
27
28 use rustc::hir;
29
30 use core;
31 use clean::{self, AttributesExt, NestedAttributesExt, def_id_to_path};
32 use doctree::*;
33
34 // looks to me like the first two of these are actually
35 // output parameters, maybe only mutated once; perhaps
36 // better simply to have the visit method return a tuple
37 // containing them?
38
39 // also, is there some reason that this doesn't use the 'visit'
40 // framework from syntax?
41
42 pub struct RustdocVisitor<'a, 'tcx: 'a, 'rcx: 'a, 'cstore: 'rcx> {
43     pub module: Module,
44     pub attrs: hir::HirVec<ast::Attribute>,
45     pub cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>,
46     view_item_stack: FxHashSet<ast::NodeId>,
47     inlining: bool,
48     /// Is the current module and all of its parents public?
49     inside_public_path: bool,
50     exact_paths: Option<FxHashMap<DefId, Vec<String>>>,
51 }
52
53 impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> {
54     pub fn new(
55         cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>
56     ) -> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> {
57         // If the root is re-exported, terminate all recursion.
58         let mut stack = FxHashSet::default();
59         stack.insert(ast::CRATE_NODE_ID);
60         RustdocVisitor {
61             module: Module::new(None),
62             attrs: hir::HirVec::new(),
63             cx,
64             view_item_stack: stack,
65             inlining: false,
66             inside_public_path: true,
67             exact_paths: Some(FxHashMap::default()),
68         }
69     }
70
71     fn store_path(&mut self, did: DefId) {
72         // We can't use the entry api, as that keeps the mutable borrow of self active
73         // when we try to use cx
74         let exact_paths = self.exact_paths.as_mut().unwrap();
75         if exact_paths.get(&did).is_none() {
76             let path = def_id_to_path(self.cx, did, self.cx.crate_name.clone());
77             exact_paths.insert(did, path);
78         }
79     }
80
81     fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
82         self.cx.tcx.hir().opt_local_def_id(id)
83             .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
84     }
85
86     fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
87         self.cx.tcx.hir().opt_local_def_id(id)
88             .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
89     }
90
91     pub fn visit(&mut self, krate: &hir::Crate) {
92         self.attrs = krate.attrs.clone();
93
94         self.module = self.visit_mod_contents(krate.span,
95                                               krate.attrs.clone(),
96                                               Spanned { span: syntax_pos::DUMMY_SP,
97                                                         node: hir::VisibilityKind::Public },
98                                               ast::CRATE_NODE_ID,
99                                               &krate.module,
100                                               None);
101         // attach the crate's exported macros to the top-level module:
102         let macro_exports: Vec<_> =
103             krate.exported_macros.iter().map(|def| self.visit_local_macro(def, None)).collect();
104         self.module.macros.extend(macro_exports);
105         self.module.is_crate = true;
106
107         self.cx.renderinfo.borrow_mut().exact_paths = self.exact_paths.take().unwrap();
108     }
109
110     pub fn visit_variant_data(&mut self, item: &hir::Item,
111                               name: ast::Name, sd: &hir::VariantData,
112                               generics: &hir::Generics) -> Struct {
113         debug!("Visiting struct");
114         let struct_type = struct_type_from_def(&*sd);
115         Struct {
116             id: item.id,
117             struct_type,
118             name,
119             vis: item.vis.clone(),
120             stab: self.stability(item.id),
121             depr: self.deprecation(item.id),
122             attrs: item.attrs.clone(),
123             generics: generics.clone(),
124             fields: sd.fields().iter().cloned().collect(),
125             whence: item.span
126         }
127     }
128
129     pub fn visit_union_data(&mut self, item: &hir::Item,
130                             name: ast::Name, sd: &hir::VariantData,
131                             generics: &hir::Generics) -> Union {
132         debug!("Visiting union");
133         let struct_type = struct_type_from_def(&*sd);
134         Union {
135             id: item.id,
136             struct_type,
137             name,
138             vis: item.vis.clone(),
139             stab: self.stability(item.id),
140             depr: self.deprecation(item.id),
141             attrs: item.attrs.clone(),
142             generics: generics.clone(),
143             fields: sd.fields().iter().cloned().collect(),
144             whence: item.span
145         }
146     }
147
148     pub fn visit_enum_def(&mut self, it: &hir::Item,
149                           name: ast::Name, def: &hir::EnumDef,
150                           params: &hir::Generics) -> Enum {
151         debug!("Visiting enum");
152         Enum {
153             name,
154             variants: def.variants.iter().map(|v| Variant {
155                 name: v.node.name,
156                 attrs: v.node.attrs.clone(),
157                 stab: self.stability(v.node.data.id()),
158                 depr: self.deprecation(v.node.data.id()),
159                 def: v.node.data.clone(),
160                 whence: v.span,
161             }).collect(),
162             vis: it.vis.clone(),
163             stab: self.stability(it.id),
164             depr: self.deprecation(it.id),
165             generics: params.clone(),
166             attrs: it.attrs.clone(),
167             id: it.id,
168             whence: it.span,
169         }
170     }
171
172     pub fn visit_fn(&mut self, om: &mut Module, item: &hir::Item,
173                     name: ast::Name, fd: &hir::FnDecl,
174                     header: hir::FnHeader,
175                     gen: &hir::Generics,
176                     body: hir::BodyId) {
177         debug!("Visiting fn");
178         let macro_kind = item.attrs.iter().filter_map(|a| {
179             if a.check_name("proc_macro") {
180                 Some(MacroKind::Bang)
181             } else if a.check_name("proc_macro_derive") {
182                 Some(MacroKind::Derive)
183             } else if a.check_name("proc_macro_attribute") {
184                 Some(MacroKind::Attr)
185             } else {
186                 None
187             }
188         }).next();
189         match macro_kind {
190             Some(kind) => {
191                 let name = if kind == MacroKind::Derive {
192                     item.attrs.lists("proc_macro_derive")
193                               .filter_map(|mi| mi.name())
194                               .next()
195                               .expect("proc-macro derives require a name")
196                 } else {
197                     name
198                 };
199
200                 let mut helpers = Vec::new();
201                 for mi in item.attrs.lists("proc_macro_derive") {
202                     if !mi.check_name("attributes") {
203                         continue;
204                     }
205
206                     if let Some(list) = mi.meta_item_list() {
207                         for inner_mi in list {
208                             if let Some(name) = inner_mi.name() {
209                                 helpers.push(name);
210                             }
211                         }
212                     }
213                 }
214
215                 om.proc_macros.push(ProcMacro {
216                     name,
217                     id: item.id,
218                     kind,
219                     helpers,
220                     attrs: item.attrs.clone(),
221                     whence: item.span,
222                     stab: self.stability(item.id),
223                     depr: self.deprecation(item.id),
224                 });
225             }
226             None => {
227                 om.fns.push(Function {
228                     id: item.id,
229                     vis: item.vis.clone(),
230                     stab: self.stability(item.id),
231                     depr: self.deprecation(item.id),
232                     attrs: item.attrs.clone(),
233                     decl: fd.clone(),
234                     name,
235                     whence: item.span,
236                     generics: gen.clone(),
237                     header,
238                     body,
239                 });
240             }
241         }
242     }
243
244     pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
245                               vis: hir::Visibility, id: ast::NodeId,
246                               m: &hir::Mod,
247                               name: Option<ast::Name>) -> Module {
248         let mut om = Module::new(name);
249         om.where_outer = span;
250         om.where_inner = m.inner;
251         om.attrs = attrs;
252         om.vis = vis.clone();
253         om.stab = self.stability(id);
254         om.depr = self.deprecation(id);
255         om.id = id;
256         // Keep track of if there were any private modules in the path.
257         let orig_inside_public_path = self.inside_public_path;
258         self.inside_public_path &= vis.node.is_pub();
259         for i in &m.item_ids {
260             let item = self.cx.tcx.hir().expect_item(i.id);
261             self.visit_item(item, None, &mut om);
262         }
263         self.inside_public_path = orig_inside_public_path;
264         om
265     }
266
267     /// Tries to resolve the target of a `pub use` statement and inlines the
268     /// target if it is defined locally and would not be documented otherwise,
269     /// or when it is specifically requested with `please_inline`.
270     /// (the latter is the case when the import is marked `doc(inline)`)
271     ///
272     /// Cross-crate inlining occurs later on during crate cleaning
273     /// and follows different rules.
274     ///
275     /// Returns true if the target has been inlined.
276     fn maybe_inline_local(&mut self,
277                           id: ast::NodeId,
278                           def: Def,
279                           renamed: Option<ast::Name>,
280                           glob: bool,
281                           om: &mut Module,
282                           please_inline: bool) -> bool {
283
284         fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
285             while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
286                 node = id;
287                 if cx.tcx.hir().attrs(node).lists("doc").has_word("hidden") {
288                     return true;
289                 }
290                 if node == ast::CRATE_NODE_ID {
291                     break;
292                 }
293             }
294             false
295         }
296
297         debug!("maybe_inline_local def: {:?}", def);
298
299         let tcx = self.cx.tcx;
300         if def == Def::Err {
301             return false;
302         }
303         let def_did = def.def_id();
304
305         let use_attrs = tcx.hir().attrs(id);
306         // Don't inline doc(hidden) imports so they can be stripped at a later stage.
307         let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
308                            use_attrs.lists("doc").has_word("hidden");
309
310         // For cross-crate impl inlining we need to know whether items are
311         // reachable in documentation - a previously nonreachable item can be
312         // made reachable by cross-crate inlining which we're checking here.
313         // (this is done here because we need to know this upfront)
314         if !def_did.is_local() && !is_no_inline {
315             let attrs = clean::inline::load_attrs(self.cx, def_did);
316             let self_is_hidden = attrs.lists("doc").has_word("hidden");
317             match def {
318                 Def::Trait(did) |
319                 Def::Struct(did) |
320                 Def::Union(did) |
321                 Def::Enum(did) |
322                 Def::ForeignTy(did) |
323                 Def::TyAlias(did) if !self_is_hidden => {
324                     self.cx.renderinfo
325                         .borrow_mut()
326                         .access_levels.map
327                         .insert(did, AccessLevel::Public);
328                 },
329                 Def::Mod(did) => if !self_is_hidden {
330                     ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
331                 },
332                 _ => {},
333             }
334
335             return false
336         }
337
338         let def_node_id = match tcx.hir().as_local_node_id(def_did) {
339             Some(n) => n, None => return false
340         };
341
342         let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(def_did);
343         let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
344
345         // Only inline if requested or if the item would otherwise be stripped
346         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
347             return false
348         }
349
350         if !self.view_item_stack.insert(def_node_id) { return false }
351
352         let ret = match tcx.hir().get(def_node_id) {
353             Node::Item(&hir::Item { node: hir::ItemKind::Mod(ref m), .. }) if glob => {
354                 let prev = mem::replace(&mut self.inlining, true);
355                 for i in &m.item_ids {
356                     let i = self.cx.tcx.hir().expect_item(i.id);
357                     self.visit_item(i, None, om);
358                 }
359                 self.inlining = prev;
360                 true
361             }
362             Node::Item(it) if !glob => {
363                 let prev = mem::replace(&mut self.inlining, true);
364                 self.visit_item(it, renamed, om);
365                 self.inlining = prev;
366                 true
367             }
368             Node::ForeignItem(it) if !glob => {
369                 // generate a fresh `extern {}` block if we want to inline a foreign item.
370                 om.foreigns.push(hir::ForeignMod {
371                     abi: tcx.hir().get_foreign_abi(it.id),
372                     items: vec![hir::ForeignItem {
373                         name: renamed.unwrap_or(it.name),
374                         .. it.clone()
375                     }].into(),
376                 });
377                 true
378             }
379             Node::MacroDef(def) if !glob => {
380                 om.macros.push(self.visit_local_macro(def, renamed));
381                 true
382             }
383             _ => false,
384         };
385         self.view_item_stack.remove(&def_node_id);
386         ret
387     }
388
389     pub fn visit_item(&mut self, item: &hir::Item,
390                       renamed: Option<ast::Name>, om: &mut Module) {
391         debug!("Visiting item {:?}", item);
392         let name = renamed.unwrap_or(item.name);
393
394         if item.vis.node.is_pub() {
395             let def_id = self.cx.tcx.hir().local_def_id(item.id);
396             self.store_path(def_id);
397         }
398
399         match item.node {
400             hir::ItemKind::ForeignMod(ref fm) => {
401                 // If inlining we only want to include public functions.
402                 om.foreigns.push(if self.inlining {
403                     hir::ForeignMod {
404                         abi: fm.abi,
405                         items: fm.items.iter().filter(|i| i.vis.node.is_pub()).cloned().collect(),
406                     }
407                 } else {
408                     fm.clone()
409                 });
410             }
411             // If we're inlining, skip private items.
412             _ if self.inlining && !item.vis.node.is_pub() => {}
413             hir::ItemKind::GlobalAsm(..) => {}
414             hir::ItemKind::ExternCrate(orig_name) => {
415                 let def_id = self.cx.tcx.hir().local_def_id(item.id);
416                 om.extern_crates.push(ExternCrate {
417                     cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
418                                 .unwrap_or(LOCAL_CRATE),
419                     name,
420                     path: orig_name.map(|x|x.to_string()),
421                     vis: item.vis.clone(),
422                     attrs: item.attrs.clone(),
423                     whence: item.span,
424                 })
425             }
426             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
427             hir::ItemKind::Use(ref path, kind) => {
428                 let is_glob = kind == hir::UseKind::Glob;
429
430                 // struct and variant constructors always show up alongside their definitions, we've
431                 // already processed them so just discard these.
432                 match path.def {
433                     Def::StructCtor(..) | Def::VariantCtor(..) | Def::SelfCtor(..) => return,
434                     _ => {}
435                 }
436
437                 // If there was a private module in the current path then don't bother inlining
438                 // anything as it will probably be stripped anyway.
439                 if item.vis.node.is_pub() && self.inside_public_path {
440                     let please_inline = item.attrs.iter().any(|item| {
441                         match item.meta_item_list() {
442                             Some(ref list) if item.check_name("doc") => {
443                                 list.iter().any(|i| i.check_name("inline"))
444                             }
445                             _ => false,
446                         }
447                     });
448                     let name = if is_glob { None } else { Some(name) };
449                     if self.maybe_inline_local(item.id,
450                                                path.def,
451                                                name,
452                                                is_glob,
453                                                om,
454                                                please_inline) {
455                         return;
456                     }
457                 }
458
459                 om.imports.push(Import {
460                     name,
461                     id: item.id,
462                     vis: item.vis.clone(),
463                     attrs: item.attrs.clone(),
464                     path: (**path).clone(),
465                     glob: is_glob,
466                     whence: item.span,
467                 });
468             }
469             hir::ItemKind::Mod(ref m) => {
470                 om.mods.push(self.visit_mod_contents(item.span,
471                                                      item.attrs.clone(),
472                                                      item.vis.clone(),
473                                                      item.id,
474                                                      m,
475                                                      Some(name)));
476             },
477             hir::ItemKind::Enum(ref ed, ref gen) =>
478                 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
479             hir::ItemKind::Struct(ref sd, ref gen) =>
480                 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
481             hir::ItemKind::Union(ref sd, ref gen) =>
482                 om.unions.push(self.visit_union_data(item, name, sd, gen)),
483             hir::ItemKind::Fn(ref fd, header, ref gen, body) =>
484                 self.visit_fn(om, item, name, &**fd, header, gen, body),
485             hir::ItemKind::Ty(ref ty, ref gen) => {
486                 let t = Typedef {
487                     ty: ty.clone(),
488                     gen: gen.clone(),
489                     name,
490                     id: item.id,
491                     attrs: item.attrs.clone(),
492                     whence: item.span,
493                     vis: item.vis.clone(),
494                     stab: self.stability(item.id),
495                     depr: self.deprecation(item.id),
496                 };
497                 om.typedefs.push(t);
498             },
499             hir::ItemKind::Existential(ref exist_ty) => {
500                 let t = Existential {
501                     exist_ty: exist_ty.clone(),
502                     name,
503                     id: item.id,
504                     attrs: item.attrs.clone(),
505                     whence: item.span,
506                     vis: item.vis.clone(),
507                     stab: self.stability(item.id),
508                     depr: self.deprecation(item.id),
509                 };
510                 om.existentials.push(t);
511             },
512             hir::ItemKind::Static(ref ty, ref mut_, ref exp) => {
513                 let s = Static {
514                     type_: ty.clone(),
515                     mutability: mut_.clone(),
516                     expr: exp.clone(),
517                     id: item.id,
518                     name,
519                     attrs: item.attrs.clone(),
520                     whence: item.span,
521                     vis: item.vis.clone(),
522                     stab: self.stability(item.id),
523                     depr: self.deprecation(item.id),
524                 };
525                 om.statics.push(s);
526             },
527             hir::ItemKind::Const(ref ty, ref exp) => {
528                 let s = Constant {
529                     type_: ty.clone(),
530                     expr: exp.clone(),
531                     id: item.id,
532                     name,
533                     attrs: item.attrs.clone(),
534                     whence: item.span,
535                     vis: item.vis.clone(),
536                     stab: self.stability(item.id),
537                     depr: self.deprecation(item.id),
538                 };
539                 om.constants.push(s);
540             },
541             hir::ItemKind::Trait(is_auto, unsafety, ref gen, ref b, ref item_ids) => {
542                 let items = item_ids.iter()
543                                     .map(|ti| self.cx.tcx.hir().trait_item(ti.id).clone())
544                                     .collect();
545                 let t = Trait {
546                     is_auto,
547                     unsafety,
548                     name,
549                     items,
550                     generics: gen.clone(),
551                     bounds: b.iter().cloned().collect(),
552                     id: item.id,
553                     attrs: item.attrs.clone(),
554                     whence: item.span,
555                     vis: item.vis.clone(),
556                     stab: self.stability(item.id),
557                     depr: self.deprecation(item.id),
558                 };
559                 om.traits.push(t);
560             },
561             hir::ItemKind::TraitAlias(..) => {
562                 unimplemented!("trait objects are not yet implemented")
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 }