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