]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/dump_visitor.rs
Appease tidy and fix save-analysis config for dist builds
[rust.git] / src / librustc_save_analysis / dump_visitor.rs
1 // Copyright 2015 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.
4 //
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.
10
11 //! Write the output of rustc's analysis to an implementor of Dump.
12 //!
13 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
14 //! info out from all over the place. We use Def IDs to identify objects. The
15 //! tricky part is getting syntactic (span, source text) and semantic (reference
16 //! Def IDs) information for parts of expressions which the compiler has discarded.
17 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
18 //! path and a reference to `baz`, but we want spans and references for all three
19 //! idents.
20 //!
21 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
22 //! from spans (e.g., the span for `bar` from the above example path).
23 //! DumpVisitor walks the AST and processes it, and an implementor of Dump
24 //! is used for recording the output in a format-agnostic way (see CsvDumper
25 //! for an example).
26
27 use rustc::hir::def::Def as HirDef;
28 use rustc::hir::def_id::DefId;
29 use rustc::hir::map::Node;
30 use rustc::session::Session;
31 use rustc::ty::{self, TyCtxt};
32 use rustc_data_structures::fx::FxHashSet;
33
34 use std::path::Path;
35
36 use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
37 use syntax::parse::token;
38 use syntax::symbol::keywords;
39 use syntax::visit::{self, Visitor};
40 use syntax::print::pprust::{path_to_string, ty_to_string, bounds_to_string, generics_to_string};
41 use syntax::ptr::P;
42 use syntax::codemap::Spanned;
43 use syntax_pos::*;
44
45 use {escape, generated_code, SaveContext, PathCollector, lower_attributes};
46 use json_dumper::{JsonDumper, DumpOutput};
47 use span_utils::SpanUtils;
48 use sig;
49
50 use rls_data::{CratePreludeData, Import, ImportKind, SpanData, Ref, RefKind,
51                Def, DefKind, Relation, RelationKind};
52
53 macro_rules! down_cast_data {
54     ($id:ident, $kind:ident, $sp:expr) => {
55         let $id = if let super::Data::$kind(data) = $id {
56             data
57         } else {
58             span_bug!($sp, "unexpected data kind: {:?}", $id);
59         };
60     };
61 }
62
63 pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> {
64     save_ctxt: SaveContext<'l, 'tcx>,
65     sess: &'l Session,
66     tcx: TyCtxt<'l, 'tcx, 'tcx>,
67     dumper: &'ll mut JsonDumper<O>,
68
69     span: SpanUtils<'l>,
70
71     cur_scope: NodeId,
72
73     // Set of macro definition (callee) spans, and the set
74     // of macro use (callsite) spans. We store these to ensure
75     // we only write one macro def per unique macro definition, and
76     // one macro use per unique callsite span.
77     // mac_defs: HashSet<Span>,
78     macro_calls: FxHashSet<Span>,
79 }
80
81 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
82     pub fn new(save_ctxt: SaveContext<'l, 'tcx>,
83                dumper: &'ll mut JsonDumper<O>)
84                -> DumpVisitor<'l, 'tcx, 'll, O> {
85         let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
86         DumpVisitor {
87             sess: &save_ctxt.tcx.sess,
88             tcx: save_ctxt.tcx,
89             save_ctxt: save_ctxt,
90             dumper: dumper,
91             span: span_utils.clone(),
92             cur_scope: CRATE_NODE_ID,
93             // mac_defs: HashSet::new(),
94             macro_calls: FxHashSet(),
95         }
96     }
97
98     fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
99         where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>)
100     {
101         let parent_scope = self.cur_scope;
102         self.cur_scope = scope_id;
103         f(self);
104         self.cur_scope = parent_scope;
105     }
106
107     fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
108         where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>)
109     {
110         let item_def_id = self.tcx.hir.local_def_id(item_id);
111         if self.tcx.has_typeck_tables(item_def_id) {
112             let tables = self.tcx.typeck_tables_of(item_def_id);
113             let old_tables = self.save_ctxt.tables;
114             self.save_ctxt.tables = tables;
115             f(self);
116             self.save_ctxt.tables = old_tables;
117         } else {
118             f(self);
119         }
120     }
121
122     fn span_from_span(&self, span: Span) -> SpanData {
123         self.save_ctxt.span_from_span(span)
124     }
125
126     pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
127         let source_file = self.tcx.sess.local_crate_source_file.as_ref();
128         let crate_root = source_file.map(|source_file| {
129             let source_file = Path::new(source_file);
130             match source_file.file_name() {
131                 Some(_) => source_file.parent().unwrap().display().to_string(),
132                 None => source_file.display().to_string(),
133             }
134         });
135
136         let data = CratePreludeData {
137             crate_name: name.into(),
138             crate_root: crate_root.unwrap_or("<no source>".to_owned()),
139             external_crates: self.save_ctxt.get_external_crates(),
140             span: self.span_from_span(krate.span),
141         };
142
143         self.dumper.crate_prelude(data);
144     }
145
146     // Return all non-empty prefixes of a path.
147     // For each prefix, we return the span for the last segment in the prefix and
148     // a str representation of the entire prefix.
149     fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
150         let spans = self.span.spans_for_path_segments(path);
151         let segments = &path.segments[if path.is_global() { 1 } else { 0 }..];
152
153         // Paths to enums seem to not match their spans - the span includes all the
154         // variants too. But they seem to always be at the end, so I hope we can cope with
155         // always using the first ones. So, only error out if we don't have enough spans.
156         // What could go wrong...?
157         if spans.len() < segments.len() {
158             if generated_code(path.span) {
159                 return vec![];
160             }
161             error!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
162                    path_to_string(path),
163                    spans.len(),
164                    segments.len());
165             for s in &spans {
166                 let loc = self.sess.codemap().lookup_char_pos(s.lo);
167                 error!("    '{}' in {}, line {}",
168                        self.span.snippet(*s),
169                        loc.file.name,
170                        loc.line);
171             }
172             error!("    master span: {:?}: `{}`", path.span, self.span.snippet(path.span));
173             return vec![];
174         }
175
176         let mut result: Vec<(Span, String)> = vec![];
177
178         let mut segs = vec![];
179         for (i, (seg, span)) in segments.iter().zip(&spans).enumerate() {
180             segs.push(seg.clone());
181             let sub_path = ast::Path {
182                 span: *span, // span for the last segment
183                 segments: segs,
184             };
185             let qualname = if i == 0 && path.is_global() {
186                 format!("::{}", path_to_string(&sub_path))
187             } else {
188                 path_to_string(&sub_path)
189             };
190             result.push((*span, qualname));
191             segs = sub_path.segments;
192         }
193
194         result
195     }
196
197     fn write_sub_paths(&mut self, path: &ast::Path) {
198         let sub_paths = self.process_path_prefixes(path);
199         for (span, _) in sub_paths {
200             let span = self.span_from_span(span);
201             self.dumper.dump_ref(Ref {
202                 kind: RefKind::Mod,
203                 span,
204                 ref_id: ::null_id(),
205             });
206         }
207     }
208
209     // As write_sub_paths, but does not process the last ident in the path (assuming it
210     // will be processed elsewhere). See note on write_sub_paths about global.
211     fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
212         let sub_paths = self.process_path_prefixes(path);
213         let len = sub_paths.len();
214         if len <= 1 {
215             return;
216         }
217
218         for (span, _) in sub_paths.into_iter().take(len - 1) {
219             let span = self.span_from_span(span);
220             self.dumper.dump_ref(Ref {
221                 kind: RefKind::Mod,
222                 span,
223                 ref_id: ::null_id(),
224             });
225         }
226     }
227
228     // As write_sub_paths, but expects a path of the form module_path::trait::method
229     // Where trait could actually be a struct too.
230     fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
231         let sub_paths = self.process_path_prefixes(path);
232         let len = sub_paths.len();
233         if len <= 1 {
234             return;
235         }
236         let sub_paths = &sub_paths[.. (len-1)];
237
238         // write the trait part of the sub-path
239         let (ref span, _) = sub_paths[len-2];
240         let span = self.span_from_span(*span);
241         self.dumper.dump_ref(Ref {
242             kind: RefKind::Type,
243             ref_id: ::null_id(),
244             span,
245         });
246
247         // write the other sub-paths
248         if len <= 2 {
249             return;
250         }
251         let sub_paths = &sub_paths[..len-2];
252         for &(ref span, _) in sub_paths {
253             let span = self.span_from_span(*span);
254             self.dumper.dump_ref(Ref {
255                 kind: RefKind::Mod,
256                 span,
257                 ref_id: ::null_id(),
258             });
259         }
260     }
261
262     fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
263         match self.save_ctxt.get_path_def(ref_id) {
264             HirDef::PrimTy(..) | HirDef::SelfTy(..) | HirDef::Err => None,
265             def => Some(def.def_id()),
266         }
267     }
268
269     fn process_def_kind(&mut self,
270                         ref_id: NodeId,
271                         span: Span,
272                         sub_span: Option<Span>,
273                         def_id: DefId) {
274         if self.span.filter_generated(sub_span, span) {
275             return;
276         }
277
278         let def = self.save_ctxt.get_path_def(ref_id);
279         match def {
280             HirDef::Mod(_) => {
281                 let span = self.span_from_span(sub_span.expect("No span found for mod ref"));
282                 self.dumper.dump_ref(Ref {
283                     kind: RefKind::Mod,
284                     span,
285                     ref_id: ::id_from_def_id(def_id),
286                 });
287             }
288             HirDef::Struct(..) |
289             HirDef::Variant(..) |
290             HirDef::Union(..) |
291             HirDef::Enum(..) |
292             HirDef::TyAlias(..) |
293             HirDef::Trait(_) => {
294                 let span = self.span_from_span(sub_span.expect("No span found for type ref"));
295                 self.dumper.dump_ref(Ref {
296                     kind: RefKind::Type,
297                     span,
298                     ref_id: ::id_from_def_id(def_id),
299                 });
300             }
301             HirDef::Static(..) |
302             HirDef::Const(..) |
303             HirDef::StructCtor(..) |
304             HirDef::VariantCtor(..) => {
305                 let span = self.span_from_span(sub_span.expect("No span found for var ref"));
306                 self.dumper.dump_ref(Ref {
307                     kind: RefKind::Variable,
308                     span,
309                     ref_id: ::id_from_def_id(def_id),
310                 });
311             }
312             HirDef::Fn(..) => {
313                 let span = self.span_from_span(sub_span.expect("No span found for fn ref"));
314                 self.dumper.dump_ref(Ref {
315                     kind: RefKind::Function,
316                     span,
317                     ref_id: ::id_from_def_id(def_id),
318                 });
319             }
320             // With macros 2.0, we can legitimately get a ref to a macro, but
321             // we don't handle it properly for now (FIXME).
322             HirDef::Macro(..) => {}
323             HirDef::Local(..) |
324             HirDef::Upvar(..) |
325             HirDef::SelfTy(..) |
326             HirDef::Label(_) |
327             HirDef::TyParam(..) |
328             HirDef::Method(..) |
329             HirDef::AssociatedTy(..) |
330             HirDef::AssociatedConst(..) |
331             HirDef::PrimTy(_) |
332             HirDef::GlobalAsm(_) |
333             HirDef::Err => {
334                span_bug!(span,
335                          "process_def_kind for unexpected item: {:?}",
336                          def);
337             }
338         }
339     }
340
341     fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
342         for arg in formals {
343             self.visit_pat(&arg.pat);
344             let mut collector = PathCollector::new();
345             collector.visit_pat(&arg.pat);
346             let span_utils = self.span.clone();
347             for &(id, ref p, ..) in &collector.collected_paths {
348                 let typ = match self.save_ctxt.tables.node_types.get(&id) {
349                     Some(s) => s.to_string(),
350                     None => continue,
351                 };
352                 // get the span only for the name of the variable (I hope the path is only ever a
353                 // variable name, but who knows?)
354                 let sub_span = span_utils.span_for_last_ident(p.span);
355                 if !self.span.filter_generated(sub_span, p.span) {
356                     let id = ::id_from_node_id(id, &self.save_ctxt);
357                     let span = self.span_from_span(sub_span.expect("No span found for variable"));
358
359                     self.dumper.dump_def(false, Def {
360                         kind: DefKind::Local,
361                         id,
362                         span,
363                         name: path_to_string(p),
364                         qualname: format!("{}::{}", qualname, path_to_string(p)),
365                         value: typ,
366                         parent: None,
367                         children: vec![],
368                         decl_id: None,
369                         docs: String::new(),
370                         sig: None,
371                         attributes:vec![],
372                     });
373                 }
374             }
375         }
376     }
377
378     fn process_method(&mut self,
379                       sig: &'l ast::MethodSig,
380                       body: Option<&'l ast::Block>,
381                       id: ast::NodeId,
382                       name: ast::Ident,
383                       vis: ast::Visibility,
384                       span: Span) {
385         debug!("process_method: {}:{}", id, name);
386
387         if let Some(mut method_data) = self.save_ctxt.get_method_data(id, name.name, span) {
388
389             let sig_str = ::make_signature(&sig.decl, &sig.generics);
390             if body.is_some() {
391                 self.nest_tables(id, |v| {
392                     v.process_formals(&sig.decl.inputs, &method_data.qualname)
393                 });
394             }
395
396             self.process_generic_params(&sig.generics, span, &method_data.qualname, id);
397
398             method_data.value = sig_str;
399             method_data.sig = sig::method_signature(id, name, sig, &self.save_ctxt);
400             self.dumper.dump_def(vis == ast::Visibility::Public, method_data);
401         }
402
403         // walk arg and return types
404         for arg in &sig.decl.inputs {
405             self.visit_ty(&arg.ty);
406         }
407
408         if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
409             self.visit_ty(ret_ty);
410         }
411
412         // walk the fn body
413         if let Some(body) = body {
414             self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
415         }
416     }
417
418     fn process_trait_ref(&mut self, trait_ref: &'l ast::TraitRef) {
419         let trait_ref_data = self.save_ctxt.get_trait_ref_data(trait_ref);
420         if let Some(trait_ref_data) = trait_ref_data {
421             self.dumper.dump_ref(trait_ref_data);
422         }
423         self.process_path(trait_ref.ref_id, &trait_ref.path);
424     }
425
426     fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
427         let field_data = self.save_ctxt.get_field_data(field, parent_id);
428         if let Some(field_data) = field_data {
429             self.dumper.dump_def(field.vis == ast::Visibility::Public, field_data);
430         }
431     }
432
433     // Dump generic params bindings, then visit_generics
434     fn process_generic_params(&mut self,
435                               generics: &'l ast::Generics,
436                               full_span: Span,
437                               prefix: &str,
438                               id: NodeId) {
439         // We can't only use visit_generics since we don't have spans for param
440         // bindings, so we reparse the full_span to get those sub spans.
441         // However full span is the entire enum/fn/struct block, so we only want
442         // the first few to match the number of generics we're looking for.
443         let param_sub_spans = self.span.spans_for_ty_params(full_span,
444                                                             (generics.ty_params.len() as isize));
445         for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans) {
446             let name = escape(self.span.snippet(param_ss));
447             // Append $id to name to make sure each one is unique
448             let qualname = format!("{}::{}${}",
449                                    prefix,
450                                    name,
451                                    id);
452             if !self.span.filter_generated(Some(param_ss), full_span) {
453                 let id = ::id_from_node_id(param.id, &self.save_ctxt);
454                 let span = self.span_from_span(param_ss);
455
456                 self.dumper.dump_def(false, Def {
457                     kind: DefKind::Type,
458                     id,
459                     span,
460                     name,
461                     qualname,
462                     value: String::new(),
463                     parent: None,
464                     children: vec![],
465                     decl_id: None,
466                     docs: String::new(),
467                     sig: None,
468                     attributes: vec![],
469                 });
470             }
471         }
472         self.visit_generics(generics);
473     }
474
475     fn process_fn(&mut self,
476                   item: &'l ast::Item,
477                   decl: &'l ast::FnDecl,
478                   ty_params: &'l ast::Generics,
479                   body: &'l ast::Block) {
480         if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
481             down_cast_data!(fn_data, DefData, item.span);
482             self.nest_tables(item.id, |v| v.process_formals(&decl.inputs, &fn_data.qualname));
483             self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
484             self.dumper.dump_def(item.vis == ast::Visibility::Public, fn_data);
485         }
486
487         for arg in &decl.inputs {
488             self.visit_ty(&arg.ty);
489         }
490
491         if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
492             self.visit_ty(&ret_ty);
493         }
494
495         self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
496     }
497
498     fn process_static_or_const_item(&mut self,
499                                     item: &'l ast::Item,
500                                     typ: &'l ast::Ty,
501                                     expr: &'l ast::Expr) {
502         if let Some(var_data) = self.save_ctxt.get_item_data(item) {
503             down_cast_data!(var_data, DefData, item.span);
504             self.dumper.dump_def(item.vis == ast::Visibility::Public, var_data);
505         }
506         self.visit_ty(&typ);
507         self.visit_expr(expr);
508     }
509
510     fn process_assoc_const(&mut self,
511                            id: ast::NodeId,
512                            name: ast::Name,
513                            span: Span,
514                            typ: &'l ast::Ty,
515                            expr: Option<&'l ast::Expr>,
516                            parent_id: DefId,
517                            vis: ast::Visibility,
518                            attrs: &'l [Attribute]) {
519         let qualname = format!("::{}", self.tcx.node_path_str(id));
520
521         let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
522
523         if !self.span.filter_generated(sub_span, span) {
524             let sig = sig::assoc_const_signature(id, name, typ, expr, &self.save_ctxt);
525             let id = ::id_from_node_id(id, &self.save_ctxt);
526             let span = self.span_from_span(sub_span.expect("No span found for variable"));
527
528             self.dumper.dump_def(vis == ast::Visibility::Public, Def {
529                 kind: DefKind::Const,
530                 id,
531                 span,
532                 name: name.to_string(),
533                 qualname,
534                 value: ty_to_string(&typ),
535                 parent: Some(::id_from_def_id(parent_id)),
536                 children: vec![],
537                 decl_id: None,
538                 docs: self.save_ctxt.docs_for_attrs(attrs),
539                 sig,
540                 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
541             });
542         }
543
544         // walk type and init value
545         self.visit_ty(typ);
546         if let Some(expr) = expr {
547             self.visit_expr(expr);
548         }
549     }
550
551     // FIXME tuple structs should generate tuple-specific data.
552     fn process_struct(&mut self,
553                       item: &'l ast::Item,
554                       def: &'l ast::VariantData,
555                       ty_params: &'l ast::Generics) {
556         let name = item.ident.to_string();
557         let qualname = format!("::{}", self.tcx.node_path_str(item.id));
558
559         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
560         let (value, fields) =
561             if let ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) = item.node
562         {
563             let include_priv_fields = !self.save_ctxt.config.pub_only;
564             let fields_str = fields
565                 .iter()
566                 .enumerate()
567                 .filter_map(|(i, f)| {
568                      if include_priv_fields || f.vis == ast::Visibility::Public {
569                          f.ident.map(|i| i.to_string()).or_else(|| Some(i.to_string()))
570                      } else {
571                          None
572                      }
573                 })
574                 .collect::<Vec<_>>()
575                 .join(", ");
576             let value = format!("{} {{ {} }}", name, fields_str);
577             (value, fields.iter().map(|f| ::id_from_node_id(f.id, &self.save_ctxt)).collect())
578         } else {
579             (String::new(), vec![])
580         };
581
582         if !self.span.filter_generated(sub_span, item.span) {
583             let span = self.span_from_span(sub_span.expect("No span found for struct"));
584             self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
585                 kind: DefKind::Struct,
586                 id: ::id_from_node_id(item.id, &self.save_ctxt),
587                 span,
588                 name,
589                 qualname: qualname.clone(),
590                 value,
591                 parent: None,
592                 children: fields,
593                 decl_id: None,
594                 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
595                 sig: sig::item_signature(item, &self.save_ctxt),
596                 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
597             });
598         }
599
600         for field in def.fields() {
601             self.process_struct_field_def(field, item.id);
602             self.visit_ty(&field.ty);
603         }
604
605         self.process_generic_params(ty_params, item.span, &qualname, item.id);
606     }
607
608     fn process_enum(&mut self,
609                     item: &'l ast::Item,
610                     enum_definition: &'l ast::EnumDef,
611                     ty_params: &'l ast::Generics) {
612         let enum_data = self.save_ctxt.get_item_data(item);
613         let enum_data = match enum_data {
614             None => return,
615             Some(data) => data,
616         };
617         down_cast_data!(enum_data, DefData, item.span);
618
619         for variant in &enum_definition.variants {
620             let name = variant.node.name.name.to_string();
621             let mut qualname = enum_data.qualname.clone();
622             qualname.push_str("::");
623             qualname.push_str(&name);
624
625             match variant.node.data {
626                 ast::VariantData::Struct(ref fields, _) => {
627                     let sub_span = self.span.span_for_first_ident(variant.span);
628                     let fields_str = fields.iter()
629                                            .enumerate()
630                                            .map(|(i, f)| f.ident.map(|i| i.to_string())
631                                                           .unwrap_or(i.to_string()))
632                                            .collect::<Vec<_>>()
633                                            .join(", ");
634                     let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
635                     if !self.span.filter_generated(sub_span, variant.span) {
636                         let span = self.span_from_span(
637                             sub_span.expect("No span found for struct variant"));
638                         let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
639                         let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
640
641                         self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
642                             kind: DefKind::Struct,
643                             id,
644                             span,
645                             name,
646                             qualname,
647                             value,
648                             parent,
649                             children: vec![],
650                             decl_id: None,
651                             docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
652                             sig: sig::variant_signature(variant, &self.save_ctxt),
653                             attributes: lower_attributes(variant.node.attrs.clone(),
654                                                          &self.save_ctxt),
655                         });
656                     }
657                 }
658                 ref v => {
659                     let sub_span = self.span.span_for_first_ident(variant.span);
660                     let mut value = format!("{}::{}", enum_data.name, name);
661                     if let &ast::VariantData::Tuple(ref fields, _) = v {
662                         value.push('(');
663                         value.push_str(&fields.iter()
664                                               .map(|f| ty_to_string(&f.ty))
665                                               .collect::<Vec<_>>()
666                                               .join(", "));
667                         value.push(')');
668                     }
669                     if !self.span.filter_generated(sub_span, variant.span) {
670                         let span =
671                             self.span_from_span(sub_span.expect("No span found for tuple variant"));
672                         let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
673                         let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
674
675                         self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
676                             kind: DefKind::Tuple,
677                             id,
678                             span,
679                             name,
680                             qualname,
681                             value,
682                             parent,
683                             children: vec![],
684                             decl_id: None,
685                             docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
686                             sig: sig::variant_signature(variant, &self.save_ctxt),
687                             attributes: lower_attributes(variant.node.attrs.clone(),
688                                                          &self.save_ctxt),
689                         });
690                     }
691                 }
692             }
693
694
695             for field in variant.node.data.fields() {
696                 self.process_struct_field_def(field, variant.node.data.id());
697                 self.visit_ty(&field.ty);
698             }
699         }
700         self.process_generic_params(ty_params, item.span, &enum_data.qualname, item.id);
701         self.dumper.dump_def(item.vis == ast::Visibility::Public, enum_data);
702     }
703
704     fn process_impl(&mut self,
705                     item: &'l ast::Item,
706                     type_parameters: &'l ast::Generics,
707                     trait_ref: &'l Option<ast::TraitRef>,
708                     typ: &'l ast::Ty,
709                     impl_items: &'l [ast::ImplItem]) {
710         if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
711             down_cast_data!(impl_data, RelationData, item.span);
712             self.dumper.dump_relation(impl_data);
713         }
714         self.visit_ty(&typ);
715         if let &Some(ref trait_ref) = trait_ref {
716             self.process_path(trait_ref.ref_id, &trait_ref.path);
717         }
718         self.process_generic_params(type_parameters, item.span, "", item.id);
719         for impl_item in impl_items {
720             let map = &self.tcx.hir;
721             self.process_impl_item(impl_item, map.local_def_id(item.id));
722         }
723     }
724
725     fn process_trait(&mut self,
726                      item: &'l ast::Item,
727                      generics: &'l ast::Generics,
728                      trait_refs: &'l ast::TyParamBounds,
729                      methods: &'l [ast::TraitItem]) {
730         let name = item.ident.to_string();
731         let qualname = format!("::{}", self.tcx.node_path_str(item.id));
732         let mut val = name.clone();
733         if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
734             val.push_str(&generics_to_string(generics));
735         }
736         if !trait_refs.is_empty() {
737             val.push_str(": ");
738             val.push_str(&bounds_to_string(trait_refs));
739         }
740         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
741         if !self.span.filter_generated(sub_span, item.span) {
742             let id = ::id_from_node_id(item.id, &self.save_ctxt);
743             let span = self.span_from_span(sub_span.expect("No span found for trait"));
744             let children =
745                 methods.iter().map(|i| ::id_from_node_id(i.id, &self.save_ctxt)).collect();
746             self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
747                 kind: DefKind::Trait,
748                 id,
749                 span,
750                 name,
751                 qualname: qualname.clone(),
752                 value: val,
753                 parent: None,
754                 children,
755                 decl_id: None,
756                 docs: self.save_ctxt.docs_for_attrs(&item.attrs),
757                 sig: sig::item_signature(item, &self.save_ctxt),
758                 attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
759             });
760         }
761
762         // super-traits
763         for super_bound in trait_refs.iter() {
764             let trait_ref = match *super_bound {
765                 ast::TraitTyParamBound(ref trait_ref, _) => {
766                     trait_ref
767                 }
768                 ast::RegionTyParamBound(..) => {
769                     continue;
770                 }
771             };
772
773             let trait_ref = &trait_ref.trait_ref;
774             if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
775                 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
776                 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
777                     let span = self.span_from_span(sub_span.expect("No span found for trait ref"));
778                     self.dumper.dump_ref(Ref {
779                         kind: RefKind::Type,
780                         span,
781                         ref_id: ::id_from_def_id(id),
782                     });
783                 }
784
785                 if !self.span.filter_generated(sub_span, trait_ref.path.span) {
786                     let sub_span = self.span_from_span(sub_span.expect("No span for inheritance"));
787                     self.dumper.dump_relation(Relation {
788                         kind: RelationKind::SuperTrait,
789                         span: sub_span,
790                         from: ::id_from_def_id(id),
791                         to: ::id_from_node_id(item.id, &self.save_ctxt),
792                     });
793                 }
794             }
795         }
796
797         // walk generics and methods
798         self.process_generic_params(generics, item.span, &qualname, item.id);
799         for method in methods {
800             let map = &self.tcx.hir;
801             self.process_trait_item(method, map.local_def_id(item.id))
802         }
803     }
804
805     // `item` is the module in question, represented as an item.
806     fn process_mod(&mut self, item: &ast::Item) {
807         if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
808             down_cast_data!(mod_data, DefData, item.span);
809             self.dumper.dump_def(item.vis == ast::Visibility::Public, mod_data);
810         }
811     }
812
813     fn process_path(&mut self, id: NodeId, path: &ast::Path) {
814         let path_data = self.save_ctxt.get_path_data(id, path);
815         if generated_code(path.span) && path_data.is_none() {
816             return;
817         }
818
819         let path_data = match path_data {
820             Some(pd) => pd,
821             None => {
822                 return;
823             }
824         };
825
826         self.dumper.dump_ref(path_data);
827
828         // Modules or types in the path prefix.
829         match self.save_ctxt.get_path_def(id) {
830             HirDef::Method(did) => {
831                 let ti = self.tcx.associated_item(did);
832                 if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
833                     self.write_sub_path_trait_truncated(path);
834                 }
835             }
836             HirDef::Fn(..) |
837             HirDef::Const(..) |
838             HirDef::Static(..) |
839             HirDef::StructCtor(..) |
840             HirDef::VariantCtor(..) |
841             HirDef::AssociatedConst(..) |
842             HirDef::Local(..) |
843             HirDef::Upvar(..) |
844             HirDef::Struct(..) |
845             HirDef::Union(..) |
846             HirDef::Variant(..) |
847             HirDef::TyAlias(..) |
848             HirDef::AssociatedTy(..) => self.write_sub_paths_truncated(path),
849             _ => {}
850         }
851     }
852
853     fn process_struct_lit(&mut self,
854                           ex: &'l ast::Expr,
855                           path: &'l ast::Path,
856                           fields: &'l [ast::Field],
857                           variant: &'l ty::VariantDef,
858                           base: &'l Option<P<ast::Expr>>) {
859         self.write_sub_paths_truncated(path);
860
861         if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
862             down_cast_data!(struct_lit_data, RefData, ex.span);
863             if !generated_code(ex.span) {
864                 self.dumper.dump_ref(struct_lit_data);
865             }
866
867             for field in fields {
868                 if let Some(field_data) = self.save_ctxt
869                                               .get_field_ref_data(field, variant) {
870                     self.dumper.dump_ref(field_data);
871                 }
872
873                 self.visit_expr(&field.expr)
874             }
875         }
876
877         walk_list!(self, visit_expr, base);
878     }
879
880     fn process_method_call(&mut self, ex: &'l ast::Expr, args: &'l [P<ast::Expr>]) {
881         if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
882             down_cast_data!(mcd, RefData, ex.span);
883             if !generated_code(ex.span) {
884                 self.dumper.dump_ref(mcd);
885             }
886         }
887
888         // walk receiver and args
889         walk_list!(self, visit_expr, args);
890     }
891
892     fn process_pat(&mut self, p: &'l ast::Pat) {
893         match p.node {
894             PatKind::Struct(ref _path, ref fields, _) => {
895                 // FIXME do something with _path?
896                 let adt = match self.save_ctxt.tables.node_id_to_type_opt(p.id) {
897                     Some(ty) => ty.ty_adt_def().unwrap(),
898                     None => {
899                         visit::walk_pat(self, p);
900                         return;
901                     }
902                 };
903                 let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
904
905                 for &Spanned { node: ref field, span } in fields {
906                     let sub_span = self.span.span_for_first_ident(span);
907                     if let Some(f) = variant.find_field_named(field.ident.name) {
908                         if !self.span.filter_generated(sub_span, span) {
909                             let span =
910                                 self.span_from_span(sub_span.expect("No span fund for var ref"));
911                             self.dumper.dump_ref(Ref {
912                                 kind: RefKind::Variable,
913                                 span,
914                                 ref_id: ::id_from_def_id(f.did),
915                             });
916                         }
917                     }
918                     self.visit_pat(&field.pat);
919                 }
920             }
921             _ => visit::walk_pat(self, p),
922         }
923     }
924
925
926     fn process_var_decl(&mut self, p: &'l ast::Pat, value: String) {
927         // The local could declare multiple new vars, we must walk the
928         // pattern and collect them all.
929         let mut collector = PathCollector::new();
930         collector.visit_pat(&p);
931         self.visit_pat(&p);
932
933         for &(id, ref p, immut) in &collector.collected_paths {
934             let mut value = match immut {
935                 ast::Mutability::Immutable => value.to_string(),
936                 _ => String::new(),
937             };
938             let typ = match self.save_ctxt.tables.node_types.get(&id) {
939                 Some(typ) => {
940                     let typ = typ.to_string();
941                     if !value.is_empty() {
942                         value.push_str(": ");
943                     }
944                     value.push_str(&typ);
945                     typ
946                 }
947                 None => String::new(),
948             };
949
950             // Get the span only for the name of the variable (I hope the path
951             // is only ever a variable name, but who knows?).
952             let sub_span = self.span.span_for_last_ident(p.span);
953             // Rust uses the id of the pattern for var lookups, so we'll use it too.
954             if !self.span.filter_generated(sub_span, p.span) {
955                 let qualname = format!("{}${}", path_to_string(p), id);
956                 let id = ::id_from_node_id(id, &self.save_ctxt);
957                 let span = self.span_from_span(sub_span.expect("No span found for variable"));
958
959                 self.dumper.dump_def(false, Def {
960                     kind: DefKind::Local,
961                     id,
962                     span,
963                     name: path_to_string(p),
964                     qualname,
965                     value: typ,
966                     parent: None,
967                     children: vec![],
968                     decl_id: None,
969                     docs: String::new(),
970                     sig: None,
971                     attributes:vec![],
972                 });
973             }
974         }
975     }
976
977     /// Extract macro use and definition information from the AST node defined
978     /// by the given NodeId, using the expansion information from the node's
979     /// span.
980     ///
981     /// If the span is not macro-generated, do nothing, else use callee and
982     /// callsite spans to record macro definition and use data, using the
983     /// mac_uses and mac_defs sets to prevent multiples.
984     fn process_macro_use(&mut self, span: Span) {
985         let source_span = span.source_callsite();
986         if self.macro_calls.contains(&source_span) {
987             return;
988         }
989         self.macro_calls.insert(source_span);
990
991         let data = match self.save_ctxt.get_macro_use_data(span) {
992             None => return,
993             Some(data) => data,
994         };
995
996         self.dumper.macro_use(data);
997
998         // FIXME write the macro def
999         // let mut hasher = DefaultHasher::new();
1000         // data.callee_span.hash(&mut hasher);
1001         // let hash = hasher.finish();
1002         // let qualname = format!("{}::{}", data.name, hash);
1003         // Don't write macro definition for imported macros
1004         // if !self.mac_defs.contains(&data.callee_span)
1005         //     && !data.imported {
1006         //     self.mac_defs.insert(data.callee_span);
1007         //     if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
1008         //         self.dumper.macro_data(MacroData {
1009         //             span: sub_span,
1010         //             name: data.name.clone(),
1011         //             qualname: qualname.clone(),
1012         //             // FIXME where do macro docs come from?
1013         //             docs: String::new(),
1014         //         }.lower(self.tcx));
1015         //     }
1016         // }
1017     }
1018
1019     fn process_trait_item(&mut self, trait_item: &'l ast::TraitItem, trait_id: DefId) {
1020         self.process_macro_use(trait_item.span);
1021         match trait_item.node {
1022             ast::TraitItemKind::Const(ref ty, ref expr) => {
1023                 self.process_assoc_const(trait_item.id,
1024                                          trait_item.ident.name,
1025                                          trait_item.span,
1026                                          &ty,
1027                                          expr.as_ref().map(|e| &**e),
1028                                          trait_id,
1029                                          ast::Visibility::Public,
1030                                          &trait_item.attrs);
1031             }
1032             ast::TraitItemKind::Method(ref sig, ref body) => {
1033                 self.process_method(sig,
1034                                     body.as_ref().map(|x| &**x),
1035                                     trait_item.id,
1036                                     trait_item.ident,
1037                                     ast::Visibility::Public,
1038                                     trait_item.span);
1039             }
1040             ast::TraitItemKind::Type(ref bounds, ref default_ty) => {
1041                 // FIXME do something with _bounds (for type refs)
1042                 let name = trait_item.ident.name.to_string();
1043                 let qualname = format!("::{}", self.tcx.node_path_str(trait_item.id));
1044                 let sub_span = self.span.sub_span_after_keyword(trait_item.span, keywords::Type);
1045
1046                 if !self.span.filter_generated(sub_span, trait_item.span) {
1047                     let span = self.span_from_span(sub_span.expect("No span found for assoc type"));
1048                     let id = ::id_from_node_id(trait_item.id, &self.save_ctxt);
1049
1050                     self.dumper.dump_def(true, Def {
1051                         kind: DefKind::Type,
1052                         id,
1053                         span,
1054                         name,
1055                         qualname,
1056                         value: self.span.snippet(trait_item.span),
1057                         parent: Some(::id_from_def_id(trait_id)),
1058                         children: vec![],
1059                         decl_id: None,
1060                         docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1061                         sig: sig::assoc_type_signature(trait_item.id,
1062                                                        trait_item.ident,
1063                                                        Some(bounds),
1064                                                        default_ty.as_ref().map(|ty| &**ty),
1065                                                        &self.save_ctxt),
1066                         attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1067                     });
1068                 }
1069
1070                 if let &Some(ref default_ty) = default_ty {
1071                     self.visit_ty(default_ty)
1072                 }
1073             }
1074             ast::TraitItemKind::Macro(_) => {}
1075         }
1076     }
1077
1078     fn process_impl_item(&mut self, impl_item: &'l ast::ImplItem, impl_id: DefId) {
1079         self.process_macro_use(impl_item.span);
1080         match impl_item.node {
1081             ast::ImplItemKind::Const(ref ty, ref expr) => {
1082                 self.process_assoc_const(impl_item.id,
1083                                          impl_item.ident.name,
1084                                          impl_item.span,
1085                                          &ty,
1086                                          Some(expr),
1087                                          impl_id,
1088                                          impl_item.vis.clone(),
1089                                          &impl_item.attrs);
1090             }
1091             ast::ImplItemKind::Method(ref sig, ref body) => {
1092                 self.process_method(sig,
1093                                     Some(body),
1094                                     impl_item.id,
1095                                     impl_item.ident,
1096                                     impl_item.vis.clone(),
1097                                     impl_item.span);
1098             }
1099             ast::ImplItemKind::Type(ref ty) => {
1100                 // FIXME uses of the assoc type should ideally point to this
1101                 // 'def' and the name here should be a ref to the def in the
1102                 // trait.
1103                 self.visit_ty(ty)
1104             }
1105             ast::ImplItemKind::Macro(_) => {}
1106         }
1107     }
1108 }
1109
1110 impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, O> {
1111     fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1112         // Since we handle explicit modules ourselves in visit_item, this should
1113         // only get called for the root module of a crate.
1114         assert_eq!(id, ast::CRATE_NODE_ID);
1115
1116         let qualname = format!("::{}", self.tcx.node_path_str(id));
1117
1118         let cm = self.tcx.sess.codemap();
1119         let filename = cm.span_to_filename(span);
1120         let data_id = ::id_from_node_id(id, &self.save_ctxt);
1121         let children = m.items.iter().map(|i| ::id_from_node_id(i.id, &self.save_ctxt)).collect();
1122         let span = self.span_from_span(span);
1123
1124         self.dumper.dump_def(true, Def {
1125             kind: DefKind::Mod,
1126             id: data_id,
1127             name: String::new(),
1128             qualname,
1129             span,
1130             value: filename,
1131             children,
1132             parent: None,
1133             decl_id: None,
1134             docs: self.save_ctxt.docs_for_attrs(attrs),
1135             sig: None,
1136             attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1137         });
1138         self.nest_scope(id, |v| visit::walk_mod(v, m));
1139     }
1140
1141     fn visit_item(&mut self, item: &'l ast::Item) {
1142         use syntax::ast::ItemKind::*;
1143         self.process_macro_use(item.span);
1144         match item.node {
1145             Use(ref use_item) => {
1146                 match use_item.node {
1147                     ast::ViewPathSimple(ident, ref path) => {
1148                         let sub_span = self.span.span_for_last_ident(path.span);
1149                         let mod_id = match self.lookup_def_id(item.id) {
1150                             Some(def_id) => {
1151                                 self.process_def_kind(item.id, path.span, sub_span, def_id);
1152                                 Some(def_id)
1153                             }
1154                             None => None,
1155                         };
1156
1157                         // 'use' always introduces an alias, if there is not an explicit
1158                         // one, there is an implicit one.
1159                         let sub_span = match self.span.sub_span_after_keyword(use_item.span,
1160                                                                               keywords::As) {
1161                             Some(sub_span) => Some(sub_span),
1162                             None => sub_span,
1163                         };
1164
1165                         if !self.span.filter_generated(sub_span, path.span) {
1166                             let span =
1167                                 self.span_from_span(sub_span.expect("No span found for use"));
1168                             self.dumper.import(item.vis == ast::Visibility::Public, Import {
1169                                 kind: ImportKind::Use,
1170                                 ref_id: mod_id.map(|id| ::id_from_def_id(id)),
1171                                 span,
1172                                 name: ident.to_string(),
1173                                 value: String::new(),
1174                             });
1175                         }
1176                         self.write_sub_paths_truncated(path);
1177                     }
1178                     ast::ViewPathGlob(ref path) => {
1179                         // Make a comma-separated list of names of imported modules.
1180                         let mut names = vec![];
1181                         let glob_map = &self.save_ctxt.analysis.glob_map;
1182                         let glob_map = glob_map.as_ref().unwrap();
1183                         if glob_map.contains_key(&item.id) {
1184                             for n in glob_map.get(&item.id).unwrap() {
1185                                 names.push(n.to_string());
1186                             }
1187                         }
1188
1189                         let sub_span = self.span
1190                                            .sub_span_of_token(item.span, token::BinOp(token::Star));
1191                         if !self.span.filter_generated(sub_span, item.span) {
1192                             let span =
1193                                 self.span_from_span(sub_span.expect("No span found for use glob"));
1194                             self.dumper.import(item.vis == ast::Visibility::Public, Import {
1195                                 kind: ImportKind::GlobUse,
1196                                 ref_id: None,
1197                                 span,
1198                                 name: "*".to_owned(),
1199                                 value: names.join(", "),
1200                             });
1201                         }
1202                         self.write_sub_paths(path);
1203                     }
1204                     ast::ViewPathList(ref path, ref list) => {
1205                         for plid in list {
1206                             let id = plid.node.id;
1207                             if let Some(def_id) = self.lookup_def_id(id) {
1208                                 let span = plid.span;
1209                                 self.process_def_kind(id, span, Some(span), def_id);
1210                             }
1211                         }
1212
1213                         self.write_sub_paths(path);
1214                     }
1215                 }
1216             }
1217             ExternCrate(_) => {
1218                 let alias_span = self.span.span_for_last_ident(item.span);
1219
1220                 if !self.span.filter_generated(alias_span, item.span) {
1221                     let span =
1222                         self.span_from_span(alias_span.expect("No span found for extern crate"));
1223                     self.dumper.import(false, Import {
1224                         kind: ImportKind::ExternCrate,
1225                         ref_id: None,
1226                         span,
1227                         name: item.ident.to_string(),
1228                         value: String::new(),
1229                     });
1230                 }
1231             }
1232             Fn(ref decl, .., ref ty_params, ref body) =>
1233                 self.process_fn(item, &decl, ty_params, &body),
1234             Static(ref typ, _, ref expr) =>
1235                 self.process_static_or_const_item(item, typ, expr),
1236             Const(ref typ, ref expr) =>
1237                 self.process_static_or_const_item(item, &typ, &expr),
1238             Struct(ref def, ref ty_params) => self.process_struct(item, def, ty_params),
1239             Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1240             Impl(..,
1241                  ref ty_params,
1242                  ref trait_ref,
1243                  ref typ,
1244                  ref impl_items) => {
1245                 self.process_impl(item, ty_params, trait_ref, &typ, impl_items)
1246             }
1247             Trait(_, ref generics, ref trait_refs, ref methods) =>
1248                 self.process_trait(item, generics, trait_refs, methods),
1249             Mod(ref m) => {
1250                 self.process_mod(item);
1251                 self.nest_scope(item.id, |v| visit::walk_mod(v, m));
1252             }
1253             Ty(ref ty, ref ty_params) => {
1254                 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
1255                 let value = ty_to_string(&ty);
1256                 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1257                 if !self.span.filter_generated(sub_span, item.span) {
1258                     let span = self.span_from_span(sub_span.expect("No span found for typedef"));
1259                     let id = ::id_from_node_id(item.id, &self.save_ctxt);
1260
1261                     self.dumper.dump_def(item.vis == ast::Visibility::Public, Def {
1262                         kind: DefKind::Type,
1263                         id,
1264                         span,
1265                         name: item.ident.to_string(),
1266                         qualname: qualname.clone(),
1267                         value,
1268                         parent: None,
1269                         children: vec![],
1270                         decl_id: None,
1271                         docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1272                         sig: sig::item_signature(item, &self.save_ctxt),
1273                         attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1274                     });
1275                 }
1276
1277                 self.visit_ty(&ty);
1278                 self.process_generic_params(ty_params, item.span, &qualname, item.id);
1279             }
1280             Mac(_) => (),
1281             _ => visit::walk_item(self, item),
1282         }
1283     }
1284
1285     fn visit_generics(&mut self, generics: &'l ast::Generics) {
1286         for param in generics.ty_params.iter() {
1287             for bound in param.bounds.iter() {
1288                 if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
1289                     self.process_trait_ref(&trait_ref.trait_ref);
1290                 }
1291             }
1292             if let Some(ref ty) = param.default {
1293                 self.visit_ty(&ty);
1294             }
1295         }
1296     }
1297
1298     fn visit_ty(&mut self, t: &'l ast::Ty) {
1299         self.process_macro_use(t.span);
1300         match t.node {
1301             ast::TyKind::Path(_, ref path) => {
1302                 if generated_code(t.span) {
1303                     return;
1304                 }
1305
1306                 if let Some(id) = self.lookup_def_id(t.id) {
1307                     if let Some(sub_span) = self.span.sub_span_for_type_name(t.span) {
1308                         let span = self.span_from_span(sub_span);
1309                         self.dumper.dump_ref(Ref {
1310                             kind: RefKind::Type,
1311                             span,
1312                             ref_id: ::id_from_def_id(id),
1313                         });
1314                     }
1315                 }
1316
1317                 self.write_sub_paths_truncated(path);
1318                 visit::walk_path(self, path);
1319             }
1320             ast::TyKind::Array(ref element, ref length) => {
1321                 self.visit_ty(element);
1322                 self.nest_tables(length.id, |v| v.visit_expr(length));
1323             }
1324             _ => visit::walk_ty(self, t),
1325         }
1326     }
1327
1328     fn visit_expr(&mut self, ex: &'l ast::Expr) {
1329         debug!("visit_expr {:?}", ex.node);
1330         self.process_macro_use(ex.span);
1331         match ex.node {
1332             ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1333                 let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id);
1334                 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1335                     Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1336                     _ => {
1337                         visit::walk_expr(self, ex);
1338                         return;
1339                     }
1340                 };
1341                 let def = self.save_ctxt.get_path_def(hir_expr.id);
1342                 self.process_struct_lit(ex, path, fields, adt.variant_of_def(def), base)
1343             }
1344             ast::ExprKind::MethodCall(.., ref args) => self.process_method_call(ex, args),
1345             ast::ExprKind::Field(ref sub_ex, _) => {
1346                 self.visit_expr(&sub_ex);
1347
1348                 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1349                     down_cast_data!(field_data, RefData, ex.span);
1350                     if !generated_code(ex.span) {
1351                         self.dumper.dump_ref(field_data);
1352                     }
1353                 }
1354             }
1355             ast::ExprKind::TupField(ref sub_ex, idx) => {
1356                 self.visit_expr(&sub_ex);
1357
1358                 let hir_node = match self.save_ctxt.tcx.hir.find(sub_ex.id) {
1359                     Some(Node::NodeExpr(expr)) => expr,
1360                     _ => {
1361                         debug!("Missing or weird node for sub-expression {} in {:?}",
1362                                sub_ex.id, ex);
1363                         return;
1364                     }
1365                 };
1366                 let ty = match self.save_ctxt.tables.expr_ty_adjusted_opt(&hir_node) {
1367                     Some(ty) => &ty.sty,
1368                     None => {
1369                         visit::walk_expr(self, ex);
1370                         return;
1371                     }
1372                 };
1373                 match *ty {
1374                     ty::TyAdt(def, _) => {
1375                         let sub_span = self.span.sub_span_after_token(ex.span, token::Dot);
1376                         if !self.span.filter_generated(sub_span, ex.span) {
1377                             let span =
1378                                 self.span_from_span(sub_span.expect("No span found for var ref"));
1379                             self.dumper.dump_ref(Ref {
1380                                 kind: RefKind::Variable,
1381                                 span: span,
1382                                 ref_id: ::id_from_def_id(def.struct_variant().fields[idx.node].did),
1383                             });
1384                         }
1385                     }
1386                     ty::TyTuple(..) => {}
1387                     _ => span_bug!(ex.span,
1388                                    "Expected struct or tuple type, found {:?}",
1389                                    ty),
1390                 }
1391             }
1392             ast::ExprKind::Closure(_, ref decl, ref body, _fn_decl_span) => {
1393                 let mut id = String::from("$");
1394                 id.push_str(&ex.id.to_string());
1395
1396                 // walk arg and return types
1397                 for arg in &decl.inputs {
1398                     self.visit_ty(&arg.ty);
1399                 }
1400
1401                 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1402                     self.visit_ty(&ret_ty);
1403                 }
1404
1405                 // walk the body
1406                 self.nest_tables(ex.id, |v| {
1407                     v.process_formals(&decl.inputs, &id);
1408                     v.nest_scope(ex.id, |v| v.visit_expr(body))
1409                 });
1410             }
1411             ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) |
1412             ast::ExprKind::WhileLet(ref pattern, ref subexpression, ref block, _) => {
1413                 let value = self.span.snippet(subexpression.span);
1414                 self.process_var_decl(pattern, value);
1415                 debug!("for loop, walk sub-expr: {:?}", subexpression.node);
1416                 visit::walk_expr(self, subexpression);
1417                 visit::walk_block(self, block);
1418             }
1419             ast::ExprKind::IfLet(ref pattern, ref subexpression, ref block, ref opt_else) => {
1420                 let value = self.span.snippet(subexpression.span);
1421                 self.process_var_decl(pattern, value);
1422                 visit::walk_expr(self, subexpression);
1423                 visit::walk_block(self, block);
1424                 opt_else.as_ref().map(|el| visit::walk_expr(self, el));
1425             }
1426             ast::ExprKind::Repeat(ref element, ref count) => {
1427                 self.visit_expr(element);
1428                 self.nest_tables(count.id, |v| v.visit_expr(count));
1429             }
1430             // In particular, we take this branch for call and path expressions,
1431             // where we'll index the idents involved just by continuing to walk.
1432             _ => {
1433                 visit::walk_expr(self, ex)
1434             }
1435         }
1436     }
1437
1438     fn visit_mac(&mut self, mac: &'l ast::Mac) {
1439         // These shouldn't exist in the AST at this point, log a span bug.
1440         span_bug!(mac.span, "macro invocation should have been expanded out of AST");
1441     }
1442
1443     fn visit_pat(&mut self, p: &'l ast::Pat) {
1444         self.process_macro_use(p.span);
1445         self.process_pat(p);
1446     }
1447
1448     fn visit_arm(&mut self, arm: &'l ast::Arm) {
1449         let mut collector = PathCollector::new();
1450         for pattern in &arm.pats {
1451             // collect paths from the arm's patterns
1452             collector.visit_pat(&pattern);
1453             self.visit_pat(&pattern);
1454         }
1455
1456         // This is to get around borrow checking, because we need mut self to call process_path.
1457         let mut paths_to_process = vec![];
1458
1459         // process collected paths
1460         for &(id, ref p, immut) in &collector.collected_paths {
1461             match self.save_ctxt.get_path_def(id) {
1462                 HirDef::Local(def_id) => {
1463                     let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1464                     let mut value = if immut == ast::Mutability::Immutable {
1465                         self.span.snippet(p.span).to_string()
1466                     } else {
1467                         "<mutable>".to_string()
1468                     };
1469                     let typ = self.save_ctxt.tables.node_types
1470                                   .get(&id).map(|t| t.to_string()).unwrap_or(String::new());
1471                     value.push_str(": ");
1472                     value.push_str(&typ);
1473
1474                     assert!(p.segments.len() == 1,
1475                             "qualified path for local variable def in arm");
1476                     if !self.span.filter_generated(Some(p.span), p.span) {
1477                         let qualname = format!("{}${}", path_to_string(p), id);
1478                         let id = ::id_from_node_id(id, &self.save_ctxt);
1479                         let span = self.span_from_span(p.span);
1480
1481                         self.dumper.dump_def(false, Def {
1482                             kind: DefKind::Local,
1483                             id,
1484                             span,
1485                             name: path_to_string(p),
1486                             qualname,
1487                             value: typ,
1488                             parent: None,
1489                             children: vec![],
1490                             decl_id: None,
1491                             docs: String::new(),
1492                             sig: None,
1493                             attributes:vec![],
1494                         });
1495                     }
1496                 }
1497                 HirDef::StructCtor(..) | HirDef::VariantCtor(..) |
1498                 HirDef::Const(..) | HirDef::AssociatedConst(..) |
1499                 HirDef::Struct(..) | HirDef::Variant(..) |
1500                 HirDef::TyAlias(..) | HirDef::AssociatedTy(..) |
1501                 HirDef::SelfTy(..) => {
1502                     paths_to_process.push((id, p.clone()))
1503                 }
1504                 def => error!("unexpected definition kind when processing collected paths: {:?}",
1505                               def),
1506             }
1507         }
1508
1509         for &(id, ref path) in &paths_to_process {
1510             self.process_path(id, path);
1511         }
1512         walk_list!(self, visit_expr, &arm.guard);
1513         self.visit_expr(&arm.body);
1514     }
1515
1516     fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1517         self.process_path(id, p);
1518     }
1519
1520     fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1521         self.process_macro_use(s.span);
1522         visit::walk_stmt(self, s)
1523     }
1524
1525     fn visit_local(&mut self, l: &'l ast::Local) {
1526         self.process_macro_use(l.span);
1527         let value = l.init.as_ref().map(|i| self.span.snippet(i.span)).unwrap_or(String::new());
1528         self.process_var_decl(&l.pat, value);
1529
1530         // Just walk the initialiser and type (don't want to walk the pattern again).
1531         walk_list!(self, visit_ty, &l.ty);
1532         walk_list!(self, visit_expr, &l.init);
1533     }
1534
1535     fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1536         match item.node {
1537             ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1538                 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1539                     down_cast_data!(fn_data, DefData, item.span);
1540
1541                     self.nest_tables(item.id, |v| v.process_formals(&decl.inputs,
1542                                                                     &fn_data.qualname));
1543                     self.process_generic_params(generics, item.span, &fn_data.qualname, item.id);
1544                     self.dumper.dump_def(item.vis == ast::Visibility::Public, fn_data);
1545                 }
1546
1547                 for arg in &decl.inputs {
1548                     self.visit_ty(&arg.ty);
1549                 }
1550
1551                 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1552                     self.visit_ty(&ret_ty);
1553                 }
1554             }
1555             ast::ForeignItemKind::Static(ref ty, _) => {
1556                 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1557                     down_cast_data!(var_data, DefData, item.span);
1558                     self.dumper.dump_def(item.vis == ast::Visibility::Public, var_data);
1559                 }
1560
1561                 self.visit_ty(ty);
1562             }
1563         }
1564     }
1565 }