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
18 use syntax::codemap::Spanned;
19 use syntax_pos::{self, Span};
21 use rustc::hir::map as hir_map;
22 use rustc::hir::def::Def;
23 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
24 use rustc::middle::cstore::CrateStore;
25 use rustc::middle::privacy::AccessLevel;
26 use rustc::util::nodemap::{FxHashSet, FxHashMap};
31 use clean::{self, AttributesExt, NestedAttributesExt, def_id_to_path};
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
39 // also, is there some reason that this doesn't use the 'visit'
40 // framework from syntax?
42 pub struct RustdocVisitor<'a, 'tcx: 'a, 'rcx: 'a> {
43 pub cstore: &'a CrateStore,
45 pub attrs: hir::HirVec<ast::Attribute>,
46 pub cx: &'a core::DocContext<'a, 'tcx, 'rcx>,
47 view_item_stack: FxHashSet<ast::NodeId>,
49 /// Is the current module and all of its parents public?
50 inside_public_path: bool,
51 exact_paths: Option<FxHashMap<DefId, Vec<String>>>,
54 impl<'a, 'tcx, 'rcx> RustdocVisitor<'a, 'tcx, 'rcx> {
55 pub fn new(cstore: &'a CrateStore,
56 cx: &'a core::DocContext<'a, 'tcx, 'rcx>) -> RustdocVisitor<'a, 'tcx, 'rcx> {
57 // If the root is re-exported, terminate all recursion.
58 let mut stack = FxHashSet();
59 stack.insert(ast::CRATE_NODE_ID);
61 module: Module::new(None),
62 attrs: hir::HirVec::new(),
64 view_item_stack: stack,
66 inside_public_path: true,
67 exact_paths: Some(FxHashMap()),
72 fn store_path(&mut self, did: DefId) {
73 // We can't use the entry api, as that keeps the mutable borrow of self active
74 // when we try to use cx
75 let exact_paths = self.exact_paths.as_mut().unwrap();
76 if exact_paths.get(&did).is_none() {
77 let path = def_id_to_path(self.cx, did, self.cx.crate_name.clone());
78 exact_paths.insert(did, path);
82 fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
83 self.cx.tcx.hir.opt_local_def_id(id)
84 .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
87 fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
88 self.cx.tcx.hir.opt_local_def_id(id)
89 .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
92 pub fn visit(&mut self, krate: &hir::Crate) {
93 self.attrs = krate.attrs.clone();
95 self.module = self.visit_mod_contents(krate.span,
97 Spanned { span: syntax_pos::DUMMY_SP,
98 node: hir::VisibilityKind::Public },
102 // attach the crate's exported macros to the top-level module:
103 let macro_exports: Vec<_> =
104 krate.exported_macros.iter().map(|def| self.visit_local_macro(def)).collect();
105 self.module.macros.extend(macro_exports);
106 self.module.is_crate = true;
108 self.cx.renderinfo.borrow_mut().exact_paths = self.exact_paths.take().unwrap();
111 pub fn visit_variant_data(&mut self, item: &hir::Item,
112 name: ast::Name, sd: &hir::VariantData,
113 generics: &hir::Generics) -> Struct {
114 debug!("Visiting struct");
115 let struct_type = struct_type_from_def(&*sd);
120 vis: item.vis.clone(),
121 stab: self.stability(item.id),
122 depr: self.deprecation(item.id),
123 attrs: item.attrs.clone(),
124 generics: generics.clone(),
125 fields: sd.fields().iter().cloned().collect(),
130 pub fn visit_union_data(&mut self, item: &hir::Item,
131 name: ast::Name, sd: &hir::VariantData,
132 generics: &hir::Generics) -> Union {
133 debug!("Visiting union");
134 let struct_type = struct_type_from_def(&*sd);
139 vis: item.vis.clone(),
140 stab: self.stability(item.id),
141 depr: self.deprecation(item.id),
142 attrs: item.attrs.clone(),
143 generics: generics.clone(),
144 fields: sd.fields().iter().cloned().collect(),
149 pub fn visit_enum_def(&mut self, it: &hir::Item,
150 name: ast::Name, def: &hir::EnumDef,
151 params: &hir::Generics) -> Enum {
152 debug!("Visiting enum");
155 variants: def.variants.iter().map(|v| Variant {
157 attrs: v.node.attrs.clone(),
158 stab: self.stability(v.node.data.id()),
159 depr: self.deprecation(v.node.data.id()),
160 def: v.node.data.clone(),
164 stab: self.stability(it.id),
165 depr: self.deprecation(it.id),
166 generics: params.clone(),
167 attrs: it.attrs.clone(),
173 pub fn visit_fn(&mut self, item: &hir::Item,
174 name: ast::Name, fd: &hir::FnDecl,
175 header: hir::FnHeader,
177 body: hir::BodyId) -> Function {
178 debug!("Visiting fn");
181 vis: item.vis.clone(),
182 stab: self.stability(item.id),
183 depr: self.deprecation(item.id),
184 attrs: item.attrs.clone(),
188 generics: gen.clone(),
194 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
195 vis: hir::Visibility, id: ast::NodeId,
197 name: Option<ast::Name>) -> Module {
198 let mut om = Module::new(name);
199 om.where_outer = span;
200 om.where_inner = m.inner;
202 om.vis = vis.clone();
203 om.stab = self.stability(id);
204 om.depr = self.deprecation(id);
206 // Keep track of if there were any private modules in the path.
207 let orig_inside_public_path = self.inside_public_path;
208 self.inside_public_path &= vis.node.is_pub();
209 for i in &m.item_ids {
210 let item = self.cx.tcx.hir.expect_item(i.id);
211 self.visit_item(item, None, &mut om);
213 self.inside_public_path = orig_inside_public_path;
217 /// Tries to resolve the target of a `pub use` statement and inlines the
218 /// target if it is defined locally and would not be documented otherwise,
219 /// or when it is specifically requested with `please_inline`.
220 /// (the latter is the case when the import is marked `doc(inline)`)
222 /// Cross-crate inlining occurs later on during crate cleaning
223 /// and follows different rules.
225 /// Returns true if the target has been inlined.
226 fn maybe_inline_local(&mut self,
229 renamed: Option<ast::Name>,
232 please_inline: bool) -> bool {
234 fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
235 while let Some(id) = cx.tcx.hir.get_enclosing_scope(node) {
237 if cx.tcx.hir.attrs(node).lists("doc").has_word("hidden") {
240 if node == ast::CRATE_NODE_ID {
247 debug!("maybe_inline_local def: {:?}", def);
249 let tcx = self.cx.tcx;
253 let def_did = def.def_id();
255 let use_attrs = tcx.hir.attrs(id);
256 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
257 let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
258 use_attrs.lists("doc").has_word("hidden");
260 // For cross-crate impl inlining we need to know whether items are
261 // reachable in documentation - a previously nonreachable item can be
262 // made reachable by cross-crate inlining which we're checking here.
263 // (this is done here because we need to know this upfront)
264 if !def_did.is_local() && !is_no_inline {
265 let attrs = clean::inline::load_attrs(self.cx, def_did);
266 let self_is_hidden = attrs.lists("doc").has_word("hidden");
272 Def::TyForeign(did) |
273 Def::TyAlias(did) if !self_is_hidden => {
274 self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
276 Def::Mod(did) => if !self_is_hidden {
277 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
285 let def_node_id = match tcx.hir.as_local_node_id(def_did) {
286 Some(n) => n, None => return false
289 let is_private = !self.cx.access_levels.borrow().is_public(def_did);
290 let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
292 // Only inline if requested or if the item would otherwise be stripped
293 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
297 if !self.view_item_stack.insert(def_node_id) { return false }
299 let ret = match tcx.hir.get(def_node_id) {
300 hir_map::NodeItem(&hir::Item { node: hir::ItemMod(ref m), .. }) if glob => {
301 let prev = mem::replace(&mut self.inlining, true);
302 for i in &m.item_ids {
303 let i = self.cx.tcx.hir.expect_item(i.id);
304 self.visit_item(i, None, om);
306 self.inlining = prev;
309 hir_map::NodeItem(it) if !glob => {
310 let prev = mem::replace(&mut self.inlining, true);
311 self.visit_item(it, renamed, om);
312 self.inlining = prev;
315 hir_map::NodeForeignItem(it) if !glob => {
316 // generate a fresh `extern {}` block if we want to inline a foreign item.
317 om.foreigns.push(hir::ForeignMod {
318 abi: tcx.hir.get_foreign_abi(it.id),
319 items: vec![hir::ForeignItem {
320 name: renamed.unwrap_or(it.name),
328 self.view_item_stack.remove(&def_node_id);
332 pub fn visit_item(&mut self, item: &hir::Item,
333 renamed: Option<ast::Name>, om: &mut Module) {
334 debug!("Visiting item {:?}", item);
335 let name = renamed.unwrap_or(item.name);
337 if item.vis.node.is_pub() {
338 let def_id = self.cx.tcx.hir.local_def_id(item.id);
339 self.store_path(def_id);
343 hir::ItemForeignMod(ref fm) => {
344 // If inlining we only want to include public functions.
345 om.foreigns.push(if self.inlining {
348 items: fm.items.iter().filter(|i| i.vis.node.is_pub()).cloned().collect(),
354 // If we're inlining, skip private items.
355 _ if self.inlining && !item.vis.node.is_pub() => {}
356 hir::ItemGlobalAsm(..) => {}
357 hir::ItemExternCrate(orig_name) => {
358 let def_id = self.cx.tcx.hir.local_def_id(item.id);
359 om.extern_crates.push(ExternCrate {
360 cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
361 .unwrap_or(LOCAL_CRATE),
363 path: orig_name.map(|x|x.to_string()),
364 vis: item.vis.clone(),
365 attrs: item.attrs.clone(),
369 hir::ItemUse(_, hir::UseKind::ListStem) => {}
370 hir::ItemUse(ref path, kind) => {
371 let is_glob = kind == hir::UseKind::Glob;
373 // struct and variant constructors always show up alongside their definitions, we've
374 // already processed them so just discard these.
376 Def::StructCtor(..) | Def::VariantCtor(..) => return,
380 // If there was a private module in the current path then don't bother inlining
381 // anything as it will probably be stripped anyway.
382 if item.vis.node.is_pub() && self.inside_public_path {
383 let please_inline = item.attrs.iter().any(|item| {
384 match item.meta_item_list() {
385 Some(ref list) if item.check_name("doc") => {
386 list.iter().any(|i| i.check_name("inline"))
391 let name = if is_glob { None } else { Some(name) };
392 if self.maybe_inline_local(item.id,
402 om.imports.push(Import {
405 vis: item.vis.clone(),
406 attrs: item.attrs.clone(),
407 path: (**path).clone(),
412 hir::ItemMod(ref m) => {
413 om.mods.push(self.visit_mod_contents(item.span,
420 hir::ItemEnum(ref ed, ref gen) =>
421 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
422 hir::ItemStruct(ref sd, ref gen) =>
423 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
424 hir::ItemUnion(ref sd, ref gen) =>
425 om.unions.push(self.visit_union_data(item, name, sd, gen)),
426 hir::ItemFn(ref fd, header, ref gen, body) =>
427 om.fns.push(self.visit_fn(item, name, &**fd, header, gen, body)),
428 hir::ItemTy(ref ty, ref gen) => {
434 attrs: item.attrs.clone(),
436 vis: item.vis.clone(),
437 stab: self.stability(item.id),
438 depr: self.deprecation(item.id),
442 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
445 mutability: mut_.clone(),
449 attrs: item.attrs.clone(),
451 vis: item.vis.clone(),
452 stab: self.stability(item.id),
453 depr: self.deprecation(item.id),
457 hir::ItemConst(ref ty, ref exp) => {
463 attrs: item.attrs.clone(),
465 vis: item.vis.clone(),
466 stab: self.stability(item.id),
467 depr: self.deprecation(item.id),
469 om.constants.push(s);
471 hir::ItemTrait(is_auto, unsafety, ref gen, ref b, ref item_ids) => {
472 let items = item_ids.iter()
473 .map(|ti| self.cx.tcx.hir.trait_item(ti.id).clone())
480 generics: gen.clone(),
481 bounds: b.iter().cloned().collect(),
483 attrs: item.attrs.clone(),
485 vis: item.vis.clone(),
486 stab: self.stability(item.id),
487 depr: self.deprecation(item.id),
491 hir::ItemTraitAlias(..) => {
492 unimplemented!("trait objects are not yet implemented")
495 hir::ItemImpl(unsafety,
502 // Don't duplicate impls when inlining, we'll pick them up
503 // regardless of where they're located.
505 let items = item_ids.iter()
506 .map(|ii| self.cx.tcx.hir.impl_item(ii.id).clone())
512 generics: gen.clone(),
516 attrs: item.attrs.clone(),
519 vis: item.vis.clone(),
520 stab: self.stability(item.id),
521 depr: self.deprecation(item.id),
526 hir::ItemExistential(_) => {
527 // FIXME(oli-obk): actually generate docs for real existential items
532 // convert each exported_macro into a doc item
533 fn visit_local_macro(&self, def: &hir::MacroDef) -> Macro {
534 debug!("visit_local_macro: {}", def.name);
535 let tts = def.body.trees().collect::<Vec<_>>();
536 // Extract the spans of all matchers. They represent the "interface" of the macro.
537 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
540 def_id: self.cx.tcx.hir.local_def_id(def.id),
541 attrs: def.attrs.clone(),
545 stab: self.stability(def.id),
546 depr: self.deprecation(def.id),