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};
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::ForeignTy(did) |
271 Def::TyAlias(did) if !self_is_hidden => {
275 .insert(did, AccessLevel::Public);
277 Def::Mod(did) => if !self_is_hidden {
278 ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
286 let def_node_id = match tcx.hir.as_local_node_id(def_did) {
287 Some(n) => n, None => return false
290 let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(def_did);
291 let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
293 // Only inline if requested or if the item would otherwise be stripped
294 if (!please_inline && !is_private && !is_hidden) || is_no_inline {
298 if !self.view_item_stack.insert(def_node_id) { return false }
300 let ret = match tcx.hir.get(def_node_id) {
301 Node::Item(&hir::Item { node: hir::ItemKind::Mod(ref m), .. }) if glob => {
302 let prev = mem::replace(&mut self.inlining, true);
303 for i in &m.item_ids {
304 let i = self.cx.tcx.hir.expect_item(i.id);
305 self.visit_item(i, None, om);
307 self.inlining = prev;
310 Node::Item(it) if !glob => {
311 let prev = mem::replace(&mut self.inlining, true);
312 self.visit_item(it, renamed, om);
313 self.inlining = prev;
316 Node::ForeignItem(it) if !glob => {
317 // generate a fresh `extern {}` block if we want to inline a foreign item.
318 om.foreigns.push(hir::ForeignMod {
319 abi: tcx.hir.get_foreign_abi(it.id),
320 items: vec![hir::ForeignItem {
321 name: renamed.unwrap_or(it.name),
329 self.view_item_stack.remove(&def_node_id);
333 pub fn visit_item(&mut self, item: &hir::Item,
334 renamed: Option<ast::Name>, om: &mut Module) {
335 debug!("Visiting item {:?}", item);
336 let name = renamed.unwrap_or(item.name);
338 if item.vis.node.is_pub() {
339 let def_id = self.cx.tcx.hir.local_def_id(item.id);
340 self.store_path(def_id);
344 hir::ItemKind::ForeignMod(ref fm) => {
345 // If inlining we only want to include public functions.
346 om.foreigns.push(if self.inlining {
349 items: fm.items.iter().filter(|i| i.vis.node.is_pub()).cloned().collect(),
355 // If we're inlining, skip private items.
356 _ if self.inlining && !item.vis.node.is_pub() => {}
357 hir::ItemKind::GlobalAsm(..) => {}
358 hir::ItemKind::ExternCrate(orig_name) => {
359 let def_id = self.cx.tcx.hir.local_def_id(item.id);
360 om.extern_crates.push(ExternCrate {
361 cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
362 .unwrap_or(LOCAL_CRATE),
364 path: orig_name.map(|x|x.to_string()),
365 vis: item.vis.clone(),
366 attrs: item.attrs.clone(),
370 hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
371 hir::ItemKind::Use(ref path, kind) => {
372 let is_glob = kind == hir::UseKind::Glob;
374 // struct and variant constructors always show up alongside their definitions, we've
375 // already processed them so just discard these.
377 Def::StructCtor(..) | Def::VariantCtor(..) | Def::SelfCtor(..) => return,
381 // If there was a private module in the current path then don't bother inlining
382 // anything as it will probably be stripped anyway.
383 if item.vis.node.is_pub() && self.inside_public_path {
384 let please_inline = item.attrs.iter().any(|item| {
385 match item.meta_item_list() {
386 Some(ref list) if item.check_name("doc") => {
387 list.iter().any(|i| i.check_name("inline"))
392 let name = if is_glob { None } else { Some(name) };
393 if self.maybe_inline_local(item.id,
403 om.imports.push(Import {
406 vis: item.vis.clone(),
407 attrs: item.attrs.clone(),
408 path: (**path).clone(),
413 hir::ItemKind::Mod(ref m) => {
414 om.mods.push(self.visit_mod_contents(item.span,
421 hir::ItemKind::Enum(ref ed, ref gen) =>
422 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
423 hir::ItemKind::Struct(ref sd, ref gen) =>
424 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
425 hir::ItemKind::Union(ref sd, ref gen) =>
426 om.unions.push(self.visit_union_data(item, name, sd, gen)),
427 hir::ItemKind::Fn(ref fd, header, ref gen, body) =>
428 om.fns.push(self.visit_fn(item, name, &**fd, header, gen, body)),
429 hir::ItemKind::Ty(ref ty, ref gen) => {
435 attrs: item.attrs.clone(),
437 vis: item.vis.clone(),
438 stab: self.stability(item.id),
439 depr: self.deprecation(item.id),
443 hir::ItemKind::Existential(ref exist_ty) => {
444 let t = Existential {
445 exist_ty: exist_ty.clone(),
448 attrs: item.attrs.clone(),
450 vis: item.vis.clone(),
451 stab: self.stability(item.id),
452 depr: self.deprecation(item.id),
454 om.existentials.push(t);
456 hir::ItemKind::Static(ref ty, ref mut_, ref exp) => {
459 mutability: mut_.clone(),
463 attrs: item.attrs.clone(),
465 vis: item.vis.clone(),
466 stab: self.stability(item.id),
467 depr: self.deprecation(item.id),
471 hir::ItemKind::Const(ref ty, ref exp) => {
477 attrs: item.attrs.clone(),
479 vis: item.vis.clone(),
480 stab: self.stability(item.id),
481 depr: self.deprecation(item.id),
483 om.constants.push(s);
485 hir::ItemKind::Trait(is_auto, unsafety, ref gen, ref b, ref item_ids) => {
486 let items = item_ids.iter()
487 .map(|ti| self.cx.tcx.hir.trait_item(ti.id).clone())
494 generics: gen.clone(),
495 bounds: b.iter().cloned().collect(),
497 attrs: item.attrs.clone(),
499 vis: item.vis.clone(),
500 stab: self.stability(item.id),
501 depr: self.deprecation(item.id),
505 hir::ItemKind::TraitAlias(..) => {
506 unimplemented!("trait objects are not yet implemented")
509 hir::ItemKind::Impl(unsafety,
516 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
517 // them up regardless of where they're located.
518 if !self.inlining && tr.is_none() {
519 let items = item_ids.iter()
520 .map(|ii| self.cx.tcx.hir.impl_item(ii.id).clone())
526 generics: gen.clone(),
530 attrs: item.attrs.clone(),
533 vis: item.vis.clone(),
534 stab: self.stability(item.id),
535 depr: self.deprecation(item.id),
543 // convert each exported_macro into a doc item
544 fn visit_local_macro(&self, def: &hir::MacroDef) -> Macro {
545 debug!("visit_local_macro: {}", def.name);
546 let tts = def.body.trees().collect::<Vec<_>>();
547 // Extract the spans of all matchers. They represent the "interface" of the macro.
548 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
551 def_id: self.cx.tcx.hir.local_def_id(def.id),
552 attrs: def.attrs.clone(),
556 stab: self.stability(def.id),
557 depr: self.deprecation(def.id),