]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/save/mod.rs
rustc: remove DefArg and DefBinding in favor of DefLocal.
[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::io;
39 use std::io::File;
40 use std::io::fs;
41 use std::os;
42
43 use syntax::ast;
44 use syntax::ast_util;
45 use syntax::ast_util::PostExpansionMethod;
46 use syntax::ast::{NodeId,DefId};
47 use syntax::ast_map::NodeItem;
48 use syntax::attr;
49 use syntax::codemap::*;
50 use syntax::parse::token;
51 use syntax::parse::token::{get_ident,keywords};
52 use syntax::owned_slice::OwnedSlice;
53 use syntax::visit;
54 use syntax::visit::Visitor;
55 use syntax::print::pprust::{path_to_string,ty_to_string};
56 use syntax::ptr::P;
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::DefAssociatedTy(..) |
231             def::DefTrait(_) => Some(recorder::TypeRef),
232             def::DefStatic(_, _) |
233             def::DefLocal(_, _) |
234             def::DefVariant(_, _, _) |
235             def::DefUpvar(_, _, _, _) => Some(recorder::VarRef),
236
237             def::DefFn(_, _) => Some(recorder::FnRef),
238
239             def::DefSelfTy(_) |
240             def::DefRegion(_) |
241             def::DefTyParamBinder(_) |
242             def::DefLabel(_) |
243             def::DefStaticMethod(_, _, _) |
244             def::DefTyParam(..) |
245             def::DefUse(_) |
246             def::DefMethod(_, _) |
247             def::DefPrimTy(_) => {
248                 self.sess.span_bug(span, format!("lookup_def_kind for unexpected item: {:?}",
249                                                  def).as_slice());
250             },
251         }
252     }
253
254     fn process_formals(&mut self, formals: &Vec<ast::Arg>, qualname: &str) {
255         for arg in formals.iter() {
256             assert!(self.collected_paths.len() == 0 && !self.collecting);
257             self.collecting = true;
258             self.visit_pat(&*arg.pat);
259             self.collecting = false;
260             let span_utils = self.span;
261             for &(id, ref p, _, _) in self.collected_paths.iter() {
262                 let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
263                     *self.analysis.ty_cx.node_types.borrow().get(&(id as uint)));
264                 // get the span only for the name of the variable (I hope the path is only ever a
265                 // variable name, but who knows?)
266                 self.fmt.formal_str(p.span,
267                                     span_utils.span_for_last_ident(p.span),
268                                     id,
269                                     qualname,
270                                     path_to_string(p).as_slice(),
271                                     typ.as_slice());
272             }
273             self.collected_paths.clear();
274         }
275     }
276
277     fn process_method(&mut self, method: &ast::Method) {
278         if generated_code(method.span) {
279             return;
280         }
281
282         let mut scope_id;
283         // The qualname for a method is the trait name or name of the struct in an impl in
284         // which the method is declared in followed by the method's name.
285         let mut qualname = match ty::impl_of_method(&self.analysis.ty_cx,
286                                                 ast_util::local_def(method.id)) {
287             Some(impl_id) => match self.analysis.ty_cx.map.get(impl_id.node) {
288                 NodeItem(item) => {
289                     scope_id = item.id;
290                     match item.node {
291                         ast::ItemImpl(_, _, ref ty, _) => {
292                             let mut result = String::from_str("<");
293                             result.push_str(ty_to_string(&**ty).as_slice());
294
295                             match ty::trait_of_item(&self.analysis.ty_cx,
296                                                     ast_util::local_def(method.id)) {
297                                 Some(def_id) => {
298                                     result.push_str(" as ");
299                                     result.push_str(
300                                         ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice());
301                                 },
302                                 None => {}
303                             }
304                             result.append(">::")
305                         }
306                         _ => {
307                             self.sess.span_bug(method.span,
308                                                format!("Container {} for method {} not an impl?",
309                                                        impl_id.node, method.id).as_slice());
310                         },
311                     }
312                 },
313                 _ => {
314                     self.sess.span_bug(method.span,
315                                        format!("Container {} for method {} is not a node item {:?}",
316                                                impl_id.node,
317                                                method.id,
318                                                self.analysis.ty_cx.map.get(impl_id.node)
319                                               ).as_slice());
320                 },
321             },
322             None => match ty::trait_of_item(&self.analysis.ty_cx,
323                                             ast_util::local_def(method.id)) {
324                 Some(def_id) => {
325                     scope_id = def_id.node;
326                     match self.analysis.ty_cx.map.get(def_id.node) {
327                         NodeItem(_) => {
328                             let result = ty::item_path_str(&self.analysis.ty_cx, def_id);
329                             result.append("::")
330                         }
331                         _ => {
332                             self.sess.span_bug(method.span,
333                                                format!("Could not find container {} for method {}",
334                                                        def_id.node, method.id).as_slice());
335                         }
336                     }
337                 },
338                 None => {
339                     self.sess.span_bug(method.span,
340                                        format!("Could not find container for method {}",
341                                                method.id).as_slice());
342                 },
343             },
344         };
345
346         qualname.push_str(get_ident(method.pe_ident()).get());
347         let qualname = qualname.as_slice();
348
349         // record the decl for this def (if it has one)
350         let decl_id = ty::trait_item_of_item(&self.analysis.ty_cx,
351                                              ast_util::local_def(method.id))
352             .filtered(|def_id| {
353                 match *def_id {
354                     ty::MethodTraitItemId(def_id) => {
355                         method.id != 0 && def_id.node == 0
356                     }
357                     ty::TypeTraitItemId(_) => false,
358                 }
359             });
360         let decl_id = match decl_id {
361             None => None,
362             Some(id) => Some(id.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::FnDecl,
470                   ty_params: &ast::Generics,
471                   body: &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::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::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(ref method) => {
647                     visit::walk_method_helper(self, &**method)
648                 }
649                 ast::TypeImplItem(ref typedef) => {
650                     visit::walk_ty(self, &*typedef.typ)
651                 }
652             }
653         }
654     }
655
656     fn process_trait(&mut self,
657                      item: &ast::Item,
658                      generics: &ast::Generics,
659                      trait_refs: &OwnedSlice<ast::TyParamBound>,
660                      methods: &Vec<ast::TraitItem>) {
661         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
662
663         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
664         self.fmt.trait_str(item.span,
665                            sub_span,
666                            item.id,
667                            qualname.as_slice(),
668                            self.cur_scope);
669
670         // super-traits
671         for super_bound in trait_refs.iter() {
672             let trait_ref = match *super_bound {
673                 ast::TraitTyParamBound(ref trait_ref) => {
674                     trait_ref
675                 }
676                 ast::UnboxedFnTyParamBound(..) | ast::RegionTyParamBound(..) => {
677                     continue;
678                 }
679             };
680
681             match self.lookup_type_ref(trait_ref.ref_id) {
682                 Some(id) => {
683                     let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
684                     self.fmt.ref_str(recorder::TypeRef,
685                                      trait_ref.path.span,
686                                      sub_span,
687                                      id,
688                                      self.cur_scope);
689                     self.fmt.inherit_str(trait_ref.path.span,
690                                          sub_span,
691                                          id,
692                                          item.id);
693                 },
694                 None => ()
695             }
696         }
697
698         // walk generics and methods
699         self.process_generic_params(generics, item.span, qualname.as_slice(), item.id);
700         for method in methods.iter() {
701             self.visit_trait_item(method)
702         }
703     }
704
705     fn process_mod(&mut self,
706                    item: &ast::Item,  // The module in question, represented as an item.
707                    m: &ast::Mod) {
708         let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
709
710         let cm = self.sess.codemap();
711         let filename = cm.span_to_filename(m.inner);
712
713         let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Mod);
714         self.fmt.mod_str(item.span,
715                          sub_span,
716                          item.id,
717                          qualname.as_slice(),
718                          self.cur_scope,
719                          filename.as_slice());
720
721         self.nest(item.id, |v| visit::walk_mod(v, m));
722     }
723
724     fn process_path(&mut self,
725                     ex: &ast::Expr,
726                     path: &ast::Path) {
727         if generated_code(path.span) {
728             return
729         }
730
731         let def_map = self.analysis.ty_cx.def_map.borrow();
732         if !def_map.contains_key(&ex.id) {
733             self.sess.span_bug(ex.span,
734                                format!("def_map has no key for {} in visit_expr",
735                                        ex.id).as_slice());
736         }
737         let def = def_map.get(&ex.id);
738         let sub_span = self.span.span_for_last_ident(ex.span);
739         match *def {
740             def::DefUpvar(id, _, _, _) |
741             def::DefLocal(id, _) => self.fmt.ref_str(recorder::VarRef,
742                                                      ex.span,
743                                                      sub_span,
744                                                      ast_util::local_def(id),
745                                                      self.cur_scope),
746             def::DefStatic(def_id,_) |
747             def::DefVariant(_, def_id, _) => self.fmt.ref_str(recorder::VarRef,
748                                                               ex.span,
749                                                               sub_span,
750                                                               def_id,
751                                                               self.cur_scope),
752             def::DefStruct(def_id) => self.fmt.ref_str(recorder::StructRef,
753                                                        ex.span,
754                                                        sub_span,
755                                                        def_id,
756                                                         self.cur_scope),
757             def::DefStaticMethod(declid, provenence, _) => {
758                 let sub_span = self.span.sub_span_for_meth_name(ex.span);
759                 let defid = if declid.krate == ast::LOCAL_CRATE {
760                     let ti = ty::impl_or_trait_item(&self.analysis.ty_cx,
761                                                     declid);
762                     match provenence {
763                         def::FromTrait(def_id) => {
764                             Some(ty::trait_items(&self.analysis.ty_cx,
765                                                  def_id)
766                                     .iter()
767                                     .find(|mr| {
768                                         mr.ident().name == ti.ident().name
769                                     })
770                                     .unwrap()
771                                     .def_id())
772                         }
773                         def::FromImpl(def_id) => {
774                             let impl_items = self.analysis
775                                                  .ty_cx
776                                                  .impl_items
777                                                  .borrow();
778                             Some(impl_items.get(&def_id)
779                                            .iter()
780                                            .find(|mr| {
781                                             ty::impl_or_trait_item(
782                                                 &self.analysis.ty_cx,
783                                                 mr.def_id()).ident().name ==
784                                                 ti.ident().name
785                                             })
786                                            .unwrap()
787                                            .def_id())
788                         }
789                     }
790                 } else {
791                     None
792                 };
793                 self.fmt.meth_call_str(ex.span,
794                                        sub_span,
795                                        defid,
796                                        Some(declid),
797                                        self.cur_scope);
798             },
799             def::DefFn(def_id, _) => self.fmt.fn_call_str(ex.span,
800                                                           sub_span,
801                                                           def_id,
802                                                           self.cur_scope),
803             _ => self.sess.span_bug(ex.span,
804                                     format!("Unexpected def kind while looking up path in '{}'",
805                                             self.span.snippet(ex.span)).as_slice()),
806         }
807         // modules or types in the path prefix
808         match *def {
809             def::DefStaticMethod(_, _, _) => {
810                 self.write_sub_path_trait_truncated(path);
811             },
812             def::DefLocal(_, _) |
813             def::DefStatic(_,_) |
814             def::DefStruct(_) |
815             def::DefFn(_, _) => self.write_sub_paths_truncated(path),
816             _ => {},
817         }
818
819         visit::walk_path(self, path);
820     }
821
822     fn process_struct_lit(&mut self,
823                           ex: &ast::Expr,
824                           path: &ast::Path,
825                           fields: &Vec<ast::Field>,
826                           base: &Option<P<ast::Expr>>) {
827         if generated_code(path.span) {
828             return
829         }
830
831         let mut struct_def: Option<DefId> = None;
832         match self.lookup_type_ref(ex.id) {
833             Some(id) => {
834                 struct_def = Some(id);
835                 let sub_span = self.span.span_for_last_ident(path.span);
836                 self.fmt.ref_str(recorder::StructRef,
837                                  path.span,
838                                  sub_span,
839                                  id,
840                                  self.cur_scope);
841             },
842             None => ()
843         }
844
845         self.write_sub_paths_truncated(path);
846
847         for field in fields.iter() {
848             match struct_def {
849                 Some(struct_def) => {
850                     let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
851                     for f in fields.iter() {
852                         if generated_code(field.ident.span) {
853                             continue;
854                         }
855                         if f.name == field.ident.node.name {
856                             // We don't really need a sub-span here, but no harm done
857                             let sub_span = self.span.span_for_last_ident(field.ident.span);
858                             self.fmt.ref_str(recorder::VarRef,
859                                              field.ident.span,
860                                              sub_span,
861                                              f.id,
862                                              self.cur_scope);
863                         }
864                     }
865                 }
866                 None => {}
867             }
868
869             self.visit_expr(&*field.expr)
870         }
871         visit::walk_expr_opt(self, base)
872     }
873
874     fn process_method_call(&mut self,
875                            ex: &ast::Expr,
876                            args: &Vec<P<ast::Expr>>) {
877         let method_map = self.analysis.ty_cx.method_map.borrow();
878         let method_callee = method_map.get(&typeck::MethodCall::expr(ex.id));
879         let (def_id, decl_id) = match method_callee.origin {
880             typeck::MethodStatic(def_id) |
881             typeck::MethodStaticUnboxedClosure(def_id) => {
882                 // method invoked on an object with a concrete type (not a static method)
883                 let decl_id =
884                     match ty::trait_item_of_item(&self.analysis.ty_cx,
885                                                  def_id) {
886                         None => None,
887                         Some(decl_id) => Some(decl_id.def_id()),
888                     };
889
890                 // This incantation is required if the method referenced is a
891                 // trait's default implementation.
892                 let def_id = match ty::impl_or_trait_item(&self.analysis
893                                                                .ty_cx,
894                                                           def_id) {
895                     ty::MethodTraitItem(method) => {
896                         method.provided_source.unwrap_or(def_id)
897                     }
898                     ty::TypeTraitItem(_) => def_id,
899                 };
900                 (Some(def_id), decl_id)
901             }
902             typeck::MethodParam(ref mp) => {
903                 // method invoked on a type parameter
904                 let trait_item = ty::trait_item(&self.analysis.ty_cx,
905                                                 mp.trait_ref.def_id,
906                                                 mp.method_num);
907                 (None, Some(trait_item.def_id()))
908             }
909             typeck::MethodObject(ref mo) => {
910                 // method invoked on a trait instance
911                 let trait_item = ty::trait_item(&self.analysis.ty_cx,
912                                                 mo.trait_ref.def_id,
913                                                 mo.method_num);
914                 (None, Some(trait_item.def_id()))
915             }
916         };
917         let sub_span = self.span.sub_span_for_meth_name(ex.span);
918         self.fmt.meth_call_str(ex.span,
919                                sub_span,
920                                def_id,
921                                decl_id,
922                                self.cur_scope);
923
924         // walk receiver and args
925         visit::walk_exprs(self, args.as_slice());
926     }
927
928     fn process_pat(&mut self, p:&ast::Pat) {
929         if generated_code(p.span) {
930             return
931         }
932
933         match p.node {
934             ast::PatStruct(ref path, ref fields, _) => {
935                 self.collected_paths.push((p.id, path.clone(), false, recorder::StructRef));
936                 visit::walk_path(self, path);
937                 let struct_def = match self.lookup_type_ref(p.id) {
938                     Some(sd) => sd,
939                     None => {
940                         self.sess.span_bug(p.span,
941                                            format!("Could not find struct_def for `{}`",
942                                                    self.span.snippet(p.span)).as_slice());
943                     }
944                 };
945                 // The AST doesn't give us a span for the struct field, so we have
946                 // to figure out where it is by assuming it's the token before each colon.
947                 let field_spans = self.span.sub_spans_before_tokens(p.span,
948                                                                     token::COMMA,
949                                                                     token::COLON);
950                 if fields.len() != field_spans.len() {
951                     self.sess.span_bug(p.span,
952                         format!("Mismatched field count in '{}', found {}, expected {}",
953                                 self.span.snippet(p.span), field_spans.len(), fields.len()
954                                ).as_slice());
955                 }
956                 for (field, &span) in fields.iter().zip(field_spans.iter()) {
957                     self.visit_pat(&*field.pat);
958                     if span.is_none() {
959                         continue;
960                     }
961                     let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
962                     for f in fields.iter() {
963                         if f.name == field.ident.name {
964                             self.fmt.ref_str(recorder::VarRef,
965                                              p.span,
966                                              span,
967                                              f.id,
968                                              self.cur_scope);
969                             break;
970                         }
971                     }
972                 }
973             }
974             ast::PatEnum(ref path, _) => {
975                 self.collected_paths.push((p.id, path.clone(), false, recorder::VarRef));
976                 visit::walk_pat(self, p);
977             }
978             ast::PatIdent(bm, ref path1, ref optional_subpattern) => {
979                 let immut = match bm {
980                     // Even if the ref is mut, you can't change the ref, only
981                     // the data pointed at, so showing the initialising expression
982                     // is still worthwhile.
983                     ast::BindByRef(_) => true,
984                     ast::BindByValue(mt) => {
985                         match mt {
986                             ast::MutMutable => false,
987                             ast::MutImmutable => true,
988                         }
989                     }
990                 };
991                 // collect path for either visit_local or visit_arm
992                 let path = ast_util::ident_to_path(path1.span,path1.node);
993                 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
994                 match *optional_subpattern {
995                     None => {}
996                     Some(ref subpattern) => self.visit_pat(&**subpattern)
997                 }
998             }
999             _ => visit::walk_pat(self, p)
1000         }
1001     }
1002 }
1003
1004 impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
1005     fn visit_item(&mut self, item: &ast::Item) {
1006         if generated_code(item.span) {
1007             return
1008         }
1009
1010         match item.node {
1011             ast::ItemFn(ref decl, _, _, ref ty_params, ref body) =>
1012                 self.process_fn(item, &**decl, ty_params, &**body),
1013             ast::ItemStatic(ref typ, mt, ref expr) =>
1014                 self.process_static(item, &**typ, mt, &**expr),
1015             ast::ItemStruct(ref def, ref ty_params) => self.process_struct(item, &**def, ty_params),
1016             ast::ItemEnum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1017             ast::ItemImpl(ref ty_params,
1018                           ref trait_ref,
1019                           ref typ,
1020                           ref impl_items) => {
1021                 self.process_impl(item,
1022                                   ty_params,
1023                                   trait_ref,
1024                                   &**typ,
1025                                   impl_items)
1026             }
1027             ast::ItemTrait(ref generics, _, ref trait_refs, ref methods) =>
1028                 self.process_trait(item, generics, trait_refs, methods),
1029             ast::ItemMod(ref m) => self.process_mod(item, m),
1030             ast::ItemTy(ref ty, ref ty_params) => {
1031                 let qualname = self.analysis.ty_cx.map.path_to_string(item.id);
1032                 let value = ty_to_string(&**ty);
1033                 let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type);
1034                 self.fmt.typedef_str(item.span,
1035                                      sub_span,
1036                                      item.id,
1037                                      qualname.as_slice(),
1038                                      value.as_slice());
1039
1040                 self.visit_ty(&**ty);
1041                 self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
1042             },
1043             ast::ItemMac(_) => (),
1044             _ => visit::walk_item(self, item),
1045         }
1046     }
1047
1048     fn visit_generics(&mut self, generics: &ast::Generics) {
1049         for param in generics.ty_params.iter() {
1050             for bound in param.bounds.iter() {
1051                 match *bound {
1052                     ast::TraitTyParamBound(ref trait_ref) => {
1053                         self.process_trait_ref(trait_ref, None);
1054                     }
1055                     _ => {}
1056                 }
1057             }
1058             match param.default {
1059                 Some(ref ty) => self.visit_ty(&**ty),
1060                 None => {}
1061             }
1062         }
1063     }
1064
1065     // We don't actually index functions here, that is done in visit_item/ItemFn.
1066     // Here we just visit methods.
1067     fn visit_fn(&mut self,
1068                 fk: visit::FnKind<'v>,
1069                 fd: &'v ast::FnDecl,
1070                 b: &'v ast::Block,
1071                 s: Span,
1072                 _: NodeId) {
1073         if generated_code(s) {
1074             return;
1075         }
1076
1077         match fk {
1078             visit::FkMethod(_, _, method) => self.process_method(method),
1079             _ => visit::walk_fn(self, fk, fd, b, s),
1080         }
1081     }
1082
1083     fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
1084         match *tm {
1085             ast::RequiredMethod(ref method_type) => {
1086                 if generated_code(method_type.span) {
1087                     return;
1088                 }
1089
1090                 let mut scope_id;
1091                 let mut qualname = match ty::trait_of_item(&self.analysis.ty_cx,
1092                                                            ast_util::local_def(method_type.id)) {
1093                     Some(def_id) => {
1094                         scope_id = def_id.node;
1095                         ty::item_path_str(&self.analysis.ty_cx, def_id).append("::")
1096                     },
1097                     None => {
1098                         self.sess.span_bug(method_type.span,
1099                                            format!("Could not find trait for method {}",
1100                                                    method_type.id).as_slice());
1101                     },
1102                 };
1103
1104                 qualname.push_str(get_ident(method_type.ident).get());
1105                 let qualname = qualname.as_slice();
1106
1107                 let sub_span = self.span.sub_span_after_keyword(method_type.span, keywords::Fn);
1108                 self.fmt.method_decl_str(method_type.span,
1109                                          sub_span,
1110                                          method_type.id,
1111                                          qualname,
1112                                          scope_id);
1113
1114                 // walk arg and return types
1115                 for arg in method_type.decl.inputs.iter() {
1116                     self.visit_ty(&*arg.ty);
1117                 }
1118                 self.visit_ty(&*method_type.decl.output);
1119
1120                 self.process_generic_params(&method_type.generics,
1121                                             method_type.span,
1122                                             qualname,
1123                                             method_type.id);
1124             }
1125             ast::ProvidedMethod(ref method) => self.process_method(&**method),
1126             ast::TypeTraitItem(_) => {}
1127         }
1128     }
1129
1130     fn visit_view_item(&mut self, i: &ast::ViewItem) {
1131         if generated_code(i.span) {
1132             return
1133         }
1134
1135         match i.node {
1136             ast::ViewItemUse(ref path) => {
1137                 match path.node {
1138                     ast::ViewPathSimple(ident, ref path, id) => {
1139                         let sub_span = self.span.span_for_last_ident(path.span);
1140                         let mod_id = match self.lookup_type_ref(id) {
1141                             Some(def_id) => {
1142                                 match self.lookup_def_kind(id, path.span) {
1143                                     Some(kind) => self.fmt.ref_str(kind,
1144                                                                    path.span,
1145                                                                    sub_span,
1146                                                                    def_id,
1147                                                                    self.cur_scope),
1148                                     None => {},
1149                                 }
1150                                 Some(def_id)
1151                             },
1152                             None => None,
1153                         };
1154
1155                         // 'use' always introduces an alias, if there is not an explicit
1156                         // one, there is an implicit one.
1157                         let sub_span =
1158                             match self.span.sub_span_before_token(path.span, token::EQ) {
1159                                 Some(sub_span) => Some(sub_span),
1160                                 None => sub_span,
1161                             };
1162
1163                         self.fmt.use_alias_str(path.span,
1164                                                sub_span,
1165                                                id,
1166                                                mod_id,
1167                                                get_ident(ident).get(),
1168                                                self.cur_scope);
1169                         self.write_sub_paths_truncated(path);
1170                     }
1171                     ast::ViewPathGlob(ref path, _) => {
1172                         self.write_sub_paths(path);
1173                     }
1174                     ast::ViewPathList(ref path, ref list, _) => {
1175                         for plid in list.iter() {
1176                             match plid.node {
1177                                 ast::PathListIdent { id, .. } => {
1178                                     match self.lookup_type_ref(id) {
1179                                         Some(def_id) =>
1180                                             match self.lookup_def_kind(id, plid.span) {
1181                                                 Some(kind) => {
1182                                                     self.fmt.ref_str(
1183                                                         kind, plid.span,
1184                                                         Some(plid.span),
1185                                                         def_id, self.cur_scope);
1186                                                 }
1187                                                 None => ()
1188                                             },
1189                                         None => ()
1190                                     }
1191                                 },
1192                                 ast::PathListMod { .. } => ()
1193                             }
1194                         }
1195
1196                         self.write_sub_paths(path);
1197                     }
1198                 }
1199             },
1200             ast::ViewItemExternCrate(ident, ref s, id) => {
1201                 let name = get_ident(ident);
1202                 let name = name.get();
1203                 let s = match *s {
1204                     Some((ref s, _)) => s.get().to_string(),
1205                     None => name.to_string(),
1206                 };
1207                 let sub_span = self.span.sub_span_after_keyword(i.span, keywords::Crate);
1208                 let cnum = match self.sess.cstore.find_extern_mod_stmt_cnum(id) {
1209                     Some(cnum) => cnum,
1210                     None => 0,
1211                 };
1212                 self.fmt.extern_crate_str(i.span,
1213                                           sub_span,
1214                                           id,
1215                                           cnum,
1216                                           name,
1217                                           s.as_slice(),
1218                                           self.cur_scope);
1219             },
1220         }
1221     }
1222
1223     fn visit_ty(&mut self, t: &ast::Ty) {
1224         if generated_code(t.span) {
1225             return
1226         }
1227
1228         match t.node {
1229             ast::TyPath(ref path, _, id) => {
1230                 match self.lookup_type_ref(id) {
1231                     Some(id) => {
1232                         let sub_span = self.span.sub_span_for_type_name(t.span);
1233                         self.fmt.ref_str(recorder::TypeRef,
1234                                          t.span,
1235                                          sub_span,
1236                                          id,
1237                                          self.cur_scope);
1238                     },
1239                     None => ()
1240                 }
1241
1242                 self.write_sub_paths_truncated(path);
1243
1244                 visit::walk_path(self, path);
1245             },
1246             _ => visit::walk_ty(self, t),
1247         }
1248     }
1249
1250     fn visit_expr(&mut self, ex: &ast::Expr) {
1251         if generated_code(ex.span) {
1252             return
1253         }
1254
1255         match ex.node {
1256             ast::ExprCall(ref _f, ref _args) => {
1257                 // Don't need to do anything for function calls,
1258                 // because just walking the callee path does what we want.
1259                 visit::walk_expr(self, ex);
1260             },
1261             ast::ExprPath(ref path) => self.process_path(ex, path),
1262             ast::ExprStruct(ref path, ref fields, ref base) =>
1263                 self.process_struct_lit(ex, path, fields, base),
1264             ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
1265             ast::ExprField(ref sub_ex, ident, _) => {
1266                 if generated_code(sub_ex.span) {
1267                     return
1268                 }
1269
1270                 self.visit_expr(&**sub_ex);
1271
1272                 let t = ty::expr_ty_adjusted(&self.analysis.ty_cx, &**sub_ex);
1273                 let t_box = ty::get(t);
1274                 match t_box.sty {
1275                     ty::ty_struct(def_id, _) => {
1276                         let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
1277                         for f in fields.iter() {
1278                             if f.name == ident.node.name {
1279                                 let sub_span = self.span.span_for_last_ident(ex.span);
1280                                 self.fmt.ref_str(recorder::VarRef,
1281                                                  ex.span,
1282                                                  sub_span,
1283                                                  f.id,
1284                                                  self.cur_scope);
1285                                 break;
1286                             }
1287                         }
1288                     },
1289                     _ => self.sess.span_bug(ex.span,
1290                                             "Expected struct type, but not ty_struct"),
1291                 }
1292             },
1293             ast::ExprTupField(ref sub_ex, idx, _) => {
1294                 if generated_code(sub_ex.span) {
1295                     return
1296                 }
1297
1298                 self.visit_expr(&**sub_ex);
1299
1300                 let t = ty::expr_ty_adjusted(&self.analysis.ty_cx, &**sub_ex);
1301                 let t_box = ty::get(t);
1302                 match t_box.sty {
1303                     ty::ty_struct(def_id, _) => {
1304                         let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, def_id);
1305                         for (i, f) in fields.iter().enumerate() {
1306                             if i == idx.node {
1307                                 let sub_span = self.span.span_for_last_ident(ex.span);
1308                                 self.fmt.ref_str(recorder::VarRef,
1309                                                  ex.span,
1310                                                  sub_span,
1311                                                  f.id,
1312                                                  self.cur_scope);
1313                                 break;
1314                             }
1315                         }
1316                     },
1317                     _ => self.sess.span_bug(ex.span,
1318                                             "Expected struct type, but not ty_struct"),
1319                 }
1320             },
1321             ast::ExprFnBlock(_, ref decl, ref body) => {
1322                 if generated_code(body.span) {
1323                     return
1324                 }
1325
1326                 let id = String::from_str("$").append(ex.id.to_string().as_slice());
1327                 self.process_formals(&decl.inputs, id.as_slice());
1328
1329                 // walk arg and return types
1330                 for arg in decl.inputs.iter() {
1331                     self.visit_ty(&*arg.ty);
1332                 }
1333                 self.visit_ty(&*decl.output);
1334
1335                 // walk the body
1336                 self.nest(ex.id, |v| v.visit_block(&**body));
1337             },
1338             _ => {
1339                 visit::walk_expr(self, ex)
1340             },
1341         }
1342     }
1343
1344     fn visit_mac(&mut self, _: &ast::Mac) {
1345         // Just stop, macros are poison to us.
1346     }
1347
1348     fn visit_pat(&mut self, p: &ast::Pat) {
1349         self.process_pat(p);
1350         if !self.collecting {
1351             self.collected_paths.clear();
1352         }
1353     }
1354
1355     fn visit_arm(&mut self, arm: &ast::Arm) {
1356         assert!(self.collected_paths.len() == 0 && !self.collecting);
1357         self.collecting = true;
1358
1359         for pattern in arm.pats.iter() {
1360             // collect paths from the arm's patterns
1361             self.visit_pat(&**pattern);
1362         }
1363         self.collecting = false;
1364         // process collected paths
1365         for &(id, ref p, ref immut, ref_kind) in self.collected_paths.iter() {
1366             let value = if *immut {
1367                 self.span.snippet(p.span).into_string()
1368             } else {
1369                 "<mutable>".to_string()
1370             };
1371             let sub_span = self.span.span_for_first_ident(p.span);
1372             let def_map = self.analysis.ty_cx.def_map.borrow();
1373             if !def_map.contains_key(&id) {
1374                 self.sess.span_bug(p.span,
1375                                    format!("def_map has no key for {} in visit_arm",
1376                                            id).as_slice());
1377             }
1378             let def = def_map.get(&id);
1379             match *def {
1380                 def::DefLocal(id, _)  => self.fmt.variable_str(p.span,
1381                                                                sub_span,
1382                                                                id,
1383                                                                path_to_string(p).as_slice(),
1384                                                                value.as_slice(),
1385                                                                ""),
1386                 def::DefVariant(_,id,_) => self.fmt.ref_str(ref_kind,
1387                                                             p.span,
1388                                                             sub_span,
1389                                                             id,
1390                                                             self.cur_scope),
1391                 // FIXME(nrc) what is this doing here?
1392                 def::DefStatic(_, _) => {}
1393                 _ => error!("unexpected definition kind when processing collected paths: {:?}",
1394                             *def)
1395             }
1396         }
1397         self.collected_paths.clear();
1398         visit::walk_expr_opt(self, &arm.guard);
1399         self.visit_expr(&*arm.body);
1400     }
1401
1402     fn visit_stmt(&mut self, s: &ast::Stmt) {
1403         if generated_code(s.span) {
1404             return
1405         }
1406
1407         visit::walk_stmt(self, s)
1408     }
1409
1410     fn visit_local(&mut self, l: &ast::Local) {
1411         if generated_code(l.span) {
1412             return
1413         }
1414
1415         // The local could declare multiple new vars, we must walk the
1416         // pattern and collect them all.
1417         assert!(self.collected_paths.len() == 0 && !self.collecting);
1418         self.collecting = true;
1419         self.visit_pat(&*l.pat);
1420         self.collecting = false;
1421
1422         let value = self.span.snippet(l.span);
1423
1424         for &(id, ref p, ref immut, _) in self.collected_paths.iter() {
1425             let value = if *immut { value.to_string() } else { "<mutable>".to_string() };
1426             let types = self.analysis.ty_cx.node_types.borrow();
1427             let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *types.get(&(id as uint)));
1428             // Get the span only for the name of the variable (I hope the path
1429             // is only ever a variable name, but who knows?).
1430             let sub_span = self.span.span_for_last_ident(p.span);
1431             // Rust uses the id of the pattern for var lookups, so we'll use it too.
1432             self.fmt.variable_str(p.span,
1433                                   sub_span,
1434                                   id,
1435                                   path_to_string(p).as_slice(),
1436                                   value.as_slice(),
1437                                   typ.as_slice());
1438         }
1439         self.collected_paths.clear();
1440
1441         // Just walk the initialiser and type (don't want to walk the pattern again).
1442         self.visit_ty(&*l.ty);
1443         visit::walk_expr_opt(self, &l.init);
1444     }
1445 }
1446
1447 pub fn process_crate(sess: &Session,
1448                      krate: &ast::Crate,
1449                      analysis: &CrateAnalysis,
1450                      odir: &Option<Path>) {
1451     if generated_code(krate.span) {
1452         return;
1453     }
1454
1455     let cratename = match attr::find_crate_name(krate.attrs.as_slice()) {
1456         Some(name) => name.get().to_string(),
1457         None => {
1458             info!("Could not find crate name, using 'unknown_crate'");
1459             String::from_str("unknown_crate")
1460         },
1461     };
1462
1463     info!("Dumping crate {}", cratename);
1464
1465     // find a path to dump our data to
1466     let mut root_path = match os::getenv("DXR_RUST_TEMP_FOLDER") {
1467         Some(val) => Path::new(val),
1468         None => match *odir {
1469             Some(ref val) => val.join("dxr"),
1470             None => Path::new("dxr-temp"),
1471         },
1472     };
1473
1474     match fs::mkdir_recursive(&root_path, io::UserRWX) {
1475         Err(e) => sess.err(format!("Could not create directory {}: {}",
1476                            root_path.display(), e).as_slice()),
1477         _ => (),
1478     }
1479
1480     {
1481         let disp = root_path.display();
1482         info!("Writing output to {}", disp);
1483     }
1484
1485     // Create output file.
1486     let mut out_name = cratename.clone();
1487     out_name.push_str(".csv");
1488     root_path.push(out_name);
1489     let output_file = match File::create(&root_path) {
1490         Ok(f) => box f,
1491         Err(e) => {
1492             let disp = root_path.display();
1493             sess.fatal(format!("Could not open {}: {}", disp, e).as_slice());
1494         }
1495     };
1496     root_path.pop();
1497
1498     let mut visitor = DxrVisitor {
1499         sess: sess,
1500         analysis: analysis,
1501         collected_paths: vec!(),
1502         collecting: false,
1503         fmt: FmtStrs::new(box Recorder {
1504                             out: output_file as Box<Writer+'static>,
1505                             dump_spans: false,
1506                         },
1507                         SpanUtils {
1508                             sess: sess,
1509                             err_count: Cell::new(0)
1510                         },
1511                         cratename.clone()),
1512         span: SpanUtils {
1513             sess: sess,
1514             err_count: Cell::new(0)
1515         },
1516         cur_scope: 0
1517     };
1518
1519     visitor.dump_crate_info(cratename.as_slice(), krate);
1520
1521     visit::walk_crate(&mut visitor, krate);
1522 }