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: hir::HirVec<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),
56 attrs: hir::HirVec::new(),
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_stability(tcx, def_id))
72 fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
73 self.cx.tcx_opt().and_then(|tcx| {
74 self.cx.map.opt_local_def_id(id)
75 .and_then(|def_id| stability::lookup_deprecation(tcx, def_id))
79 pub fn visit(&mut self, krate: &hir::Crate) {
80 self.attrs = krate.attrs.clone();
82 self.module = self.visit_mod_contents(krate.span,
88 // attach the crate's exported macros to the top-level module:
89 self.module.macros = krate.exported_macros.iter()
90 .map(|def| self.visit_macro(def)).collect();
91 self.module.is_crate = true;
94 pub fn visit_variant_data(&mut self, item: &hir::Item,
95 name: ast::Name, sd: &hir::VariantData,
96 generics: &hir::Generics) -> Struct {
97 debug!("Visiting struct");
98 let struct_type = struct_type_from_def(&*sd);
101 struct_type: struct_type,
104 stab: self.stability(item.id),
105 depr: self.deprecation(item.id),
106 attrs: item.attrs.clone(),
107 generics: generics.clone(),
108 fields: sd.fields().iter().cloned().collect(),
113 pub fn visit_enum_def(&mut self, it: &hir::Item,
114 name: ast::Name, def: &hir::EnumDef,
115 params: &hir::Generics) -> Enum {
116 debug!("Visiting enum");
119 variants: def.variants.iter().map(|v| Variant {
121 attrs: v.node.attrs.clone(),
122 stab: self.stability(v.node.data.id()),
123 depr: self.deprecation(v.node.data.id()),
124 def: v.node.data.clone(),
128 stab: self.stability(it.id),
129 depr: self.deprecation(it.id),
130 generics: params.clone(),
131 attrs: it.attrs.clone(),
137 pub fn visit_fn(&mut self, item: &hir::Item,
138 name: ast::Name, fd: &hir::FnDecl,
139 unsafety: &hir::Unsafety,
140 constness: hir::Constness,
142 gen: &hir::Generics) -> Function {
143 debug!("Visiting fn");
147 stab: self.stability(item.id),
148 depr: self.deprecation(item.id),
149 attrs: item.attrs.clone(),
153 generics: gen.clone(),
155 constness: constness,
160 pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
161 vis: hir::Visibility, id: ast::NodeId,
163 name: Option<ast::Name>) -> Module {
164 let mut om = Module::new(name);
165 om.where_outer = span;
166 om.where_inner = m.inner;
169 om.stab = self.stability(id);
170 om.depr = self.deprecation(id);
172 for i in &m.item_ids {
173 let item = self.cx.map.expect_item(i.id);
174 self.visit_item(item, None, &mut om);
179 fn visit_view_path(&mut self, path: hir::ViewPath_,
182 please_inline: bool) -> Option<hir::ViewPath_> {
184 hir::ViewPathSimple(dst, base) => {
185 if self.resolve_id(id, Some(dst), false, om, please_inline) {
188 Some(hir::ViewPathSimple(dst, base))
191 hir::ViewPathList(p, paths) => {
192 let mine = paths.into_iter().filter(|path| {
193 !self.resolve_id(path.node.id(), None, false, om,
195 }).collect::<hir::HirVec<hir::PathListItem>>();
200 Some(hir::ViewPathList(p, mine))
204 // these are feature gated anyway
205 hir::ViewPathGlob(base) => {
206 if self.resolve_id(id, None, true, om, please_inline) {
209 Some(hir::ViewPathGlob(base))
216 fn resolve_id(&mut self, id: ast::NodeId, renamed: Option<ast::Name>,
217 glob: bool, om: &mut Module, please_inline: bool) -> bool {
218 let tcx = match self.cx.tcx_opt() {
222 let def = tcx.def_map.borrow()[&id].def_id();
223 let def_node_id = match tcx.map.as_local_node_id(def) {
224 Some(n) => n, None => return false
226 let analysis = match self.analysis {
227 Some(analysis) => analysis, None => return false
229 if !please_inline && analysis.access_levels.is_public(def) {
232 if !self.view_item_stack.insert(def_node_id) { return false }
234 let ret = match tcx.map.get(def_node_id) {
235 hir_map::NodeItem(it) => {
237 let prev = mem::replace(&mut self.inlining_from_glob, true);
239 hir::ItemMod(ref m) => {
240 for i in &m.item_ids {
241 let i = self.cx.map.expect_item(i.id);
242 self.visit_item(i, None, om);
245 hir::ItemEnum(..) => {}
246 _ => { panic!("glob not mapped to a module or enum"); }
248 self.inlining_from_glob = prev;
250 self.visit_item(it, renamed, om);
256 self.view_item_stack.remove(&def_node_id);
260 pub fn visit_item(&mut self, item: &hir::Item,
261 renamed: Option<ast::Name>, om: &mut Module) {
262 debug!("Visiting item {:?}", item);
263 let name = renamed.unwrap_or(item.name);
265 hir::ItemExternCrate(ref p) => {
266 let path = match *p {
268 Some(x) => Some(x.to_string()),
270 om.extern_crates.push(ExternCrate {
274 attrs: item.attrs.clone(),
278 hir::ItemUse(ref vpath) => {
279 let node = vpath.node.clone();
280 let node = if item.vis == hir::Public {
281 let please_inline = item.attrs.iter().any(|item| {
282 match item.meta_item_list() {
284 list.iter().any(|i| &i.name()[..] == "inline")
289 match self.visit_view_path(node, om, item.id, please_inline) {
296 om.imports.push(Import {
299 attrs: item.attrs.clone(),
304 hir::ItemMod(ref m) => {
305 om.mods.push(self.visit_mod_contents(item.span,
312 hir::ItemEnum(ref ed, ref gen) =>
313 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
314 hir::ItemStruct(ref sd, ref gen) =>
315 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
316 hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
317 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
318 constness, abi, gen)),
319 hir::ItemTy(ref ty, ref gen) => {
325 attrs: item.attrs.clone(),
328 stab: self.stability(item.id),
329 depr: self.deprecation(item.id),
333 hir::ItemStatic(ref ty, ref mut_, ref exp) => {
336 mutability: mut_.clone(),
340 attrs: item.attrs.clone(),
343 stab: self.stability(item.id),
344 depr: self.deprecation(item.id),
348 hir::ItemConst(ref ty, ref exp) => {
354 attrs: item.attrs.clone(),
357 stab: self.stability(item.id),
358 depr: self.deprecation(item.id),
360 om.constants.push(s);
362 hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
366 items: items.clone(),
367 generics: gen.clone(),
368 bounds: b.iter().cloned().collect(),
370 attrs: item.attrs.clone(),
373 stab: self.stability(item.id),
374 depr: self.deprecation(item.id),
378 hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref items) => {
382 generics: gen.clone(),
385 items: items.clone(),
386 attrs: item.attrs.clone(),
390 stab: self.stability(item.id),
391 depr: self.deprecation(item.id),
393 // Don't duplicate impls when inlining glob imports, we'll pick
394 // them up regardless of where they're located.
395 if !self.inlining_from_glob {
399 hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
400 let i = DefaultImpl {
402 trait_: trait_ref.clone(),
404 attrs: item.attrs.clone(),
407 // see comment above about ItemImpl
408 if !self.inlining_from_glob {
409 om.def_traits.push(i);
412 hir::ItemForeignMod(ref fm) => {
413 om.foreigns.push(fm.clone());
418 // convert each exported_macro into a doc item
419 fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
420 // Extract the spans of all matchers. They represent the "interface" of the macro.
421 let matchers = def.body.chunks(4).map(|arm| arm[0].get_span()).collect();
425 attrs: def.attrs.clone(),
429 stab: self.stability(def.id),
430 depr: self.deprecation(def.id),
431 imported_from: def.imported_from,