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::source_map::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::privacy::AccessLevel;
25 use rustc::util::nodemap::{FxHashSet, FxHashMap};
30 use clean::{self, AttributesExt, NestedAttributesExt, def_id_to_path};
33 // looks to me like the first two of these are actually
34 // output parameters, maybe only mutated once; perhaps
35 // better simply to have the visit method return a tuple
38 // also, is there some reason that this doesn't use the 'visit'
39 // framework from syntax?
41 pub struct RustdocVisitor<'a, 'tcx: 'a, 'rcx: 'a, 'cstore: 'rcx> {
43 pub attrs: hir::HirVec<ast::Attribute>,
44 pub cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>,
45 view_item_stack: FxHashSet<ast::NodeId>,
47 /// Is the current module and all of its parents public?
48 inside_public_path: bool,
49 exact_paths: Option<FxHashMap<DefId, Vec<String>>>,
52 impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> {
54 cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>
55 ) -> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> {
56 // If the root is re-exported, terminate all recursion.
57 let mut stack = FxHashSet();
58 stack.insert(ast::CRATE_NODE_ID);
60 module: Module::new(None),
61 attrs: hir::HirVec::new(),
63 view_item_stack: stack,
65 inside_public_path: true,
66 exact_paths: Some(FxHashMap()),
70 fn store_path(&mut self, did: DefId) {
71 // We can't use the entry api, as that keeps the mutable borrow of self active
72 // when we try to use cx
73 let exact_paths = self.exact_paths.as_mut().unwrap();
74 if exact_paths.get(&did).is_none() {
75 let path = def_id_to_path(self.cx, did, self.cx.crate_name.clone());
76 exact_paths.insert(did, path);
80 fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
81 self.cx.tcx.hir.opt_local_def_id(id)
82 .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
85 fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
86 self.cx.tcx.hir.opt_local_def_id(id)
87 .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
90 pub fn visit(&mut self, krate: &hir::Crate) {
91 self.attrs = krate.attrs.clone();
93 self.module = self.visit_mod_contents(krate.span,
95 Spanned { span: syntax_pos::DUMMY_SP,
96 node: hir::VisibilityKind::Public },
100 // attach the crate's exported macros to the top-level module:
101 let macro_exports: Vec<_> =
102 krate.exported_macros.iter().map(|def| self.visit_local_macro(def)).collect();
103 self.module.macros.extend(macro_exports);
104 self.module.is_crate = true;
106 self.cx.renderinfo.borrow_mut().exact_paths = self.exact_paths.take().unwrap();
109 pub fn visit_variant_data(&mut self, item: &hir::Item,
110 name: ast::Name, sd: &hir::VariantData,
111 generics: &hir::Generics) -> Struct {
112 debug!("Visiting struct");
113 let struct_type = struct_type_from_def(&*sd);
118 vis: item.vis.clone(),
119 stab: self.stability(item.id),
120 depr: self.deprecation(item.id),
121 attrs: item.attrs.clone(),
122 generics: generics.clone(),
123 fields: sd.fields().iter().cloned().collect(),
128 pub fn visit_union_data(&mut self, item: &hir::Item,
129 name: ast::Name, sd: &hir::VariantData,
130 generics: &hir::Generics) -> Union {
131 debug!("Visiting union");
132 let struct_type = struct_type_from_def(&*sd);
137 vis: item.vis.clone(),
138 stab: self.stability(item.id),
139 depr: self.deprecation(item.id),
140 attrs: item.attrs.clone(),
141 generics: generics.clone(),
142 fields: sd.fields().iter().cloned().collect(),
147 pub fn visit_enum_def(&mut self, it: &hir::Item,
148 name: ast::Name, def: &hir::EnumDef,
149 params: &hir::Generics) -> Enum {
150 debug!("Visiting enum");
153 variants: def.variants.iter().map(|v| Variant {
155 attrs: v.node.attrs.clone(),
156 stab: self.stability(v.node.data.id()),
157 depr: self.deprecation(v.node.data.id()),
158 def: v.node.data.clone(),
162 stab: self.stability(it.id),
163 depr: self.deprecation(it.id),
164 generics: params.clone(),
165 attrs: it.attrs.clone(),
171 pub fn visit_fn(&mut self, item: &hir::Item,
172 name: ast::Name, fd: &hir::FnDecl,
173 header: hir::FnHeader,
175 body: hir::BodyId) -> Function {
176 debug!("Visiting fn");
179 vis: item.vis.clone(),
180 stab: self.stability(item.id),
181 depr: self.deprecation(item.id),
182 attrs: item.attrs.clone(),
186 generics: gen.clone(),
192 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
193 vis: hir::Visibility, id: ast::NodeId,
195 name: Option<ast::Name>) -> Module {
196 let mut om = Module::new(name);
197 om.where_outer = span;
198 om.where_inner = m.inner;
200 om.vis = vis.clone();
201 om.stab = self.stability(id);
202 om.depr = self.deprecation(id);
204 // Keep track of if there were any private modules in the path.
205 let orig_inside_public_path = self.inside_public_path;
206 self.inside_public_path &= vis.node.is_pub();
207 for i in &m.item_ids {
208 let item = self.cx.tcx.hir.expect_item(i.id);
209 self.visit_item(item, None, &mut om);
211 self.inside_public_path = orig_inside_public_path;
215 /// Tries to resolve the target of a `pub use` statement and inlines the
216 /// target if it is defined locally and would not be documented otherwise,
217 /// or when it is specifically requested with `please_inline`.
218 /// (the latter is the case when the import is marked `doc(inline)`)
220 /// Cross-crate inlining occurs later on during crate cleaning
221 /// and follows different rules.
223 /// Returns true if the target has been inlined.
224 fn maybe_inline_local(&mut self,
227 renamed: Option<ast::Name>,
230 please_inline: bool) -> bool {
232 fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
233 while let Some(id) = cx.tcx.hir.get_enclosing_scope(node) {
235 if cx.tcx.hir.attrs(node).lists("doc").has_word("hidden") {
238 if node == ast::CRATE_NODE_ID {
245 debug!("maybe_inline_local def: {:?}", def);
247 let tcx = self.cx.tcx;
251 let def_did = def.def_id();
253 let use_attrs = tcx.hir.attrs(id);
254 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
255 let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
256 use_attrs.lists("doc").has_word("hidden");
258 // For cross-crate impl inlining we need to know whether items are
259 // reachable in documentation - a previously nonreachable item can be
260 // made reachable by cross-crate inlining which we're checking here.
261 // (this is done here because we need to know this upfront)
262 if !def_did.is_local() && !is_no_inline {
263 let attrs = clean::inline::load_attrs(self.cx, def_did);
264 let self_is_hidden = attrs.lists("doc").has_word("hidden");
270 Def::TyForeign(did) |
271 Def::TyAlias(did) if !self_is_hidden => {
272 self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
274 Def::Mod(did) => if !self_is_hidden {
275 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
283 let def_node_id = match tcx.hir.as_local_node_id(def_did) {
284 Some(n) => n, None => return false
287 let is_private = !self.cx.access_levels.borrow().is_public(def_did);
288 let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
290 // Only inline if requested or if the item would otherwise be stripped
291 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
295 if !self.view_item_stack.insert(def_node_id) { return false }
297 let ret = match tcx.hir.get(def_node_id) {
298 hir_map::NodeItem(&hir::Item { node: hir::ItemKind::Mod(ref m), .. }) if glob => {
299 let prev = mem::replace(&mut self.inlining, true);
300 for i in &m.item_ids {
301 let i = self.cx.tcx.hir.expect_item(i.id);
302 self.visit_item(i, None, om);
304 self.inlining = prev;
307 hir_map::NodeItem(it) if !glob => {
308 let prev = mem::replace(&mut self.inlining, true);
309 self.visit_item(it, renamed, om);
310 self.inlining = prev;
313 hir_map::NodeForeignItem(it) if !glob => {
314 // generate a fresh `extern {}` block if we want to inline a foreign item.
315 om.foreigns.push(hir::ForeignMod {
316 abi: tcx.hir.get_foreign_abi(it.id),
317 items: vec![hir::ForeignItem {
318 name: renamed.unwrap_or(it.name),
326 self.view_item_stack.remove(&def_node_id);
330 pub fn visit_item(&mut self, item: &hir::Item,
331 renamed: Option<ast::Name>, om: &mut Module) {
332 debug!("Visiting item {:?}", item);
333 let name = renamed.unwrap_or(item.name);
335 if item.vis.node.is_pub() {
336 let def_id = self.cx.tcx.hir.local_def_id(item.id);
337 self.store_path(def_id);
341 hir::ItemKind::ForeignMod(ref fm) => {
342 // If inlining we only want to include public functions.
343 om.foreigns.push(if self.inlining {
346 items: fm.items.iter().filter(|i| i.vis.node.is_pub()).cloned().collect(),
352 // If we're inlining, skip private items.
353 _ if self.inlining && !item.vis.node.is_pub() => {}
354 hir::ItemKind::GlobalAsm(..) => {}
355 hir::ItemKind::ExternCrate(orig_name) => {
356 let def_id = self.cx.tcx.hir.local_def_id(item.id);
357 om.extern_crates.push(ExternCrate {
358 cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
359 .unwrap_or(LOCAL_CRATE),
361 path: orig_name.map(|x|x.to_string()),
362 vis: item.vis.clone(),
363 attrs: item.attrs.clone(),
367 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
368 hir::ItemKind::Use(ref path, kind) => {
369 let is_glob = kind == hir::UseKind::Glob;
371 // struct and variant constructors always show up alongside their definitions, we've
372 // already processed them so just discard these.
374 Def::StructCtor(..) | Def::VariantCtor(..) => return,
378 // If there was a private module in the current path then don't bother inlining
379 // anything as it will probably be stripped anyway.
380 if item.vis.node.is_pub() && self.inside_public_path {
381 let please_inline = item.attrs.iter().any(|item| {
382 match item.meta_item_list() {
383 Some(ref list) if item.check_name("doc") => {
384 list.iter().any(|i| i.check_name("inline"))
389 let name = if is_glob { None } else { Some(name) };
390 if self.maybe_inline_local(item.id,
400 om.imports.push(Import {
403 vis: item.vis.clone(),
404 attrs: item.attrs.clone(),
405 path: (**path).clone(),
410 hir::ItemKind::Mod(ref m) => {
411 om.mods.push(self.visit_mod_contents(item.span,
418 hir::ItemKind::Enum(ref ed, ref gen) =>
419 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
420 hir::ItemKind::Struct(ref sd, ref gen) =>
421 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
422 hir::ItemKind::Union(ref sd, ref gen) =>
423 om.unions.push(self.visit_union_data(item, name, sd, gen)),
424 hir::ItemKind::Fn(ref fd, header, ref gen, body) =>
425 om.fns.push(self.visit_fn(item, name, &**fd, header, gen, body)),
426 hir::ItemKind::Ty(ref ty, ref gen) => {
432 attrs: item.attrs.clone(),
434 vis: item.vis.clone(),
435 stab: self.stability(item.id),
436 depr: self.deprecation(item.id),
440 hir::ItemKind::Existential(ref exist_ty) => {
441 let t = Existential {
442 exist_ty: exist_ty.clone(),
445 attrs: item.attrs.clone(),
447 vis: item.vis.clone(),
448 stab: self.stability(item.id),
449 depr: self.deprecation(item.id),
451 om.existentials.push(t);
453 hir::ItemKind::Static(ref ty, ref mut_, ref exp) => {
456 mutability: mut_.clone(),
460 attrs: item.attrs.clone(),
462 vis: item.vis.clone(),
463 stab: self.stability(item.id),
464 depr: self.deprecation(item.id),
468 hir::ItemKind::Const(ref ty, ref exp) => {
474 attrs: item.attrs.clone(),
476 vis: item.vis.clone(),
477 stab: self.stability(item.id),
478 depr: self.deprecation(item.id),
480 om.constants.push(s);
482 hir::ItemKind::Trait(is_auto, unsafety, ref gen, ref b, ref item_ids) => {
483 let items = item_ids.iter()
484 .map(|ti| self.cx.tcx.hir.trait_item(ti.id).clone())
491 generics: gen.clone(),
492 bounds: b.iter().cloned().collect(),
494 attrs: item.attrs.clone(),
496 vis: item.vis.clone(),
497 stab: self.stability(item.id),
498 depr: self.deprecation(item.id),
502 hir::ItemKind::TraitAlias(..) => {
503 unimplemented!("trait objects are not yet implemented")
506 hir::ItemKind::Impl(unsafety,
513 // Don't duplicate impls when inlining, we'll pick them up
514 // regardless of where they're located.
516 let items = item_ids.iter()
517 .map(|ii| self.cx.tcx.hir.impl_item(ii.id).clone())
523 generics: gen.clone(),
527 attrs: item.attrs.clone(),
530 vis: item.vis.clone(),
531 stab: self.stability(item.id),
532 depr: self.deprecation(item.id),
540 // convert each exported_macro into a doc item
541 fn visit_local_macro(&self, def: &hir::MacroDef) -> Macro {
542 debug!("visit_local_macro: {}", def.name);
543 let tts = def.body.trees().collect::<Vec<_>>();
544 // Extract the spans of all matchers. They represent the "interface" of the macro.
545 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
548 def_id: self.cx.tcx.hir.local_def_id(def.id),
549 attrs: def.attrs.clone(),
553 stab: self.stability(def.id),
554 depr: self.deprecation(def.id),