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.
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.
11 //! Rust AST Visitor. Extracts useful information and massages it into a form
19 use syntax::tokenstream::TokenStream;
22 use rustc::hir::map as hir_map;
23 use rustc::hir::def::Def;
24 use rustc::hir::def_id::LOCAL_CRATE;
25 use rustc::middle::cstore::LoadedMacro;
26 use rustc::middle::privacy::AccessLevel;
27 use rustc::util::nodemap::FxHashSet;
32 use clean::{self, AttributesExt, NestedAttributesExt};
35 // looks to me like the first two of these are actually
36 // output parameters, maybe only mutated once; perhaps
37 // better simply to have the visit method return a tuple
40 // also, is there some reason that this doesn't use the 'visit'
41 // framework from syntax?
43 pub struct RustdocVisitor<'a, 'tcx: 'a> {
45 pub attrs: hir::HirVec<ast::Attribute>,
46 pub cx: &'a core::DocContext<'a, 'tcx>,
47 view_item_stack: FxHashSet<ast::NodeId>,
49 /// Is the current module and all of its parents public?
50 inside_public_path: bool,
53 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
54 pub fn new(cx: &'a core::DocContext<'a, 'tcx>) -> RustdocVisitor<'a, 'tcx> {
55 // If the root is reexported, terminate all recursion.
56 let mut stack = FxHashSet();
57 stack.insert(ast::CRATE_NODE_ID);
59 module: Module::new(None),
60 attrs: hir::HirVec::new(),
62 view_item_stack: stack,
64 inside_public_path: true,
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()
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))
78 pub fn visit(&mut self, krate: &hir::Crate) {
79 self.attrs = krate.attrs.clone();
81 self.module = self.visit_mod_contents(krate.span,
87 // attach the crate's exported macros to the top-level module:
88 let macro_exports: Vec<_> =
89 krate.exported_macros.iter().map(|def| self.visit_local_macro(def)).collect();
90 self.module.macros.extend(macro_exports);
91 self.module.is_crate = true;
94 pub fn visit_variant_data(&mut self, item: &hir::Item,
95 name: ast::Name, sd: &hir::VariantData,
96 generics: &hir::Generics) -> Struct {
97 debug!("Visiting struct");
98 let struct_type = struct_type_from_def(&*sd);
101 struct_type: struct_type,
103 vis: item.vis.clone(),
104 stab: self.stability(item.id),
105 depr: self.deprecation(item.id),
106 attrs: item.attrs.clone(),
107 generics: generics.clone(),
108 fields: sd.fields().iter().cloned().collect(),
113 pub fn visit_union_data(&mut self, item: &hir::Item,
114 name: ast::Name, sd: &hir::VariantData,
115 generics: &hir::Generics) -> Union {
116 debug!("Visiting union");
117 let struct_type = struct_type_from_def(&*sd);
120 struct_type: struct_type,
122 vis: item.vis.clone(),
123 stab: self.stability(item.id),
124 depr: self.deprecation(item.id),
125 attrs: item.attrs.clone(),
126 generics: generics.clone(),
127 fields: sd.fields().iter().cloned().collect(),
132 pub fn visit_enum_def(&mut self, it: &hir::Item,
133 name: ast::Name, def: &hir::EnumDef,
134 params: &hir::Generics) -> Enum {
135 debug!("Visiting enum");
138 variants: def.variants.iter().map(|v| Variant {
140 attrs: v.node.attrs.clone(),
141 stab: self.stability(v.node.data.id()),
142 depr: self.deprecation(v.node.data.id()),
143 def: v.node.data.clone(),
147 stab: self.stability(it.id),
148 depr: self.deprecation(it.id),
149 generics: params.clone(),
150 attrs: it.attrs.clone(),
156 pub fn visit_fn(&mut self, item: &hir::Item,
157 name: ast::Name, fd: &hir::FnDecl,
158 unsafety: &hir::Unsafety,
159 constness: hir::Constness,
162 body: hir::BodyId) -> Function {
163 debug!("Visiting fn");
166 vis: item.vis.clone(),
167 stab: self.stability(item.id),
168 depr: self.deprecation(item.id),
169 attrs: item.attrs.clone(),
173 generics: gen.clone(),
175 constness: constness,
181 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
182 vis: hir::Visibility, id: ast::NodeId,
184 name: Option<ast::Name>) -> Module {
185 let mut om = Module::new(name);
186 om.where_outer = span;
187 om.where_inner = m.inner;
189 om.vis = vis.clone();
190 om.stab = self.stability(id);
191 om.depr = self.deprecation(id);
193 // Keep track of if there were any private modules in the path.
194 let orig_inside_public_path = self.inside_public_path;
195 self.inside_public_path &= vis == hir::Public;
196 for i in &m.item_ids {
197 let item = self.cx.tcx.hir.expect_item(i.id);
198 self.visit_item(item, None, &mut om);
200 self.inside_public_path = orig_inside_public_path;
201 if let Some(exports) = self.cx.tcx.export_map.get(&id) {
202 for export in exports {
203 if let Def::Macro(def_id, ..) = export.def {
204 if def_id.krate == LOCAL_CRATE {
205 continue // These are `krate.exported_macros`, handled in `self.visit()`.
207 let imported_from = self.cx.sess().cstore.original_crate_name(def_id.krate);
208 let def = match self.cx.sess().cstore.load_macro(def_id, self.cx.sess()) {
209 LoadedMacro::MacroDef(macro_def) => macro_def,
210 // FIXME(jseyfried): document proc macro reexports
211 LoadedMacro::ProcMacro(..) => continue,
214 let matchers = if let ast::ItemKind::MacroDef(ref tokens) = def.node {
215 let tts: Vec<_> = TokenStream::from(tokens.clone()).into_trees().collect();
216 tts.chunks(4).map(|arm| arm[0].span()).collect()
220 om.macros.push(Macro {
222 attrs: def.attrs.clone().into(),
223 name: def.ident.name,
226 stab: self.stability(def.id),
227 depr: self.deprecation(def.id),
228 imported_from: Some(imported_from),
236 /// Tries to resolve the target of a `pub use` statement and inlines the
237 /// target if it is defined locally and would not be documented otherwise,
238 /// or when it is specifically requested with `please_inline`.
239 /// (the latter is the case when the import is marked `doc(inline)`)
241 /// Cross-crate inlining occurs later on during crate cleaning
242 /// and follows different rules.
244 /// Returns true if the target has been inlined.
245 fn maybe_inline_local(&mut self,
248 renamed: Option<ast::Name>,
251 please_inline: bool) -> bool {
253 fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
254 while let Some(id) = cx.tcx.hir.get_enclosing_scope(node) {
256 if cx.tcx.hir.attrs(node).lists("doc").has_word("hidden") {
259 if node == ast::CRATE_NODE_ID {
266 let tcx = self.cx.tcx;
270 let def_did = def.def_id();
272 let use_attrs = tcx.hir.attrs(id);
273 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
274 let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
275 use_attrs.lists("doc").has_word("hidden");
277 // For cross-crate impl inlining we need to know whether items are
278 // reachable in documentation - a previously nonreachable item can be
279 // made reachable by cross-crate inlining which we're checking here.
280 // (this is done here because we need to know this upfront)
281 if !def_did.is_local() && !is_no_inline {
282 let attrs = clean::inline::load_attrs(self.cx, def_did);
283 let self_is_hidden = attrs.lists("doc").has_word("hidden");
289 Def::TyAlias(did) if !self_is_hidden => {
290 self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
292 Def::Mod(did) => if !self_is_hidden {
293 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
300 let def_node_id = match tcx.hir.as_local_node_id(def_did) {
301 Some(n) => n, None => return false
304 let is_private = !self.cx.access_levels.borrow().is_public(def_did);
305 let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
307 // Only inline if requested or if the item would otherwise be stripped
308 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
312 if !self.view_item_stack.insert(def_node_id) { return false }
314 let ret = match tcx.hir.get(def_node_id) {
315 hir_map::NodeItem(it) => {
316 let prev = mem::replace(&mut self.inlining, true);
319 hir::ItemMod(ref m) => {
320 for i in &m.item_ids {
321 let i = self.cx.tcx.hir.expect_item(i.id);
322 self.visit_item(i, None, om);
325 hir::ItemEnum(..) => {}
326 _ => { panic!("glob not mapped to a module or enum"); }
329 self.visit_item(it, renamed, om);
331 self.inlining = prev;
336 self.view_item_stack.remove(&def_node_id);
340 pub fn visit_item(&mut self, item: &hir::Item,
341 renamed: Option<ast::Name>, om: &mut Module) {
342 debug!("Visiting item {:?}", item);
343 let name = renamed.unwrap_or(item.name);
345 hir::ItemForeignMod(ref fm) => {
346 // If inlining we only want to include public functions.
347 om.foreigns.push(if self.inlining {
350 items: fm.items.iter().filter(|i| i.vis == hir::Public).cloned().collect(),
356 // If we're inlining, skip private items.
357 _ if self.inlining && item.vis != hir::Public => {}
358 hir::ItemExternCrate(ref p) => {
359 let cstore = &self.cx.sess().cstore;
360 om.extern_crates.push(ExternCrate {
361 cnum: cstore.extern_mod_stmt_cnum(item.id)
362 .unwrap_or(LOCAL_CRATE),
364 path: p.map(|x|x.to_string()),
365 vis: item.vis.clone(),
366 attrs: item.attrs.clone(),
370 hir::ItemUse(_, hir::UseKind::ListStem) => {}
371 hir::ItemUse(ref path, kind) => {
372 let is_glob = kind == hir::UseKind::Glob;
374 // If there was a private module in the current path then don't bother inlining
375 // anything as it will probably be stripped anyway.
376 if item.vis == hir::Public && self.inside_public_path {
377 let please_inline = item.attrs.iter().any(|item| {
378 match item.meta_item_list() {
379 Some(ref list) if item.check_name("doc") => {
380 list.iter().any(|i| i.check_name("inline"))
385 let name = if is_glob { None } else { Some(name) };
386 if self.maybe_inline_local(item.id,
396 om.imports.push(Import {
399 vis: item.vis.clone(),
400 attrs: item.attrs.clone(),
401 path: (**path).clone(),
406 hir::ItemMod(ref m) => {
407 om.mods.push(self.visit_mod_contents(item.span,
414 hir::ItemEnum(ref ed, ref gen) =>
415 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
416 hir::ItemStruct(ref sd, ref gen) =>
417 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
418 hir::ItemUnion(ref sd, ref gen) =>
419 om.unions.push(self.visit_union_data(item, name, sd, gen)),
420 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, body) =>
421 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
422 constness, abi, gen, body)),
423 hir::ItemTy(ref ty, ref gen) => {
429 attrs: item.attrs.clone(),
431 vis: item.vis.clone(),
432 stab: self.stability(item.id),
433 depr: self.deprecation(item.id),
437 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
440 mutability: mut_.clone(),
444 attrs: item.attrs.clone(),
446 vis: item.vis.clone(),
447 stab: self.stability(item.id),
448 depr: self.deprecation(item.id),
452 hir::ItemConst(ref ty, ref exp) => {
458 attrs: item.attrs.clone(),
460 vis: item.vis.clone(),
461 stab: self.stability(item.id),
462 depr: self.deprecation(item.id),
464 om.constants.push(s);
466 hir::ItemTrait(unsafety, ref gen, ref b, ref item_ids) => {
467 let items = item_ids.iter()
468 .map(|ti| self.cx.tcx.hir.trait_item(ti.id).clone())
474 generics: gen.clone(),
475 bounds: b.iter().cloned().collect(),
477 attrs: item.attrs.clone(),
479 vis: item.vis.clone(),
480 stab: self.stability(item.id),
481 depr: self.deprecation(item.id),
486 hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref item_ids) => {
487 // Don't duplicate impls when inlining, we'll pick them up
488 // regardless of where they're located.
490 let items = item_ids.iter()
491 .map(|ii| self.cx.tcx.hir.impl_item(ii.id).clone())
496 generics: gen.clone(),
500 attrs: item.attrs.clone(),
503 vis: item.vis.clone(),
504 stab: self.stability(item.id),
505 depr: self.deprecation(item.id),
510 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
511 // See comment above about ItemImpl.
513 let i = DefaultImpl {
515 trait_: trait_ref.clone(),
517 attrs: item.attrs.clone(),
520 om.def_traits.push(i);
526 // convert each exported_macro into a doc item
527 fn visit_local_macro(&self, def: &hir::MacroDef) -> Macro {
528 let tts = def.body.trees().collect::<Vec<_>>();
529 // Extract the spans of all matchers. They represent the "interface" of the macro.
530 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
533 def_id: self.cx.tcx.hir.local_def_id(def.id),
534 attrs: def.attrs.clone(),
538 stab: self.stability(def.id),
539 depr: self.deprecation(def.id),