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