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