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
14 use std::collections::HashSet;
20 use syntax::attr::AttrMetaMethods;
21 use syntax::codemap::Span;
23 use rustc::front::map as hir_map;
24 use rustc::middle::stability;
31 // looks to me like the first two of these are actually
32 // output parameters, maybe only mutated once; perhaps
33 // better simply to have the visit method return a tuple
36 // also, is there some reason that this doesn't use the 'visit'
37 // framework from syntax?
39 pub struct RustdocVisitor<'a, 'tcx: 'a> {
41 pub attrs: Vec<ast::Attribute>,
42 pub cx: &'a core::DocContext<'a, 'tcx>,
43 pub analysis: Option<&'a core::CrateAnalysis>,
44 view_item_stack: HashSet<ast::NodeId>,
45 inlining_from_glob: bool,
48 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
49 pub fn new(cx: &'a core::DocContext<'a, 'tcx>,
50 analysis: Option<&'a core::CrateAnalysis>) -> RustdocVisitor<'a, 'tcx> {
51 // If the root is reexported, terminate all recursion.
52 let mut stack = HashSet::new();
53 stack.insert(ast::CRATE_NODE_ID);
55 module: Module::new(None),
59 view_item_stack: stack,
60 inlining_from_glob: false,
64 fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
65 self.cx.tcx_opt().and_then(|tcx| {
66 self.cx.map.opt_local_def_id(id)
67 .and_then(|def_id| stability::lookup(tcx, def_id))
72 pub fn visit(&mut self, krate: &hir::Crate) {
73 self.attrs = krate.attrs.clone();
75 self.module = self.visit_mod_contents(krate.span,
81 // attach the crate's exported macros to the top-level module:
82 self.module.macros = krate.exported_macros.iter()
83 .map(|def| self.visit_macro(def)).collect();
84 self.module.is_crate = true;
87 pub fn visit_variant_data(&mut self, item: &hir::Item,
88 name: ast::Name, sd: &hir::VariantData,
89 generics: &hir::Generics) -> Struct {
90 debug!("Visiting struct");
91 let struct_type = struct_type_from_def(&*sd);
94 struct_type: struct_type,
97 stab: self.stability(item.id),
98 attrs: item.attrs.clone(),
99 generics: generics.clone(),
100 fields: sd.fields().iter().cloned().collect(),
105 pub fn visit_enum_def(&mut self, it: &hir::Item,
106 name: ast::Name, def: &hir::EnumDef,
107 params: &hir::Generics) -> Enum {
108 debug!("Visiting enum");
111 variants: def.variants.iter().map(|v| Variant {
113 attrs: v.node.attrs.clone(),
114 stab: self.stability(v.node.data.id()),
115 def: v.node.data.clone(),
119 stab: self.stability(it.id),
120 generics: params.clone(),
121 attrs: it.attrs.clone(),
127 pub fn visit_fn(&mut self, item: &hir::Item,
128 name: ast::Name, fd: &hir::FnDecl,
129 unsafety: &hir::Unsafety,
130 constness: hir::Constness,
132 gen: &hir::Generics) -> Function {
133 debug!("Visiting fn");
137 stab: self.stability(item.id),
138 attrs: item.attrs.clone(),
142 generics: gen.clone(),
144 constness: constness,
149 pub fn visit_mod_contents(&mut self, span: Span, attrs: Vec<ast::Attribute> ,
150 vis: hir::Visibility, id: ast::NodeId,
152 name: Option<ast::Name>) -> Module {
153 let mut om = Module::new(name);
154 om.where_outer = span;
155 om.where_inner = m.inner;
158 om.stab = self.stability(id);
161 self.visit_item(&**i, None, &mut om);
166 fn visit_view_path(&mut self, path: hir::ViewPath_,
169 please_inline: bool) -> Option<hir::ViewPath_> {
171 hir::ViewPathSimple(dst, base) => {
172 if self.resolve_id(id, Some(dst), false, om, please_inline) {
175 Some(hir::ViewPathSimple(dst, base))
178 hir::ViewPathList(p, paths) => {
179 let mine = paths.into_iter().filter(|path| {
180 !self.resolve_id(path.node.id(), None, false, om,
182 }).collect::<Vec<hir::PathListItem>>();
187 Some(hir::ViewPathList(p, mine))
191 // these are feature gated anyway
192 hir::ViewPathGlob(base) => {
193 if self.resolve_id(id, None, true, om, please_inline) {
196 Some(hir::ViewPathGlob(base))
203 fn resolve_id(&mut self, id: ast::NodeId, renamed: Option<ast::Name>,
204 glob: bool, om: &mut Module, please_inline: bool) -> bool {
205 let tcx = match self.cx.tcx_opt() {
209 let def = tcx.def_map.borrow()[&id].def_id();
210 let def_node_id = match tcx.map.as_local_node_id(def) {
211 Some(n) => n, None => return false
213 let analysis = match self.analysis {
214 Some(analysis) => analysis, None => return false
216 if !please_inline && analysis.public_items.contains(&def) {
219 if !self.view_item_stack.insert(def_node_id) { return false }
221 let ret = match tcx.map.get(def_node_id) {
222 hir_map::NodeItem(it) => {
224 let prev = mem::replace(&mut self.inlining_from_glob, true);
226 hir::ItemMod(ref m) => {
228 self.visit_item(&**i, None, om);
231 hir::ItemEnum(..) => {}
232 _ => { panic!("glob not mapped to a module or enum"); }
234 self.inlining_from_glob = prev;
236 self.visit_item(it, renamed, om);
242 self.view_item_stack.remove(&def_node_id);
246 pub fn visit_item(&mut self, item: &hir::Item,
247 renamed: Option<ast::Name>, om: &mut Module) {
248 debug!("Visiting item {:?}", item);
249 let name = renamed.unwrap_or(item.name);
251 hir::ItemExternCrate(ref p) => {
252 let path = match *p {
254 Some(x) => Some(x.to_string()),
256 om.extern_crates.push(ExternCrate {
260 attrs: item.attrs.clone(),
264 hir::ItemUse(ref vpath) => {
265 let node = vpath.node.clone();
266 let node = if item.vis == hir::Public {
267 let please_inline = item.attrs.iter().any(|item| {
268 match item.meta_item_list() {
270 list.iter().any(|i| &i.name()[..] == "inline")
275 match self.visit_view_path(node, om, item.id, please_inline) {
282 om.imports.push(Import {
285 attrs: item.attrs.clone(),
290 hir::ItemMod(ref m) => {
291 om.mods.push(self.visit_mod_contents(item.span,
298 hir::ItemEnum(ref ed, ref gen) =>
299 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
300 hir::ItemStruct(ref sd, ref gen) =>
301 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
302 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
303 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
304 constness, abi, gen)),
305 hir::ItemTy(ref ty, ref gen) => {
311 attrs: item.attrs.clone(),
314 stab: self.stability(item.id),
318 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
321 mutability: mut_.clone(),
325 attrs: item.attrs.clone(),
328 stab: self.stability(item.id),
332 hir::ItemConst(ref ty, ref exp) => {
338 attrs: item.attrs.clone(),
341 stab: self.stability(item.id),
343 om.constants.push(s);
345 hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
349 items: items.clone(),
350 generics: gen.clone(),
351 bounds: b.iter().cloned().collect(),
353 attrs: item.attrs.clone(),
356 stab: self.stability(item.id),
360 hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref items) => {
364 generics: gen.clone(),
367 items: items.clone(),
368 attrs: item.attrs.clone(),
372 stab: self.stability(item.id),
374 // Don't duplicate impls when inlining glob imports, we'll pick
375 // them up regardless of where they're located.
376 if !self.inlining_from_glob {
380 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
381 let i = DefaultImpl {
383 trait_: trait_ref.clone(),
385 attrs: item.attrs.clone(),
388 // see comment above about ItemImpl
389 if !self.inlining_from_glob {
390 om.def_traits.push(i);
393 hir::ItemForeignMod(ref fm) => {
394 om.foreigns.push(fm.clone());
399 // convert each exported_macro into a doc item
400 fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
403 attrs: def.attrs.clone(),
406 stab: self.stability(def.id),
407 imported_from: def.imported_from,