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