]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/save/mod.rs
auto merge of #17188 : thestinger/rust/tvec, r=pcwalton
[rust.git] / src / librustc / middle / save / mod.rs
1 // Copyright 2012-2014 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 //! Output a CSV file containing the output from rustc's analysis. The data is
12 //! primarily designed to be used as input to the DXR tool, specifically its
13 //! Rust plugin. It could also be used by IDEs or other code browsing, search, or
14 //! cross-referencing tools.
15 //!
16 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
17 //! info out from all over the place. We use Def IDs to identify objects. The
18 //! tricky part is getting syntactic (span, source text) and semantic (reference
19 //! Def IDs) information for parts of expressions which the compiler has discarded.
20 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
21 //! path and a reference to `baz`, but we want spans and references for all three
22 //! idents.
23 //!
24 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
25 //! from spans (e.g., the span for `bar` from the above example path).
26 //! Recorder is used for recording the output in csv format. FmtStrs separates
27 //! the format of the output away from extracting it from the compiler.
28 //! DxrVisitor walks the AST and processes it.
29
30 use driver::driver::CrateAnalysis;
31 use driver::session::Session;
32
33 use middle::def;
34 use middle::ty;
35 use middle::typeck;
36
37 use std::cell::Cell;
38 use std::gc::Gc;
39 use std::io;
40 use std::io::File;
41 use std::io::fs;
42 use std::os;
43
44 use syntax::ast;
45 use syntax::ast_util;
46 use syntax::ast_util::PostExpansionMethod;
47 use syntax::ast::{NodeId,DefId};
48 use syntax::ast_map::NodeItem;
49 use syntax::attr;
50 use syntax::codemap::*;
51 use syntax::parse::token;
52 use syntax::parse::token::{get_ident,keywords};
53 use syntax::owned_slice::OwnedSlice;
54 use syntax::visit;
55 use syntax::visit::Visitor;
56 use syntax::print::pprust::{path_to_string,ty_to_string};
57
58 use middle::save::span_utils::SpanUtils;
59 use middle::save::recorder::Recorder;
60 use middle::save::recorder::FmtStrs;
61
62 use util::ppaux;
63
64 mod span_utils;
65 mod recorder;
66
67 // Helper function to escape quotes in a string
68 fn escape(s: String) -> String {
69     s.replace("\"", "\"\"")
70 }
71
72 // If the expression is a macro expansion or other generated code, run screaming and don't index.
73 fn generated_code(span: Span) -> bool {
74     span.expn_info.is_some() || span  == DUMMY_SP
75 }
76
77 struct DxrVisitor<'l, 'tcx: 'l> {
78     sess: &'l Session,
79     analysis: &'l CrateAnalysis<'tcx>,
80
81     collected_paths: Vec<(NodeId, ast::Path, bool, recorder::Row)>,
82     collecting: bool,
83
84     span: SpanUtils<'l>,
85     fmt: FmtStrs<'l>,
86
87     cur_scope: NodeId
88 }
89
90 impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
91     fn nest(&mut self, scope_id: NodeId, f: |&mut DxrVisitor<'l, 'tcx>|) {
92         let parent_scope = self.cur_scope;
93         self.cur_scope = scope_id;
94         f(self);
95         self.cur_scope = parent_scope;
96     }
97
98     fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
99         // the current crate
100         self.fmt.crate_str(krate.span, name);
101
102         // dump info about all the external crates referenced from this crate
103         self.sess.cstore.iter_crate_data(|n, cmd| {
104             self.fmt.external_crate_str(krate.span, cmd.name.as_slice(), n);
105         });
106         self.fmt.recorder.record("end_external_crates\n");
107     }
108
109     // Return all non-empty prefixes of a path.
110     // For each prefix, we return the span for the last segment in the prefix and
111     // a str representation of the entire prefix.
112     fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
113         let spans = self.span.spans_for_path_segments(path);
114
115         // Paths to enums seem to not match their spans - the span includes all the
116         // variants too. But they seem to always be at the end, so I hope we can cope with
117         // always using the first ones. So, only error out if we don't have enough spans.
118         // What could go wrong...?
119         if spans.len() < path.segments.len() {
120             error!("Mis-calculated spans for path '{}'. \
121                     Found {} spans, expected {}. Found spans:",
122                    path_to_string(path), spans.len(), path.segments.len());
123             for s in spans.iter() {
124                 let loc = self.sess.codemap().lookup_char_pos(s.lo);
125                 error!("    '{}' in {}, line {}",
126                        self.span.snippet(*s), loc.file.name, loc.line);
127             }
128             return vec!();
129         }
130
131         let mut result: Vec<(Span, String)> = vec!();
132
133
134         let mut segs = vec!();
135         for (seg, span) in path.segments.iter().zip(spans.iter()) {
136             segs.push(seg.clone());
137             let sub_path = ast::Path{span: *span, // span for the last segment
138                                      global: path.global,
139                                      segments: segs};
140             let qualname = path_to_string(&sub_path);
141             result.push((*span, qualname));
142             segs = sub_path.segments;
143         }
144
145         result
146     }
147
148     fn write_sub_paths(&mut self, path: &ast::Path) {
149         let sub_paths = self.process_path_prefixes(path);
150         for &(ref span, ref qualname) in sub_paths.iter() {
151             self.fmt.sub_mod_ref_str(path.span,
152                                      *span,
153                                      qualname.as_slice(),
154                                      self.cur_scope);
155         }
156     }
157
158     // As write_sub_paths, but does not process the last ident in the path (assuming it
159     // will be processed elsewhere).
160     fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
161         let sub_paths = self.process_path_prefixes(path);
162         let len = sub_paths.len();
163         if len <= 1 {
164             return;
165         }
166
167         let sub_paths = sub_paths.slice(0, len-1);
168         for &(ref span, ref qualname) in sub_paths.iter() {
169             self.fmt.sub_mod_ref_str(path.span,
170                                      *span,
171                                      qualname.as_slice(),
172                                      self.cur_scope);
173         }
174     }
175
176     // As write_sub_paths, but expects a path of the form module_path::trait::method
177     // Where trait could actually be a struct too.
178     fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
179         let sub_paths = self.process_path_prefixes(path);
180         let len = sub_paths.len();
181         if len <= 1 {
182             return;
183         }
184         let sub_paths = sub_paths.slice_to(len-1);
185
186         // write the trait part of the sub-path
187         let (ref span, ref qualname) = sub_paths[len-2];
188         self.fmt.sub_type_ref_str(path.span,
189                                   *span,
190                                   qualname.as_slice());
191
192         // write the other sub-paths
193         if len <= 2 {
194             return;
195         }
196         let sub_paths = sub_paths.slice(0, len-2);
197         for &(ref span, ref qualname) in sub_paths.iter() {
198             self.fmt.sub_mod_ref_str(path.span,
199                                      *span,
200                                      qualname.as_slice(),
201                                      self.cur_scope);
202         }
203     }
204
205     // looks up anything, not just a type
206     fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> {
207         if !self.analysis.ty_cx.def_map.borrow().contains_key(&ref_id) {
208             self.sess.bug(format!("def_map has no key for {} in lookup_type_ref",
209                                   ref_id).as_slice());
210         }
211         let def = *self.analysis.ty_cx.def_map.borrow().get(&ref_id);
212         match def {
213             def::DefPrimTy(_) => None,
214             _ => Some(def.def_id()),
215         }
216     }
217
218     fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> {
219         let def_map = self.analysis.ty_cx.def_map.borrow();
220         if !def_map.contains_key(&ref_id) {
221             self.sess.span_bug(span, format!("def_map has no key for {} in lookup_def_kind",
222                                              ref_id).as_slice());
223         }
224         let def = *def_map.get(&ref_id);
225         match def {
226             def::DefMod(_) |
227             def::DefForeignMod(_) => Some(recorder::ModRef),
228             def::DefStruct(_) => Some(recorder::StructRef),
229             def::DefTy(_) |
230             def::DefTrait(_) => Some(recorder::TypeRef),
231             def::DefStatic(_, _) |
232             def::DefBinding(_, _) |
233             def::DefArg(_, _) |
234             def::DefLocal(_, _) |
235             def::DefVariant(_, _, _) |
236             def::DefUpvar(_, _, _, _) => Some(recorder::VarRef),
237
238             def::DefFn(_, _) => Some(recorder::FnRef),
239
240             def::DefSelfTy(_) |
241             def::DefRegion(_) |
242             def::DefTyParamBinder(_) |
243             def::DefLabel(_) |
244             def::DefStaticMethod(_, _, _) |
245             def::DefTyParam(..) |
246             def::DefUse(_) |
247             def::DefMethod(_, _) |
248             def::DefPrimTy(_) => {
249                 self.sess.span_bug(span, format!("lookup_def_kind for unexpected item: {:?}",
250                                                  def).as_slice());
251             },
252         }
253     }
254
255     fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
256         for arg in formals.iter() {
257             assert!(self.collected_paths.len() == 0 && !self.collecting);
258             self.collecting = true;
259             self.visit_pat(&*arg.pat);
260             self.collecting = false;
261             let span_utils = self.span;
262             for &(id, ref p, _, _) in self.collected_paths.iter() {
263                 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
264                     *self.analysis.ty_cx.node_types.borrow().get(&(id as uint)));
265                 // get the span only for the name of the variable (I hope the path is only ever a
266                 // variable name, but who knows?)
267                 self.fmt.formal_str(p.span,
268                                     span_utils.span_for_last_ident(p.span),
269                                     id,
270                                     qualname,
271                                     path_to_string(p).as_slice(),
272                                     typ.as_slice());
273             }
274             self.collected_paths.clear();
275         }
276     }
277
278     fn process_method(&mut self, method: &ast::Method) {
279         if generated_code(method.span) {
280             return;
281         }
282
283         let mut scope_id;
284         // The qualname for a method is the trait name or name of the struct in an impl in
285         // which the method is declared in followed by the method's name.
286         let mut qualname = match ty::impl_of_method(&self.analysis.ty_cx,
287                                                 ast_util::local_def(method.id)) {
288             Some(impl_id) => match self.analysis.ty_cx.map.get(impl_id.node) {
289                 NodeItem(item) => {
290                     scope_id = item.id;
291                     match item.node {
292                         ast::ItemImpl(_, _, ty, _) => {
293                             let mut result = String::from_str("<");
294                             result.push_str(ty_to_string(&*ty).as_slice());
295
296                             match ty::trait_of_item(&self.analysis.ty_cx,
297                                                     ast_util::local_def(method.id)) {
298                                 Some(def_id) => {
299                                     result.push_str(" as ");
300                                     result.push_str(
301                                         ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice());
302                                 },
303                                 None => {}
304                             }
305                             result.append(">::")
306                         }
307                         _ => {
308                             self.sess.span_bug(method.span,
309                                                format!("Container {} for method {} not an impl?",
310                                                        impl_id.node, method.id).as_slice());
311                         },
312                     }
313                 },
314                 _ => {
315                     self.sess.span_bug(method.span,
316                                        format!("Container {} for method {} is not a node item {:?}",
317                                                impl_id.node,
318                                                method.id,
319                                                self.analysis.ty_cx.map.get(impl_id.node)
320                                               ).as_slice());
321                 },
322             },
323             None => match ty::trait_of_item(&self.analysis.ty_cx,
324                                             ast_util::local_def(method.id)) {
325                 Some(def_id) => {
326                     scope_id = def_id.node;
327                     match self.analysis.ty_cx.map.get(def_id.node) {
328                         NodeItem(_) => {
329                             let result = ty::item_path_str(&self.analysis.ty_cx, def_id);
330                             result.append("::")
331                         }
332                         _ => {
333                             self.sess.span_bug(method.span,
334                                                format!("Could not find container {} for method {}",
335                                                        def_id.node, method.id).as_slice());
336                         }
337                     }
338                 },
339                 None => {
340                     self.sess.span_bug(method.span,
341                                        format!("Could not find container for method {}",
342                                                method.id).as_slice());
343                 },
344             },
345         };
346
347         qualname.push_str(get_ident(method.pe_ident()).get());
348         let qualname = qualname.as_slice();
349
350         // record the decl for this def (if it has one)
351         let decl_id = ty::trait_item_of_item(&self.analysis.ty_cx,
352                                              ast_util::local_def(method.id))
353             .filtered(|def_id| {
354                 match *def_id {
355                     ty::MethodTraitItemId(def_id) => {
356                         method.id != 0 && def_id.node == 0
357                     }
358                 }
359             });
360         let decl_id = match decl_id {
361             None => None,
362             Some(ty::MethodTraitItemId(def_id)) => Some(def_id),
363         };
364
365         let sub_span = self.span.sub_span_after_keyword(method.span, keywords::Fn);
366         self.fmt.method_str(method.span,
367                             sub_span,
368                             method.id,
369                             qualname,
370                             decl_id,
371                             scope_id);
372
373         self.process_formals(&method.pe_fn_decl().inputs, qualname);
374
375         // walk arg and return types
376         for arg in method.pe_fn_decl().inputs.iter() {
377             self.visit_ty(&*arg.ty);
378         }
379         self.visit_ty(&*method.pe_fn_decl().output);
380         // walk the fn body
381         self.nest(method.id, |v| v.visit_block(&*method.pe_body()));
382
383         self.process_generic_params(method.pe_generics(),
384                                     method.span,
385                                     qualname,
386                                     method.id);
387     }
388
389     fn process_trait_ref(&mut self,
390                          trait_ref: &ast::TraitRef,
391                          impl_id: Option<NodeId>) {
392         match self.lookup_type_ref(trait_ref.ref_id) {
393             Some(id) => {
394                 let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
395                 self.fmt.ref_str(recorder::TypeRef,
396                                  trait_ref.path.span,
397                                  sub_span,
398                                  id,
399                                  self.cur_scope);
400                 match impl_id {
401                     Some(impl_id) => self.fmt.impl_str(trait_ref.path.span,
402                                                        sub_span,
403                                                        impl_id,
404                                                        id,
405                                                        self.cur_scope),
406                     None => (),
407                 }
408                 visit::walk_path(self, &trait_ref.path);
409             },
410             None => ()
411         }
412     }
413
414     fn process_struct_field_def(&mut self,
415                                 field: &ast::StructField,
416                                 qualname: &str,
417                                 scope_id: NodeId) {
418         match field.node.kind {
419             ast::NamedField(ident, _) => {
420                 let name = get_ident(ident);
421                 let qualname = format!("{}::{}", qualname, name);
422                 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
423                     *self.analysis.ty_cx.node_types.borrow().get(&(field.node.id as uint)));
424                 match self.span.sub_span_before_token(field.span, token::COLON) {
425                     Some(sub_span) => self.fmt.field_str(field.span,
426                                                          Some(sub_span),
427                                                          field.node.id,
428                                                          name.get().as_slice(),
429                                                          qualname.as_slice(),
430                                                          typ.as_slice(),
431                                                          scope_id),
432                     None => self.sess.span_bug(field.span,
433                                                format!("Could not find sub-span for field {}",
434                                                        qualname).as_slice()),
435                 }
436             },
437             _ => (),
438         }
439     }
440
441     // Dump generic params bindings, then visit_generics
442     fn process_generic_params(&mut self, generics:&ast::Generics,
443                               full_span: Span,
444                               prefix: &str,
445                               id: NodeId) {
446         // We can't only use visit_generics since we don't have spans for param
447         // bindings, so we reparse the full_span to get those sub spans.
448         // However full span is the entire enum/fn/struct block, so we only want
449         // the first few to match the number of generics we're looking for.
450         let param_sub_spans = self.span.spans_for_ty_params(full_span,
451                                                            (generics.ty_params.len() as int));
452         for (param, param_ss) in generics.ty_params.iter().zip(param_sub_spans.iter()) {
453             // Append $id to name to make sure each one is unique
454             let name = format!("{}::{}${}",
455                                prefix,
456                                escape(self.span.snippet(*param_ss)),
457                                id);
458             self.fmt.typedef_str(full_span,
459                                  Some(*param_ss),
460                                  param.id,
461                                  name.as_slice(),
462                                  "");
463         }
464         self.visit_generics(generics);
465     }
466
467     fn process_fn(&mut self,
468                   item: &ast::Item,
469                   decl: ast::P<ast::FnDecl>,
470                   ty_params: &ast::Generics,
471                   body: ast::P<ast::Block>) {
472         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
473
474         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Fn);
475         self.fmt.fn_str(item.span,
476                         sub_span,
477                         item.id,
478                         qualname.as_slice(),
479                         self.cur_scope);
480
481         self.process_formals(&decl.inputs, qualname.as_slice());
482
483         // walk arg and return types
484         for arg in decl.inputs.iter() {
485             self.visit_ty(&*arg.ty);
486         }
487         self.visit_ty(&*decl.output);
488
489         // walk the body
490         self.nest(item.id, |v| v.visit_block(&*body));
491
492         self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
493     }
494
495     fn process_static(&mut self,
496                       item: &ast::Item,
497                       typ: ast::P<ast::Ty>,
498                       mt: ast::Mutability,
499                       expr: &ast::Expr)
500     {
501         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
502
503         // If the variable is immutable, save the initialising expression.
504         let value = match mt {
505             ast::MutMutable => String::from_str("<mutable>"),
506             ast::MutImmutable => self.span.snippet(expr.span),
507         };
508
509         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Static);
510         self.fmt.static_str(item.span,
511                             sub_span,
512                             item.id,
513                             get_ident(item.ident).get(),
514                             qualname.as_slice(),
515                             value.as_slice(),
516                             ty_to_string(&*typ).as_slice(),
517                             self.cur_scope);
518
519         // walk type and init value
520         self.visit_ty(&*typ);
521         self.visit_expr(expr);
522     }
523
524     fn process_struct(&mut self,
525                       item: &ast::Item,
526                       def: &ast::StructDef,
527                       ty_params: &ast::Generics) {
528         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
529
530         let ctor_id = match def.ctor_id {
531             Some(node_id) => node_id,
532             None => -1,
533         };
534         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Struct);
535         self.fmt.struct_str(item.span,
536                             sub_span,
537                             item.id,
538                             ctor_id,
539                             qualname.as_slice(),
540                             self.cur_scope);
541
542         // fields
543         for field in def.fields.iter() {
544             self.process_struct_field_def(field, qualname.as_slice(), item.id);
545             self.visit_ty(&*field.node.ty);
546         }
547
548         self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
549     }
550
551     fn process_enum(&mut self,
552                     item: &ast::Item,
553                     enum_definition: &ast::EnumDef,
554                     ty_params: &ast::Generics) {
555         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
556         match self.span.sub_span_after_keyword(item.span, keywords::Enum) {
557             Some(sub_span) => self.fmt.enum_str(item.span,
558                                                 Some(sub_span),
559                                                 item.id,
560                                                 qualname.as_slice(),
561                                                 self.cur_scope),
562             None => self.sess.span_bug(item.span,
563                                        format!("Could not find subspan for enum {}",
564                                                qualname).as_slice()),
565         }
566         for variant in enum_definition.variants.iter() {
567             let name = get_ident(variant.node.name);
568             let name = name.get();
569             let qualname = qualname.clone().append("::").append(name);
570             let val = self.span.snippet(variant.span);
571             match variant.node.kind {
572                 ast::TupleVariantKind(ref args) => {
573                     // first ident in span is the variant's name
574                     self.fmt.tuple_variant_str(variant.span,
575                                                self.span.span_for_first_ident(variant.span),
576                                                variant.node.id,
577                                                name,
578                                                qualname.as_slice(),
579                                                val.as_slice(),
580                                                item.id);
581                     for arg in args.iter() {
582                         self.visit_ty(&*arg.ty);
583                     }
584                 }
585                 ast::StructVariantKind(ref struct_def) => {
586                     let ctor_id = match struct_def.ctor_id {
587                         Some(node_id) => node_id,
588                         None => -1,
589                     };
590                     self.fmt.struct_variant_str(
591                         variant.span,
592                         self.span.span_for_first_ident(variant.span),
593                         variant.node.id,
594                         ctor_id,
595                         qualname.as_slice(),
596                         val.as_slice(),
597                         item.id);
598
599                     for field in struct_def.fields.iter() {
600                         self.process_struct_field_def(field, qualname.as_slice(), variant.node.id);
601                         self.visit_ty(&*field.node.ty);
602                     }
603                 }
604             }
605         }
606
607         self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
608     }
609
610     fn process_impl(&mut self,
611                     item: &ast::Item,
612                     type_parameters: &ast::Generics,
613                     trait_ref: &Option<ast::TraitRef>,
614                     typ: ast::P<ast::Ty>,
615                     impl_items: &Vec<ast::ImplItem>) {
616         match typ.node {
617             ast::TyPath(ref path, _, id) => {
618                 match self.lookup_type_ref(id) {
619                     Some(id) => {
620                         let sub_span = self.span.sub_span_for_type_name(path.span);
621                         self.fmt.ref_str(recorder::TypeRef,
622                                          path.span,
623                                          sub_span,
624                                          id,
625                                          self.cur_scope);
626                         self.fmt.impl_str(path.span,
627                                           sub_span,
628                                           item.id,
629                                           id,
630                                           self.cur_scope);
631                     },
632                     None => ()
633                 }
634             },
635             _ => self.visit_ty(&*typ),
636         }
637
638         match *trait_ref {
639             Some(ref trait_ref) => self.process_trait_ref(trait_ref, Some(item.id)),
640             None => (),
641         }
642
643         self.process_generic_params(type_parameters, item.span, "", item.id);
644         for impl_item in impl_items.iter() {
645             match *impl_item {
646                 ast::MethodImplItem(method) => {
647                     visit::walk_method_helper(self, &*method)
648                 }
649             }
650         }
651     }
652
653     fn process_trait(&mut self,
654                      item: &ast::Item,
655                      generics: &ast::Generics,
656                      trait_refs: &OwnedSlice<ast::TyParamBound>,
657                      methods: &Vec<ast::TraitItem>) {
658         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
659
660         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
661         self.fmt.trait_str(item.span,
662                            sub_span,
663                            item.id,
664                            qualname.as_slice(),
665                            self.cur_scope);
666
667         // super-traits
668         for super_bound in trait_refs.iter() {
669             let trait_ref = match *super_bound {
670                 ast::TraitTyParamBound(ref trait_ref) => {
671                     trait_ref
672                 }
673                 ast::UnboxedFnTyParamBound(..) | ast::RegionTyParamBound(..) => {
674                     continue;
675                 }
676             };
677
678             match self.lookup_type_ref(trait_ref.ref_id) {
679                 Some(id) => {
680                     let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
681                     self.fmt.ref_str(recorder::TypeRef,
682                                      trait_ref.path.span,
683                                      sub_span,
684                                      id,
685                                      self.cur_scope);
686                     self.fmt.inherit_str(trait_ref.path.span,
687                                          sub_span,
688                                          id,
689                                          item.id);
690                 },
691                 None => ()
692             }
693         }
694
695         // walk generics and methods
696         self.process_generic_params(generics, item.span, qualname.as_slice(), item.id);
697         for method in methods.iter() {
698             self.visit_trait_item(method)
699         }
700     }
701
702     fn process_mod(&mut self,
703                    item: &ast::Item,  // The module in question, represented as an item.
704                    m: &ast::Mod) {
705         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
706
707         let cm = self.sess.codemap();
708         let filename = cm.span_to_filename(m.inner);
709
710         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Mod);
711         self.fmt.mod_str(item.span,
712                          sub_span,
713                          item.id,
714                          qualname.as_slice(),
715                          self.cur_scope,
716                          filename.as_slice());
717
718         self.nest(item.id, |v| visit::walk_mod(v, m));
719     }
720
721     fn process_path(&mut self,
722                     ex: &ast::Expr,
723                     path: &ast::Path) {
724         if generated_code(path.span) {
725             return
726         }
727
728         let def_map = self.analysis.ty_cx.def_map.borrow();
729         if !def_map.contains_key(&ex.id) {
730             self.sess.span_bug(ex.span,
731                                format!("def_map has no key for {} in visit_expr",
732                                        ex.id).as_slice());
733         }
734         let def = def_map.get(&ex.id);
735         let sub_span = self.span.span_for_last_ident(ex.span);
736         match *def {
737             def::DefLocal(id, _) |
738             def::DefArg(id, _) |
739             def::DefUpvar(id, _, _, _) |
740             def::DefBinding(id, _) => self.fmt.ref_str(recorder::VarRef,
741                                                        ex.span,
742                                                        sub_span,
743                                                        ast_util::local_def(id),
744                                                        self.cur_scope),
745             def::DefStatic(def_id,_) |
746             def::DefVariant(_, def_id, _) => self.fmt.ref_str(recorder::VarRef,
747                                                               ex.span,
748                                                               sub_span,
749                                                               def_id,
750                                                               self.cur_scope),
751             def::DefStruct(def_id) => self.fmt.ref_str(recorder::StructRef,
752                                                        ex.span,
753                                                        sub_span,
754                                                        def_id,
755                                                         self.cur_scope),
756             def::DefStaticMethod(declid, provenence, _) => {
757                 let sub_span = self.span.sub_span_for_meth_name(ex.span);
758                 let defid = if declid.krate == ast::LOCAL_CRATE {
759                     let ti = ty::impl_or_trait_item(&self.analysis.ty_cx,
760                                                     declid);
761                     match provenence {
762                         def::FromTrait(def_id) => {
763                             Some(ty::trait_items(&self.analysis.ty_cx,
764                                                  def_id)
765                                     .iter()
766                                     .find(|mr| {
767                                         match **mr {
768                                             ty::MethodTraitItem(ref mr) => {
769                                                 mr.ident.name == ti.ident()
770                                                                    .name
771                                             }
772                                         }
773                                     })
774                                     .unwrap()
775                                     .def_id())
776                         }
777                         def::FromImpl(def_id) => {
778                             let impl_items = self.analysis
779                                                  .ty_cx
780                                                  .impl_items
781                                                  .borrow();
782                             Some(impl_items.get(&def_id)
783                                            .iter()
784                                            .find(|mr| {
785                                             match **mr {
786                                                 ty::MethodTraitItemId(mr) => {
787                                                     ty::impl_or_trait_item(
788                                                             &self.analysis
789                                                                  .ty_cx,
790                                                             mr).ident()
791                                                                .name ==
792                                                         ti.ident().name
793                                                     }
794                                                 }
795                                             }).unwrap()
796                                               .def_id())
797                         }
798                     }
799                 } else {
800                     None
801                 };
802                 self.fmt.meth_call_str(ex.span,
803                                        sub_span,
804                                        defid,
805                                        Some(declid),
806                                        self.cur_scope);
807             },
808             def::DefFn(def_id, _) => self.fmt.fn_call_str(ex.span,
809                                                           sub_span,
810                                                           def_id,
811                                                           self.cur_scope),
812             _ => self.sess.span_bug(ex.span,
813                                     format!("Unexpected def kind while looking up path in '{}'",
814                                             self.span.snippet(ex.span)).as_slice()),
815         }
816         // modules or types in the path prefix
817         match *def {
818             def::DefStaticMethod(_, _, _) => {
819                 self.write_sub_path_trait_truncated(path);
820             },
821             def::DefLocal(_, _) |
822             def::DefArg(_, _) |
823             def::DefStatic(_,_) |
824             def::DefStruct(_) |
825             def::DefFn(_, _) => self.write_sub_paths_truncated(path),
826             _ => {},
827         }
828
829         visit::walk_path(self, path);
830     }
831
832     fn process_struct_lit(&mut self,
833                           ex: &ast::Expr,
834                           path: &ast::Path,
835                           fields: &Vec<ast::Field>,
836                           base: &Option<Gc<ast::Expr>>) {
837         if generated_code(path.span) {
838             return
839         }
840
841         let mut struct_def: Option<DefId> = None;
842         match self.lookup_type_ref(ex.id) {
843             Some(id) => {
844                 struct_def = Some(id);
845                 let sub_span = self.span.span_for_last_ident(path.span);
846                 self.fmt.ref_str(recorder::StructRef,
847                                  path.span,
848                                  sub_span,
849                                  id,
850                                  self.cur_scope);
851             },
852             None => ()
853         }
854
855         self.write_sub_paths_truncated(path);
856
857         for field in fields.iter() {
858             match struct_def {
859                 Some(struct_def) => {
860                     let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
861                     for f in fields.iter() {
862                         if generated_code(field.ident.span) {
863                             continue;
864                         }
865                         if f.name == field.ident.node.name {
866                             // We don't really need a sub-span here, but no harm done
867                             let sub_span = self.span.span_for_last_ident(field.ident.span);
868                             self.fmt.ref_str(recorder::VarRef,
869                                              field.ident.span,
870                                              sub_span,
871                                              f.id,
872                                              self.cur_scope);
873                         }
874                     }
875                 }
876                 None => {}
877             }
878
879             self.visit_expr(&*field.expr)
880         }
881         visit::walk_expr_opt(self, base)
882     }
883
884     fn process_method_call(&mut self,
885                            ex: &ast::Expr,
886                            args: &Vec<Gc<ast::Expr>>) {
887         let method_map = self.analysis.ty_cx.method_map.borrow();
888         let method_callee = method_map.get(&typeck::MethodCall::expr(ex.id));
889         let (def_id, decl_id) = match method_callee.origin {
890             typeck::MethodStatic(def_id) |
891             typeck::MethodStaticUnboxedClosure(def_id) => {
892                 // method invoked on an object with a concrete type (not a static method)
893                 let decl_id =
894                     match ty::trait_item_of_item(&self.analysis.ty_cx,
895                                                  def_id) {
896                         None => None,
897                         Some(ty::MethodTraitItemId(decl_id)) => Some(decl_id),
898                     };
899
900                 // This incantation is required if the method referenced is a
901                 // trait's default implementation.
902                 let def_id = match ty::impl_or_trait_item(&self.analysis
903                                                                .ty_cx,
904                                                           def_id) {
905                     ty::MethodTraitItem(method) => {
906                         method.provided_source.unwrap_or(def_id)
907                     }
908                 };
909                 (Some(def_id), decl_id)
910             }
911             typeck::MethodParam(mp) => {
912                 // method invoked on a type parameter
913                 let trait_item = ty::trait_item(&self.analysis.ty_cx,
914                                                 mp.trait_id,
915                                                 mp.method_num);
916                 match trait_item {
917                     ty::MethodTraitItem(method) => {
918                         (None, Some(method.def_id))
919                     }
920                 }
921             },
922             typeck::MethodObject(mo) => {
923                 // method invoked on a trait instance
924                 let trait_item = ty::trait_item(&self.analysis.ty_cx,
925                                                 mo.trait_id,
926                                                 mo.method_num);
927                 match trait_item {
928                     ty::MethodTraitItem(method) => {
929                         (None, Some(method.def_id))
930                     }
931                 }
932             },
933         };
934         let sub_span = self.span.sub_span_for_meth_name(ex.span);
935         self.fmt.meth_call_str(ex.span,
936                                sub_span,
937                                def_id,
938                                decl_id,
939                                self.cur_scope);
940
941         // walk receiver and args
942         visit::walk_exprs(self, args.as_slice());
943     }
944
945     fn process_pat(&mut self, p:&ast::Pat) {
946         if generated_code(p.span) {
947             return
948         }
949
950         match p.node {
951             ast::PatStruct(ref path, ref fields, _) => {
952                 self.collected_paths.push((p.id, path.clone(), false, recorder::StructRef));
953                 visit::walk_path(self, path);
954                 let struct_def = match self.lookup_type_ref(p.id) {
955                     Some(sd) => sd,
956                     None => {
957                         self.sess.span_bug(p.span,
958                                            format!("Could not find struct_def for `{}`",
959                                                    self.span.snippet(p.span)).as_slice());
960                     }
961                 };
962                 // The AST doesn't give us a span for the struct field, so we have
963                 // to figure out where it is by assuming it's the token before each colon.
964                 let field_spans = self.span.sub_spans_before_tokens(p.span,
965                                                                     token::COMMA,
966                                                                     token::COLON);
967                 if fields.len() != field_spans.len() {
968                     self.sess.span_bug(p.span,
969                         format!("Mismatched field count in '{}', found {}, expected {}",
970                                 self.span.snippet(p.span), field_spans.len(), fields.len()
971                                ).as_slice());
972                 }
973                 for (field, &span) in fields.iter().zip(field_spans.iter()) {
974                     self.visit_pat(&*field.pat);
975                     if span.is_none() {
976                         continue;
977                     }
978                     let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
979                     for f in fields.iter() {
980                         if f.name == field.ident.name {
981                             self.fmt.ref_str(recorder::VarRef,
982                                              p.span,
983                                              span,
984                                              f.id,
985                                              self.cur_scope);
986                             break;
987                         }
988                     }
989                 }
990             }
991             ast::PatEnum(ref path, _) => {
992                 self.collected_paths.push((p.id, path.clone(), false, recorder::VarRef));
993                 visit::walk_pat(self, p);
994             }
995             ast::PatIdent(bm, ref path1, ref optional_subpattern) => {
996                 let immut = match bm {
997                     // Even if the ref is mut, you can't change the ref, only
998                     // the data pointed at, so showing the initialising expression
999                     // is still worthwhile.
1000                     ast::BindByRef(_) => true,
1001                     ast::BindByValue(mt) => {
1002                         match mt {
1003                             ast::MutMutable => false,
1004                             ast::MutImmutable => true,
1005                         }
1006                     }
1007                 };
1008                 // collect path for either visit_local or visit_arm
1009                 let path = ast_util::ident_to_path(path1.span,path1.node);
1010                 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
1011                 match *optional_subpattern {
1012                     None => {}
1013                     Some(subpattern) => self.visit_pat(&*subpattern),
1014                 }
1015             }
1016             _ => visit::walk_pat(self, p)
1017         }
1018     }
1019 }
1020
1021 impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
1022     fn visit_item(&mut self, item: &ast::Item) {
1023         if generated_code(item.span) {
1024             return
1025         }
1026
1027         match item.node {
1028             ast::ItemFn(decl, _, _, ref ty_params, body) =>
1029                 self.process_fn(item, decl, ty_params, body),
1030             ast::ItemStatic(typ, mt, expr) =>
1031                 self.process_static(item, typ, mt, &*expr),
1032             ast::ItemStruct(def, ref ty_params) => self.process_struct(item, &*def, ty_params),
1033             ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1034             ast::ItemImpl(ref ty_params,
1035                           ref trait_ref,
1036                           typ,
1037                           ref impl_items) => {
1038                 self.process_impl(item,
1039                                   ty_params,
1040                                   trait_ref,
1041                                   typ,
1042                                   impl_items)
1043             }
1044             ast::ItemTrait(ref generics, _, ref trait_refs, ref methods) =>
1045                 self.process_trait(item, generics, trait_refs, methods),
1046             ast::ItemMod(ref m) => self.process_mod(item, m),
1047             ast::ItemTy(ty, ref ty_params) => {
1048                 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
1049                 let value = ty_to_string(&*ty);
1050                 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1051                 self.fmt.typedef_str(item.span,
1052                                      sub_span,
1053                                      item.id,
1054                                      qualname.as_slice(),
1055                                      value.as_slice());
1056
1057                 self.visit_ty(&*ty);
1058                 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
1059             },
1060             ast::ItemMac(_) => (),
1061             _ => visit::walk_item(self, item),
1062         }
1063     }
1064
1065     fn visit_generics(&mut self, generics: &ast::Generics) {
1066         for param in generics.ty_params.iter() {
1067             for bound in param.bounds.iter() {
1068                 match *bound {
1069                     ast::TraitTyParamBound(ref trait_ref) => {
1070                         self.process_trait_ref(trait_ref, None);
1071                     }
1072                     _ => {}
1073                 }
1074             }
1075             match param.default {
1076                 Some(ty) => self.visit_ty(&*ty),
1077                 None => (),
1078             }
1079         }
1080     }
1081
1082     // We don't actually index functions here, that is done in visit_item/ItemFn.
1083     // Here we just visit methods.
1084     fn visit_fn(&mut self,
1085                 fk: visit::FnKind<'v>,
1086                 fd: &'v ast::FnDecl,
1087                 b: &'v ast::Block,
1088                 s: Span,
1089                 _: NodeId) {
1090         if generated_code(s) {
1091             return;
1092         }
1093
1094         match fk {
1095             visit::FkMethod(_, _, method) => self.process_method(method),
1096             _ => visit::walk_fn(self, fk, fd, b, s),
1097         }
1098     }
1099
1100     fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
1101         match *tm {
1102             ast::RequiredMethod(ref method_type) => {
1103                 if generated_code(method_type.span) {
1104                     return;
1105                 }
1106
1107                 let mut scope_id;
1108                 let mut qualname = match ty::trait_of_item(&self.analysis.ty_cx,
1109                                                            ast_util::local_def(method_type.id)) {
1110                     Some(def_id) => {
1111                         scope_id = def_id.node;
1112                         ty::item_path_str(&self.analysis.ty_cx, def_id).append("::")
1113                     },
1114                     None => {
1115                         self.sess.span_bug(method_type.span,
1116                                            format!("Could not find trait for method {}",
1117                                                    method_type.id).as_slice());
1118                     },
1119                 };
1120
1121                 qualname.push_str(get_ident(method_type.ident).get());
1122                 let qualname = qualname.as_slice();
1123
1124                 let sub_span = self.span.sub_span_after_keyword(method_type.span, keywords::Fn);
1125                 self.fmt.method_decl_str(method_type.span,
1126                                          sub_span,
1127                                          method_type.id,
1128                                          qualname,
1129                                          scope_id);
1130
1131                 // walk arg and return types
1132                 for arg in method_type.decl.inputs.iter() {
1133                     self.visit_ty(&*arg.ty);
1134                 }
1135                 self.visit_ty(&*method_type.decl.output);
1136
1137                 self.process_generic_params(&method_type.generics,
1138                                             method_type.span,
1139                                             qualname,
1140                                             method_type.id);
1141             }
1142             ast::ProvidedMethod(method) => self.process_method(&*method),
1143         }
1144     }
1145
1146     fn visit_view_item(&mut self, i: &ast::ViewItem) {
1147         if generated_code(i.span) {
1148             return
1149         }
1150
1151         match i.node {
1152             ast::ViewItemUse(ref path) => {
1153                 match path.node {
1154                     ast::ViewPathSimple(ident, ref path, id) => {
1155                         let sub_span = self.span.span_for_last_ident(path.span);
1156                         let mod_id = match self.lookup_type_ref(id) {
1157                             Some(def_id) => {
1158                                 match self.lookup_def_kind(id, path.span) {
1159                                     Some(kind) => self.fmt.ref_str(kind,
1160                                                                    path.span,
1161                                                                    sub_span,
1162                                                                    def_id,
1163                                                                    self.cur_scope),
1164                                     None => {},
1165                                 }
1166                                 Some(def_id)
1167                             },
1168                             None => None,
1169                         };
1170
1171                         // 'use' always introduces an alias, if there is not an explicit
1172                         // one, there is an implicit one.
1173                         let sub_span =
1174                             match self.span.sub_span_before_token(path.span, token::EQ) {
1175                                 Some(sub_span) => Some(sub_span),
1176                                 None => sub_span,
1177                             };
1178
1179                         self.fmt.use_alias_str(path.span,
1180                                                sub_span,
1181                                                id,
1182                                                mod_id,
1183                                                get_ident(ident).get(),
1184                                                self.cur_scope);
1185                         self.write_sub_paths_truncated(path);
1186                     }
1187                     ast::ViewPathGlob(ref path, _) => {
1188                         self.write_sub_paths(path);
1189                     }
1190                     ast::ViewPathList(ref path, ref list, _) => {
1191                         for plid in list.iter() {
1192                             match plid.node {
1193                                 ast::PathListIdent { id, .. } => {
1194                                     match self.lookup_type_ref(id) {
1195                                         Some(def_id) =>
1196                                             match self.lookup_def_kind(id, plid.span) {
1197                                                 Some(kind) => {
1198                                                     self.fmt.ref_str(
1199                                                         kind, plid.span,
1200                                                         Some(plid.span),
1201                                                         def_id, self.cur_scope);
1202                                                 }
1203                                                 None => ()
1204                                             },
1205                                         None => ()
1206                                     }
1207                                 },
1208                                 ast::PathListMod { .. } => ()
1209                             }
1210                         }
1211
1212                         self.write_sub_paths(path);
1213                     }
1214                 }
1215             },
1216             ast::ViewItemExternCrate(ident, ref s, id) => {
1217                 let name = get_ident(ident);
1218                 let name = name.get();
1219                 let s = match *s {
1220                     Some((ref s, _)) => s.get().to_string(),
1221                     None => name.to_string(),
1222                 };
1223                 let sub_span = self.span.sub_span_after_keyword(i.span, keywords::Crate);
1224                 let cnum = match self.sess.cstore.find_extern_mod_stmt_cnum(id) {
1225                     Some(cnum) => cnum,
1226                     None => 0,
1227                 };
1228                 self.fmt.extern_crate_str(i.span,
1229                                           sub_span,
1230                                           id,
1231                                           cnum,
1232                                           name,
1233                                           s.as_slice(),
1234                                           self.cur_scope);
1235             },
1236         }
1237     }
1238
1239     fn visit_ty(&mut self, t: &ast::Ty) {
1240         if generated_code(t.span) {
1241             return
1242         }
1243
1244         match t.node {
1245             ast::TyPath(ref path, _, id) => {
1246                 match self.lookup_type_ref(id) {
1247                     Some(id) => {
1248                         let sub_span = self.span.sub_span_for_type_name(t.span);
1249                         self.fmt.ref_str(recorder::TypeRef,
1250                                          t.span,
1251                                          sub_span,
1252                                          id,
1253                                          self.cur_scope);
1254                     },
1255                     None => ()
1256                 }
1257
1258                 self.write_sub_paths_truncated(path);
1259
1260                 visit::walk_path(self, path);
1261             },
1262             _ => visit::walk_ty(self, t),
1263         }
1264     }
1265
1266     fn visit_expr(&mut self, ex: &ast::Expr) {
1267         if generated_code(ex.span) {
1268             return
1269         }
1270
1271         match ex.node {
1272             ast::ExprCall(_f, ref _args) => {
1273                 // Don't need to do anything for function calls,
1274                 // because just walking the callee path does what we want.
1275                 visit::walk_expr(self, ex);
1276             },
1277             ast::ExprPath(ref path) => self.process_path(ex, path),
1278             ast::ExprStruct(ref path, ref fields, ref base) =>
1279                 self.process_struct_lit(ex, path, fields, base),
1280             ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1281             ast::ExprField(sub_ex, ident, _) => {
1282                 if generated_code(sub_ex.span) {
1283                     return
1284                 }
1285
1286                 self.visit_expr(&*sub_ex);
1287
1288                 let t = ty::expr_ty_adjusted(&self.analysis.ty_cx, &*sub_ex);
1289                 let t_box = ty::get(t);
1290                 match t_box.sty {
1291                     ty::ty_struct(def_id, _) => {
1292                         let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
1293                         for f in fields.iter() {
1294                             if f.name == ident.node.name {
1295                                 let sub_span = self.span.span_for_last_ident(ex.span);
1296                                 self.fmt.ref_str(recorder::VarRef,
1297                                                  ex.span,
1298                                                  sub_span,
1299                                                  f.id,
1300                                                  self.cur_scope);
1301                                 break;
1302                             }
1303                         }
1304                     },
1305                     _ => self.sess.span_bug(ex.span,
1306                                             "Expected struct type, but not ty_struct"),
1307                 }
1308             },
1309             ast::ExprTupField(sub_ex, idx, _) => {
1310                 if generated_code(sub_ex.span) {
1311                     return
1312                 }
1313
1314                 self.visit_expr(&*sub_ex);
1315
1316                 let t = ty::expr_ty_adjusted(&self.analysis.ty_cx, &*sub_ex);
1317                 let t_box = ty::get(t);
1318                 match t_box.sty {
1319                     ty::ty_struct(def_id, _) => {
1320                         let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
1321                         for (i, f) in fields.iter().enumerate() {
1322                             if i == idx.node {
1323                                 let sub_span = self.span.span_for_last_ident(ex.span);
1324                                 self.fmt.ref_str(recorder::VarRef,
1325                                                  ex.span,
1326                                                  sub_span,
1327                                                  f.id,
1328                                                  self.cur_scope);
1329                                 break;
1330                             }
1331                         }
1332                     },
1333                     _ => self.sess.span_bug(ex.span,
1334                                             "Expected struct type, but not ty_struct"),
1335                 }
1336             },
1337             ast::ExprFnBlock(_, decl, body) => {
1338                 if generated_code(body.span) {
1339                     return
1340                 }
1341
1342                 let id = String::from_str("$").append(ex.id.to_string().as_slice());
1343                 self.process_formals(&decl.inputs, id.as_slice());
1344
1345                 // walk arg and return types
1346                 for arg in decl.inputs.iter() {
1347                     self.visit_ty(&*arg.ty);
1348                 }
1349                 self.visit_ty(&*decl.output);
1350
1351                 // walk the body
1352                 self.nest(ex.id, |v| v.visit_block(&*body));
1353             },
1354             _ => {
1355                 visit::walk_expr(self, ex)
1356             },
1357         }
1358     }
1359
1360     fn visit_mac(&mut self, _: &ast::Mac) {
1361         // Just stop, macros are poison to us.
1362     }
1363
1364     fn visit_pat(&mut self, p: &ast::Pat) {
1365         self.process_pat(p);
1366         if !self.collecting {
1367             self.collected_paths.clear();
1368         }
1369     }
1370
1371     fn visit_arm(&mut self, arm: &ast::Arm) {
1372         assert!(self.collected_paths.len() == 0 && !self.collecting);
1373         self.collecting = true;
1374
1375         for pattern in arm.pats.iter() {
1376             // collect paths from the arm's patterns
1377             self.visit_pat(&**pattern);
1378         }
1379         self.collecting = false;
1380         // process collected paths
1381         for &(id, ref p, ref immut, ref_kind) in self.collected_paths.iter() {
1382             let value = if *immut {
1383                 self.span.snippet(p.span).into_string()
1384             } else {
1385                 "<mutable>".to_string()
1386             };
1387             let sub_span = self.span.span_for_first_ident(p.span);
1388             let def_map = self.analysis.ty_cx.def_map.borrow();
1389             if !def_map.contains_key(&id) {
1390                 self.sess.span_bug(p.span,
1391                                    format!("def_map has no key for {} in visit_arm",
1392                                            id).as_slice());
1393             }
1394             let def = def_map.get(&id);
1395             match *def {
1396                 def::DefBinding(id, _)  => self.fmt.variable_str(p.span,
1397                                                                  sub_span,
1398                                                                  id,
1399                                                                  path_to_string(p).as_slice(),
1400                                                                  value.as_slice(),
1401                                                                  ""),
1402                 def::DefVariant(_,id,_) => self.fmt.ref_str(ref_kind,
1403                                                             p.span,
1404                                                             sub_span,
1405                                                             id,
1406                                                             self.cur_scope),
1407                 // FIXME(nrc) what is this doing here?
1408                 def::DefStatic(_, _) => {}
1409                 _ => error!("unexpected defintion kind when processing collected paths: {:?}", *def)
1410             }
1411         }
1412         self.collected_paths.clear();
1413         visit::walk_expr_opt(self, &arm.guard);
1414         self.visit_expr(&*arm.body);
1415     }
1416
1417     fn visit_stmt(&mut self, s: &ast::Stmt) {
1418         if generated_code(s.span) {
1419             return
1420         }
1421
1422         visit::walk_stmt(self, s)
1423     }
1424
1425     fn visit_local(&mut self, l: &ast::Local) {
1426         if generated_code(l.span) {
1427             return
1428         }
1429
1430         // The local could declare multiple new vars, we must walk the
1431         // pattern and collect them all.
1432         assert!(self.collected_paths.len() == 0 && !self.collecting);
1433         self.collecting = true;
1434         self.visit_pat(&*l.pat);
1435         self.collecting = false;
1436
1437         let value = self.span.snippet(l.span);
1438
1439         for &(id, ref p, ref immut, _) in self.collected_paths.iter() {
1440             let value = if *immut { value.to_string() } else { "<mutable>".to_string() };
1441             let types = self.analysis.ty_cx.node_types.borrow();
1442             let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *types.get(&(id as uint)));
1443             // Get the span only for the name of the variable (I hope the path
1444             // is only ever a variable name, but who knows?).
1445             let sub_span = self.span.span_for_last_ident(p.span);
1446             // Rust uses the id of the pattern for var lookups, so we'll use it too.
1447             self.fmt.variable_str(p.span,
1448                                   sub_span,
1449                                   id,
1450                                   path_to_string(p).as_slice(),
1451                                   value.as_slice(),
1452                                   typ.as_slice());
1453         }
1454         self.collected_paths.clear();
1455
1456         // Just walk the initialiser and type (don't want to walk the pattern again).
1457         self.visit_ty(&*l.ty);
1458         visit::walk_expr_opt(self, &l.init);
1459     }
1460 }
1461
1462 pub fn process_crate(sess: &Session,
1463                      krate: &ast::Crate,
1464                      analysis: &CrateAnalysis,
1465                      odir: &Option<Path>) {
1466     if generated_code(krate.span) {
1467         return;
1468     }
1469
1470     let cratename = match attr::find_crate_name(krate.attrs.as_slice()) {
1471         Some(name) => name.get().to_string(),
1472         None => {
1473             info!("Could not find crate name, using 'unknown_crate'");
1474             String::from_str("unknown_crate")
1475         },
1476     };
1477
1478     info!("Dumping crate {}", cratename);
1479
1480     // find a path to dump our data to
1481     let mut root_path = match os::getenv("DXR_RUST_TEMP_FOLDER") {
1482         Some(val) => Path::new(val),
1483         None => match *odir {
1484             Some(ref val) => val.join("dxr"),
1485             None => Path::new("dxr-temp"),
1486         },
1487     };
1488
1489     match fs::mkdir_recursive(&root_path, io::UserRWX) {
1490         Err(e) => sess.err(format!("Could not create directory {}: {}",
1491                            root_path.display(), e).as_slice()),
1492         _ => (),
1493     }
1494
1495     {
1496         let disp = root_path.display();
1497         info!("Writing output to {}", disp);
1498     }
1499
1500     // Create output file.
1501     let mut out_name = cratename.clone();
1502     out_name.push_str(".csv");
1503     root_path.push(out_name);
1504     let output_file = match File::create(&root_path) {
1505         Ok(f) => box f,
1506         Err(e) => {
1507             let disp = root_path.display();
1508             sess.fatal(format!("Could not open {}: {}", disp, e).as_slice());
1509         }
1510     };
1511     root_path.pop();
1512
1513     let mut visitor = DxrVisitor {
1514         sess: sess,
1515         analysis: analysis,
1516         collected_paths: vec!(),
1517         collecting: false,
1518         fmt: FmtStrs::new(box Recorder {
1519                             out: output_file as Box<Writer+'static>,
1520                             dump_spans: false,
1521                         },
1522                         SpanUtils {
1523                             sess: sess,
1524                             err_count: Cell::new(0)
1525                         },
1526                         cratename.clone()),
1527         span: SpanUtils {
1528             sess: sess,
1529             err_count: Cell::new(0)
1530         },
1531         cur_scope: 0
1532     };
1533
1534     visitor.dump_crate_info(cratename.as_slice(), krate);
1535
1536     visit::walk_crate(&mut visitor, krate);
1537 }