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::def_id::DefId;
25 use rustc::middle::stability;
32 // looks to me like the first two of these are actually
33 // output parameters, maybe only mutated once; perhaps
34 // better simply to have the visit method return a tuple
37 // also, is there some reason that this doesn't use the 'visit'
38 // framework from syntax?
40 pub struct RustdocVisitor<'a, 'tcx: 'a> {
42 pub attrs: Vec<ast::Attribute>,
43 pub cx: &'a core::DocContext<'a, 'tcx>,
44 pub analysis: Option<&'a core::CrateAnalysis>,
45 view_item_stack: HashSet<ast::NodeId>,
46 inlining_from_glob: bool,
49 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
50 pub fn new(cx: &'a core::DocContext<'a, 'tcx>,
51 analysis: Option<&'a core::CrateAnalysis>) -> RustdocVisitor<'a, 'tcx> {
52 // If the root is reexported, terminate all recursion.
53 let mut stack = HashSet::new();
54 stack.insert(ast::CRATE_NODE_ID);
56 module: Module::new(None),
60 view_item_stack: stack,
61 inlining_from_glob: false,
65 fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
66 self.cx.tcx_opt().and_then(
67 |tcx| stability::lookup(tcx, DefId::local(id)).map(|x| x.clone()))
70 pub fn visit(&mut self, krate: &hir::Crate) {
71 self.attrs = krate.attrs.clone();
73 self.module = self.visit_mod_contents(krate.span,
79 // attach the crate's exported macros to the top-level module:
80 self.module.macros = krate.exported_macros.iter()
81 .map(|def| self.visit_macro(def)).collect();
82 self.module.is_crate = true;
85 pub fn visit_struct_def(&mut self, item: &hir::Item,
86 name: ast::Ident, sd: &hir::StructDef,
87 generics: &hir::Generics) -> Struct {
88 debug!("Visiting struct");
89 let struct_type = struct_type_from_def(&*sd);
92 struct_type: struct_type,
95 stab: self.stability(item.id),
96 attrs: item.attrs.clone(),
97 generics: generics.clone(),
98 fields: sd.fields.clone(),
103 pub fn visit_enum_def(&mut self, it: &hir::Item,
104 name: ast::Ident, def: &hir::EnumDef,
105 params: &hir::Generics) -> Enum {
106 debug!("Visiting enum");
109 variants: def.variants.iter().map(|v| Variant {
111 attrs: v.node.attrs.clone(),
113 stab: self.stability(v.node.id),
115 kind: v.node.kind.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::Ident, 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::Ident>) -> 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::Ident>,
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 if !def.is_local() { return false }
211 let analysis = match self.analysis {
212 Some(analysis) => analysis, None => return false
214 if !please_inline && analysis.public_items.contains(&def.node) {
217 if !self.view_item_stack.insert(def.node) { return false }
219 let ret = match tcx.map.get(def.node) {
220 hir_map::NodeItem(it) => {
222 let prev = mem::replace(&mut self.inlining_from_glob, true);
224 hir::ItemMod(ref m) => {
226 self.visit_item(&**i, None, om);
229 hir::ItemEnum(..) => {}
230 _ => { panic!("glob not mapped to a module or enum"); }
232 self.inlining_from_glob = prev;
234 self.visit_item(it, renamed, om);
240 self.view_item_stack.remove(&id);
244 pub fn visit_item(&mut self, item: &hir::Item,
245 renamed: Option<ast::Ident>, om: &mut Module) {
246 debug!("Visiting item {:?}", item);
247 let name = renamed.unwrap_or(item.ident);
249 hir::ItemExternCrate(ref p) => {
250 let path = match *p {
252 Some(x) => Some(x.to_string()),
254 om.extern_crates.push(ExternCrate {
258 attrs: item.attrs.clone(),
262 hir::ItemUse(ref vpath) => {
263 let node = vpath.node.clone();
264 let node = if item.vis == hir::Public {
265 let please_inline = item.attrs.iter().any(|item| {
266 match item.meta_item_list() {
268 list.iter().any(|i| &i.name()[..] == "inline")
273 match self.visit_view_path(node, om, item.id, please_inline) {
280 om.imports.push(Import {
283 attrs: item.attrs.clone(),
288 hir::ItemMod(ref m) => {
289 om.mods.push(self.visit_mod_contents(item.span,
296 hir::ItemEnum(ref ed, ref gen) =>
297 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
298 hir::ItemStruct(ref sd, ref gen) =>
299 om.structs.push(self.visit_struct_def(item, name, &**sd, gen)),
300 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
301 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
302 constness, abi, gen)),
303 hir::ItemTy(ref ty, ref gen) => {
309 attrs: item.attrs.clone(),
312 stab: self.stability(item.id),
316 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
319 mutability: mut_.clone(),
323 attrs: item.attrs.clone(),
326 stab: self.stability(item.id),
330 hir::ItemConst(ref ty, ref exp) => {
336 attrs: item.attrs.clone(),
339 stab: self.stability(item.id),
341 om.constants.push(s);
343 hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
347 items: items.clone(),
348 generics: gen.clone(),
349 bounds: b.iter().cloned().collect(),
351 attrs: item.attrs.clone(),
354 stab: self.stability(item.id),
358 hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref items) => {
362 generics: gen.clone(),
365 items: items.clone(),
366 attrs: item.attrs.clone(),
370 stab: self.stability(item.id),
372 // Don't duplicate impls when inlining glob imports, we'll pick
373 // them up regardless of where they're located.
374 if !self.inlining_from_glob {
378 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
379 let i = DefaultImpl {
381 trait_: trait_ref.clone(),
383 attrs: item.attrs.clone(),
386 // see comment above about ItemImpl
387 if !self.inlining_from_glob {
388 om.def_traits.push(i);
391 hir::ItemForeignMod(ref fm) => {
392 om.foreigns.push(fm.clone());
397 // convert each exported_macro into a doc item
398 fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
401 attrs: def.attrs.clone(),
404 stab: self.stability(def.id),
405 imported_from: def.imported_from,