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