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.
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.
11 //! Write the output of rustc's analysis to an implementor of Dump. The data is
12 //! primarily designed to be used as input to the DXR tool, specifically its
13 //! Rust plugin. It could also be used by IDEs or other code browsing, search, or
14 //! cross-referencing tools.
16 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
17 //! info out from all over the place. We use Def IDs to identify objects. The
18 //! tricky part is getting syntactic (span, source text) and semantic (reference
19 //! Def IDs) information for parts of expressions which the compiler has discarded.
20 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
21 //! path and a reference to `baz`, but we want spans and references for all three
24 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
25 //! from spans (e.g., the span for `bar` from the above example path).
26 //! DumpVisitor walks the AST and processes it, and an implementor of Dump
27 //! is used for recording the output in a format-agnostic way (see CsvDumper
30 use rustc
::hir
::def
::Def
;
31 use rustc
::hir
::def_id
::DefId
;
32 use rustc
::session
::Session
;
33 use rustc
::ty
::{self, TyCtxt}
;
35 use std
::collections
::HashSet
;
38 use syntax
::ast
::{self, NodeId, PatKind}
;
39 use syntax
::codemap
::*;
40 use syntax
::parse
::token
::{self, keywords}
;
41 use syntax
::visit
::{self, Visitor}
;
42 use syntax
::print
::pprust
::{path_to_string, ty_to_string}
;
45 use rustc
::hir
::lowering
::{lower_expr, LoweringContext}
;
47 use super::{escape, generated_code, SaveContext, PathCollector}
;
49 use super::dump
::Dump
;
50 use super::span_utils
::SpanUtils
;
53 macro_rules
! down_cast_data
{
54 ($id
:ident
, $kind
:ident
, $sp
:expr
) => {
55 let $id
= if let super::Data
::$
kind(data
) = $id
{
58 span_bug
!($sp
, "unexpected data kind: {:?}", $id
);
63 pub struct DumpVisitor
<'l
, 'tcx
: 'l
, D
: 'l
> {
64 save_ctxt
: SaveContext
<'l
, 'tcx
>,
66 tcx
: &'l TyCtxt
<'tcx
>,
67 analysis
: &'l ty
::CrateAnalysis
<'l
>,
74 // Set of macro definition (callee) spans, and the set
75 // of macro use (callsite) spans. We store these to ensure
76 // we only write one macro def per unique macro definition, and
77 // one macro use per unique callsite span.
78 mac_defs
: HashSet
<Span
>,
79 mac_uses
: HashSet
<Span
>,
83 impl <'l
, 'tcx
, D
> DumpVisitor
<'l
, 'tcx
, D
>
86 pub fn new(tcx
: &'l TyCtxt
<'tcx
>,
87 lcx
: &'l LoweringContext
<'l
>,
88 analysis
: &'l ty
::CrateAnalysis
<'l
>,
90 -> DumpVisitor
<'l
, 'tcx
, D
> {
91 let span_utils
= SpanUtils
::new(&tcx
.sess
);
95 save_ctxt
: SaveContext
::from_span_utils(tcx
, lcx
, span_utils
.clone()),
98 span
: span_utils
.clone(),
100 mac_defs
: HashSet
::new(),
101 mac_uses
: HashSet
::new(),
105 fn nest
<F
>(&mut self, scope_id
: NodeId
, f
: F
)
106 where F
: FnOnce(&mut DumpVisitor
<'l
, 'tcx
, D
>)
108 let parent_scope
= self.cur_scope
;
109 self.cur_scope
= scope_id
;
111 self.cur_scope
= parent_scope
;
114 pub fn dump_crate_info(&mut self, name
: &str, krate
: &ast
::Crate
) {
115 let source_file
= self.tcx
.sess
.local_crate_source_file
.as_ref();
116 let crate_root
= source_file
.map(|source_file
| {
117 match source_file
.file_name() {
118 Some(_
) => source_file
.parent().unwrap().display().to_string(),
119 None
=> source_file
.display().to_string(),
123 // Info about all the external crates referenced from this crate.
124 let external_crates
= self.save_ctxt
.get_external_crates().into_iter().map(|c
| {
131 // The current crate.
132 let data
= CratePreludeData
{
133 crate_name
: name
.into(),
134 crate_root
: crate_root
,
135 external_crates
: external_crates
138 self.dumper
.crate_prelude(krate
.span
, data
);
141 // Return all non-empty prefixes of a path.
142 // For each prefix, we return the span for the last segment in the prefix and
143 // a str representation of the entire prefix.
144 fn process_path_prefixes(&self, path
: &ast
::Path
) -> Vec
<(Span
, String
)> {
145 let spans
= self.span
.spans_for_path_segments(path
);
147 // Paths to enums seem to not match their spans - the span includes all the
148 // variants too. But they seem to always be at the end, so I hope we can cope with
149 // always using the first ones. So, only error out if we don't have enough spans.
150 // What could go wrong...?
151 if spans
.len() < path
.segments
.len() {
152 if generated_code(path
.span
) {
155 error
!("Mis-calculated spans for path '{}'. Found {} spans, expected {}. Found spans:",
156 path_to_string(path
),
158 path
.segments
.len());
160 let loc
= self.sess
.codemap().lookup_char_pos(s
.lo
);
161 error
!(" '{}' in {}, line {}",
162 self.span
.snippet(*s
),
169 let mut result
: Vec
<(Span
, String
)> = vec
!();
171 let mut segs
= vec
!();
172 for (i
, (seg
, span
)) in path
.segments
.iter().zip(&spans
).enumerate() {
173 segs
.push(seg
.clone());
174 let sub_path
= ast
::Path
{
175 span
: *span
, // span for the last segment
179 let qualname
= if i
== 0 && path
.global
{
180 format
!("::{}", path_to_string(&sub_path
))
182 path_to_string(&sub_path
)
184 result
.push((*span
, qualname
));
185 segs
= sub_path
.segments
;
191 // The global arg allows us to override the global-ness of the path (which
192 // actually means 'does the path start with `::`', rather than 'is the path
193 // semantically global). We use the override for `use` imports (etc.) where
194 // the syntax is non-global, but the semantics are global.
195 fn write_sub_paths(&mut self, path
: &ast
::Path
, global
: bool
) {
196 let sub_paths
= self.process_path_prefixes(path
);
197 for (i
, &(ref span
, ref qualname
)) in sub_paths
.iter().enumerate() {
198 let qualname
= if i
== 0 && global
&& !path
.global
{
199 format
!("::{}", qualname
)
203 self.dumper
.mod_ref(path
.span
, ModRefData
{
206 scope
: self.cur_scope
,
208 }.normalize(&self.tcx
));
212 // As write_sub_paths, but does not process the last ident in the path (assuming it
213 // will be processed elsewhere). See note on write_sub_paths about global.
214 fn write_sub_paths_truncated(&mut self, path
: &ast
::Path
, global
: bool
) {
215 let sub_paths
= self.process_path_prefixes(path
);
216 let len
= sub_paths
.len();
221 let sub_paths
= &sub_paths
[..len
-1];
222 for (i
, &(ref span
, ref qualname
)) in sub_paths
.iter().enumerate() {
223 let qualname
= if i
== 0 && global
&& !path
.global
{
224 format
!("::{}", qualname
)
228 self.dumper
.mod_ref(path
.span
, ModRefData
{
231 scope
: self.cur_scope
,
233 }.normalize(&self.tcx
));
237 // As write_sub_paths, but expects a path of the form module_path::trait::method
238 // Where trait could actually be a struct too.
239 fn write_sub_path_trait_truncated(&mut self, path
: &ast
::Path
) {
240 let sub_paths
= self.process_path_prefixes(path
);
241 let len
= sub_paths
.len();
245 let sub_paths
= &sub_paths
[.. (len
-1)];
247 // write the trait part of the sub-path
248 let (ref span
, ref qualname
) = sub_paths
[len
-2];
249 self.dumper
.type_ref(path
.span
, TypeRefData
{
252 qualname
: qualname
.to_owned(),
256 // write the other sub-paths
260 let sub_paths
= &sub_paths
[..len
-2];
261 for &(ref span
, ref qualname
) in sub_paths
{
262 self.dumper
.mod_ref(path
.span
, ModRefData
{
264 qualname
: qualname
.to_owned(),
265 scope
: self.cur_scope
,
267 }.normalize(&self.tcx
));
271 // looks up anything, not just a type
272 fn lookup_type_ref(&self, ref_id
: NodeId
) -> Option
<DefId
> {
273 if !self.tcx
.def_map
.borrow().contains_key(&ref_id
) {
274 bug
!("def_map has no key for {} in lookup_type_ref", ref_id
);
276 let def
= self.tcx
.def_map
.borrow().get(&ref_id
).unwrap().full_def();
278 Def
::PrimTy(..) => None
,
279 Def
::SelfTy(..) => None
,
280 _
=> Some(def
.def_id()),
284 fn process_def_kind(&mut self,
287 sub_span
: Option
<Span
>,
290 if self.span
.filter_generated(sub_span
, span
) {
294 let def_map
= self.tcx
.def_map
.borrow();
295 if !def_map
.contains_key(&ref_id
) {
297 "def_map has no key for {} in lookup_def_kind",
300 let def
= def_map
.get(&ref_id
).unwrap().full_def();
303 Def
::ForeignMod(_
) => {
304 self.dumper
.mod_ref(span
, ModRefData
{
305 span
: sub_span
.expect("No span found for mod ref"),
306 ref_id
: Some(def_id
),
308 qualname
: String
::new()
309 }.normalize(&self.tcx
));
314 Def
::AssociatedTy(..) |
316 self.dumper
.type_ref(span
, TypeRefData
{
317 span
: sub_span
.expect("No span found for type ref"),
318 ref_id
: Some(def_id
),
320 qualname
: String
::new()
321 }.normalize(&self.tcx
));
325 Def
::AssociatedConst(..) |
329 self.dumper
.variable_ref(span
, VariableRefData
{
330 span
: sub_span
.expect("No span found for var ref"),
334 }.normalize(&self.tcx
));
337 self.dumper
.function_ref(span
, FunctionRefData
{
338 span
: sub_span
.expect("No span found for fn ref"),
341 }.normalize(&self.tcx
));
350 "process_def_kind for unexpected item: {:?}",
356 fn process_formals(&mut self, formals
: &Vec
<ast
::Arg
>, qualname
: &str) {
358 self.visit_pat(&arg
.pat
);
359 let mut collector
= PathCollector
::new();
360 collector
.visit_pat(&arg
.pat
);
361 let span_utils
= self.span
.clone();
362 for &(id
, ref p
, _
, _
) in &collector
.collected_paths
{
363 let typ
= self.tcx
.node_types().get(&id
).unwrap().to_string();
364 // get the span only for the name of the variable (I hope the path is only ever a
365 // variable name, but who knows?)
366 let sub_span
= span_utils
.span_for_last_ident(p
.span
);
367 if !self.span
.filter_generated(sub_span
, p
.span
) {
368 self.dumper
.variable(p
.span
, VariableData
{
370 span
: sub_span
.expect("No span found for variable"),
371 name
: path_to_string(p
),
372 qualname
: format
!("{}::{}", qualname
, path_to_string(p
)),
374 value
: String
::new(),
376 }.normalize(&self.tcx
));
382 fn process_method(&mut self,
383 sig
: &ast
::MethodSig
,
384 body
: Option
<&ast
::Block
>,
388 debug
!("process_method: {}:{}", id
, name
);
390 if let Some(method_data
) = self.save_ctxt
.get_method_data(id
, name
, span
) {
393 if !self.span
.filter_generated(Some(method_data
.span
), span
) {
394 self.dumper
.function(span
, method_data
.clone().normalize(&self.tcx
));
396 self.process_formals(&sig
.decl
.inputs
, &method_data
.qualname
);
398 if !self.span
.filter_generated(Some(method_data
.span
), span
) {
399 self.dumper
.method(span
, MethodData
{
401 span
: method_data
.span
,
402 scope
: method_data
.scope
,
403 qualname
: method_data
.qualname
.clone(),
404 }.normalize(&self.tcx
));
407 self.process_generic_params(&sig
.generics
, span
, &method_data
.qualname
, id
);
410 // walk arg and return types
411 for arg
in &sig
.decl
.inputs
{
412 self.visit_ty(&arg
.ty
);
415 if let ast
::FunctionRetTy
::Ty(ref ret_ty
) = sig
.decl
.output
{
416 self.visit_ty(ret_ty
);
420 if let Some(body
) = body
{
421 self.nest(id
, |v
| v
.visit_block(body
));
425 fn process_trait_ref(&mut self, trait_ref
: &ast
::TraitRef
) {
426 let trait_ref_data
= self.save_ctxt
.get_trait_ref_data(trait_ref
, self.cur_scope
);
427 if let Some(trait_ref_data
) = trait_ref_data
{
428 if !self.span
.filter_generated(Some(trait_ref_data
.span
), trait_ref
.path
.span
) {
429 self.dumper
.type_ref(trait_ref
.path
.span
, trait_ref_data
.normalize(&self.tcx
));
432 visit
::walk_path(self, &trait_ref
.path
);
436 fn process_struct_field_def(&mut self, field
: &ast
::StructField
, parent_id
: NodeId
) {
437 let field_data
= self.save_ctxt
.get_field_data(field
, parent_id
);
438 if let Some(mut field_data
) = field_data
{
439 if !self.span
.filter_generated(Some(field_data
.span
), field
.span
) {
440 field_data
.scope
= normalize_node_id(&self.tcx
, field_data
.scope
) as u32;
441 field_data
.value
= String
::new();
442 self.dumper
.variable(field
.span
, field_data
.normalize(&self.tcx
));
447 // Dump generic params bindings, then visit_generics
448 fn process_generic_params(&mut self,
449 generics
: &ast
::Generics
,
453 // We can't only use visit_generics since we don't have spans for param
454 // bindings, so we reparse the full_span to get those sub spans.
455 // However full span is the entire enum/fn/struct block, so we only want
456 // the first few to match the number of generics we're looking for.
457 let param_sub_spans
= self.span
.spans_for_ty_params(full_span
,
458 (generics
.ty_params
.len() as isize));
459 for (param
, param_ss
) in generics
.ty_params
.iter().zip(param_sub_spans
) {
460 // Append $id to name to make sure each one is unique
461 let name
= format
!("{}::{}${}",
463 escape(self.span
.snippet(param_ss
)),
465 if !self.span
.filter_generated(Some(param_ss
), full_span
) {
466 self.dumper
.typedef(full_span
, TypedefData
{
471 }.normalize(&self.tcx
));
474 self.visit_generics(generics
);
477 fn process_fn(&mut self,
480 ty_params
: &ast
::Generics
,
482 if let Some(fn_data
) = self.save_ctxt
.get_item_data(item
) {
483 down_cast_data
!(fn_data
, FunctionData
, item
.span
);
484 if !self.span
.filter_generated(Some(fn_data
.span
), item
.span
) {
485 self.dumper
.function(item
.span
, fn_data
.clone().normalize(&self.tcx
));
488 self.process_formals(&decl
.inputs
, &fn_data
.qualname
);
489 self.process_generic_params(ty_params
, item
.span
, &fn_data
.qualname
, item
.id
);
492 for arg
in &decl
.inputs
{
493 self.visit_ty(&arg
.ty
);
496 if let ast
::FunctionRetTy
::Ty(ref ret_ty
) = decl
.output
{
497 self.visit_ty(&ret_ty
);
500 self.nest(item
.id
, |v
| v
.visit_block(&body
));
503 fn process_static_or_const_item(&mut self, item
: &ast
::Item
, typ
: &ast
::Ty
, expr
: &ast
::Expr
) {
504 if let Some(var_data
) = self.save_ctxt
.get_item_data(item
) {
505 down_cast_data
!(var_data
, VariableData
, item
.span
);
506 if !self.span
.filter_generated(Some(var_data
.span
), item
.span
) {
507 let mut var_data
= var_data
;
508 var_data
.scope
= normalize_node_id(&self.tcx
, var_data
.scope
) as u32;
509 self.dumper
.variable(item
.span
, var_data
.normalize(&self.tcx
));
513 self.visit_expr(expr
);
516 fn process_const(&mut self,
522 let qualname
= format
!("::{}", self.tcx
.node_path_str(id
));
524 let sub_span
= self.span
.sub_span_after_keyword(span
, keywords
::Const
);
526 if !self.span
.filter_generated(sub_span
, span
) {
527 self.dumper
.variable(span
, VariableData
{
528 span
: sub_span
.expect("No span found for variable"),
530 name
: name
.to_string(),
532 value
: self.span
.snippet(expr
.span
),
533 type_value
: ty_to_string(&typ
),
534 scope
: normalize_node_id(&self.tcx
, self.cur_scope
) as u32
535 }.normalize(&self.tcx
));
538 // walk type and init value
540 self.visit_expr(expr
);
543 fn process_struct(&mut self,
545 def
: &ast
::VariantData
,
546 ty_params
: &ast
::Generics
) {
547 let qualname
= format
!("::{}", self.tcx
.node_path_str(item
.id
));
549 let val
= self.span
.snippet(item
.span
);
550 let sub_span
= self.span
.sub_span_after_keyword(item
.span
, keywords
::Struct
);
551 if !self.span
.filter_generated(sub_span
, item
.span
) {
552 self.dumper
.struct_data(item
.span
, StructData
{
553 span
: sub_span
.expect("No span found for struct"),
556 qualname
: qualname
.clone(),
557 scope
: self.cur_scope
,
559 }.normalize(&self.tcx
));
564 for field
in def
.fields() {
565 self.process_struct_field_def(field
, item
.id
);
566 self.visit_ty(&field
.ty
);
569 self.process_generic_params(ty_params
, item
.span
, &qualname
, item
.id
);
572 fn process_enum(&mut self,
574 enum_definition
: &ast
::EnumDef
,
575 ty_params
: &ast
::Generics
) {
576 let enum_data
= self.save_ctxt
.get_item_data(item
);
577 let enum_data
= match enum_data
{
581 down_cast_data
!(enum_data
, EnumData
, item
.span
);
582 let normalized
= enum_data
.clone().normalize(&self.tcx
);
583 if !self.span
.filter_generated(Some(normalized
.span
), item
.span
) {
584 self.dumper
.enum_data(item
.span
, normalized
);
587 for variant
in &enum_definition
.variants
{
588 let name
= &variant
.node
.name
.name
.as_str();
589 let mut qualname
= enum_data
.qualname
.clone();
590 qualname
.push_str("::");
591 qualname
.push_str(name
);
592 let val
= self.span
.snippet(variant
.span
);
594 match variant
.node
.data
{
595 ast
::VariantData
::Struct(..) => {
596 let sub_span
= self.span
.span_for_first_ident(variant
.span
);
597 if !self.span
.filter_generated(sub_span
, variant
.span
) {
598 self.dumper
.struct_variant(variant
.span
, StructVariantData
{
599 span
: sub_span
.expect("No span found for struct variant"),
600 id
: variant
.node
.data
.id(),
602 type_value
: enum_data
.qualname
.clone(),
604 scope
: enum_data
.scope
605 }.normalize(&self.tcx
));
609 let sub_span
= self.span
.span_for_first_ident(variant
.span
);
610 if !self.span
.filter_generated(sub_span
, variant
.span
) {
611 self.dumper
.tuple_variant(variant
.span
, TupleVariantData
{
612 span
: sub_span
.expect("No span found for tuple variant"),
613 id
: variant
.node
.data
.id(),
614 name
: name
.to_string(),
616 type_value
: enum_data
.qualname
.clone(),
618 scope
: enum_data
.scope
619 }.normalize(&self.tcx
));
625 for field
in variant
.node
.data
.fields() {
626 self.process_struct_field_def(field
, variant
.node
.data
.id());
627 self.visit_ty(&field
.ty
);
630 self.process_generic_params(ty_params
, item
.span
, &enum_data
.qualname
, enum_data
.id
);
633 fn process_impl(&mut self,
635 type_parameters
: &ast
::Generics
,
636 trait_ref
: &Option
<ast
::TraitRef
>,
638 impl_items
: &[ast
::ImplItem
]) {
639 let mut has_self_ref
= false;
640 if let Some(impl_data
) = self.save_ctxt
.get_item_data(item
) {
641 down_cast_data
!(impl_data
, ImplData
, item
.span
);
642 if let Some(ref self_ref
) = impl_data
.self_ref
{
644 if !self.span
.filter_generated(Some(self_ref
.span
), item
.span
) {
645 self.dumper
.type_ref(item
.span
, self_ref
.clone().normalize(&self.tcx
));
648 if let Some(ref trait_ref_data
) = impl_data
.trait_ref
{
649 if !self.span
.filter_generated(Some(trait_ref_data
.span
), item
.span
) {
650 self.dumper
.type_ref(item
.span
, trait_ref_data
.clone().normalize(&self.tcx
));
653 visit
::walk_path(self, &trait_ref
.as_ref().unwrap().path
);
656 if !self.span
.filter_generated(Some(impl_data
.span
), item
.span
) {
657 self.dumper
.impl_data(item
.span
, ImplData
{
659 span
: impl_data
.span
,
660 scope
: impl_data
.scope
,
661 trait_ref
: impl_data
.trait_ref
.map(|d
| d
.ref_id
.unwrap()),
662 self_ref
: impl_data
.self_ref
.map(|d
| d
.ref_id
.unwrap())
663 }.normalize(&self.tcx
));
669 self.process_generic_params(type_parameters
, item
.span
, "", item
.id
);
670 for impl_item
in impl_items
{
671 self.visit_impl_item(impl_item
);
675 fn process_trait(&mut self,
677 generics
: &ast
::Generics
,
678 trait_refs
: &ast
::TyParamBounds
,
679 methods
: &[ast
::TraitItem
]) {
680 let qualname
= format
!("::{}", self.tcx
.node_path_str(item
.id
));
681 let val
= self.span
.snippet(item
.span
);
682 let sub_span
= self.span
.sub_span_after_keyword(item
.span
, keywords
::Trait
);
683 if !self.span
.filter_generated(sub_span
, item
.span
) {
684 self.dumper
.trait_data(item
.span
, TraitData
{
685 span
: sub_span
.expect("No span found for trait"),
687 qualname
: qualname
.clone(),
688 scope
: self.cur_scope
,
690 }.normalize(&self.tcx
));
694 for super_bound
in trait_refs
.iter() {
695 let trait_ref
= match *super_bound
{
696 ast
::TraitTyParamBound(ref trait_ref
, _
) => {
699 ast
::RegionTyParamBound(..) => {
704 let trait_ref
= &trait_ref
.trait_ref
;
705 if let Some(id
) = self.lookup_type_ref(trait_ref
.ref_id
) {
706 let sub_span
= self.span
.sub_span_for_type_name(trait_ref
.path
.span
);
707 if !self.span
.filter_generated(sub_span
, trait_ref
.path
.span
) {
708 self.dumper
.type_ref(trait_ref
.path
.span
, TypeRefData
{
709 span
: sub_span
.expect("No span found for trait ref"),
711 scope
: self.cur_scope
,
712 qualname
: String
::new()
713 }.normalize(&self.tcx
));
716 if !self.span
.filter_generated(sub_span
, trait_ref
.path
.span
) {
717 let sub_span
= sub_span
.expect("No span for inheritance");
718 self.dumper
.inheritance(InheritanceData
{
722 }.normalize(&self.tcx
));
727 // walk generics and methods
728 self.process_generic_params(generics
, item
.span
, &qualname
, item
.id
);
729 for method
in methods
{
730 self.visit_trait_item(method
)
734 // `item` is the module in question, represented as an item.
735 fn process_mod(&mut self, item
: &ast
::Item
) {
736 if let Some(mod_data
) = self.save_ctxt
.get_item_data(item
) {
737 down_cast_data
!(mod_data
, ModData
, item
.span
);
738 if !self.span
.filter_generated(Some(mod_data
.span
), item
.span
) {
739 self.dumper
.mod_data(mod_data
.normalize(&self.tcx
));
744 fn process_path(&mut self, id
: NodeId
, path
: &ast
::Path
, ref_kind
: Option
<recorder
::Row
>) {
745 let path_data
= self.save_ctxt
.get_path_data(id
, path
);
746 if generated_code(path
.span
) && path_data
.is_none() {
750 let path_data
= match path_data
{
754 "Unexpected def kind while looking up path in `{}`",
755 self.span
.snippet(path
.span
))
760 Data
::VariableRefData(vrd
) => {
761 // FIXME: this whole block duplicates the code in process_def_kind
762 if !self.span
.filter_generated(Some(vrd
.span
), path
.span
) {
764 Some(recorder
::TypeRef
) => {
765 self.dumper
.type_ref(path
.span
, TypeRefData
{
767 ref_id
: Some(vrd
.ref_id
),
769 qualname
: String
::new()
770 }.normalize(&self.tcx
));
772 Some(recorder
::FnRef
) => {
773 self.dumper
.function_ref(path
.span
, FunctionRefData
{
777 }.normalize(&self.tcx
));
779 Some(recorder
::ModRef
) => {
780 self.dumper
.mod_ref(path
.span
, ModRefData
{
782 ref_id
: Some(vrd
.ref_id
),
784 qualname
: String
::new()
785 }.normalize(&self.tcx
));
787 Some(recorder
::VarRef
) | None
788 => self.dumper
.variable_ref(path
.span
, vrd
.normalize(&self.tcx
))
793 Data
::TypeRefData(trd
) => {
794 if !self.span
.filter_generated(Some(trd
.span
), path
.span
) {
795 self.dumper
.type_ref(path
.span
, trd
.normalize(&self.tcx
));
798 Data
::MethodCallData(mcd
) => {
799 if !self.span
.filter_generated(Some(mcd
.span
), path
.span
) {
800 self.dumper
.method_call(path
.span
, mcd
.normalize(&self.tcx
));
803 Data
::FunctionCallData(fcd
) => {
804 if !self.span
.filter_generated(Some(fcd
.span
), path
.span
) {
805 self.dumper
.function_call(path
.span
, fcd
.normalize(&self.tcx
));
809 span_bug
!(path
.span
, "Unexpected data: {:?}", path_data
);
813 // Modules or types in the path prefix.
814 let def_map
= self.tcx
.def_map
.borrow();
815 let def
= def_map
.get(&id
).unwrap().full_def();
817 Def
::Method(did
) => {
818 let ti
= self.tcx
.impl_or_trait_item(did
);
819 if let ty
::MethodTraitItem(m
) = ti
{
820 if m
.explicit_self
== ty
::ExplicitSelfCategory
::Static
{
821 self.write_sub_path_trait_truncated(path
);
828 Def
::AssociatedConst(..) |
831 Def
::Fn(..) => self.write_sub_paths_truncated(path
, false),
836 fn process_struct_lit(&mut self,
839 fields
: &Vec
<ast
::Field
>,
840 variant
: ty
::VariantDef
,
841 base
: &Option
<P
<ast
::Expr
>>) {
842 self.write_sub_paths_truncated(path
, false);
844 if let Some(struct_lit_data
) = self.save_ctxt
.get_expr_data(ex
) {
845 down_cast_data
!(struct_lit_data
, TypeRefData
, ex
.span
);
846 if !self.span
.filter_generated(Some(struct_lit_data
.span
), ex
.span
) {
847 self.dumper
.type_ref(ex
.span
, struct_lit_data
.normalize(&self.tcx
));
850 let scope
= self.save_ctxt
.enclosing_scope(ex
.id
);
852 for field
in fields
{
853 if let Some(field_data
) = self.save_ctxt
854 .get_field_ref_data(field
, variant
, scope
) {
856 if !self.span
.filter_generated(Some(field_data
.span
), field
.ident
.span
) {
857 self.dumper
.variable_ref(field
.ident
.span
, field_data
.normalize(&self.tcx
));
861 self.visit_expr(&field
.expr
)
865 walk_list
!(self, visit_expr
, base
);
868 fn process_method_call(&mut self, ex
: &ast
::Expr
, args
: &Vec
<P
<ast
::Expr
>>) {
869 if let Some(mcd
) = self.save_ctxt
.get_expr_data(ex
) {
870 down_cast_data
!(mcd
, MethodCallData
, ex
.span
);
871 if !self.span
.filter_generated(Some(mcd
.span
), ex
.span
) {
872 self.dumper
.method_call(ex
.span
, mcd
.normalize(&self.tcx
));
876 // walk receiver and args
877 walk_list
!(self, visit_expr
, args
);
880 fn process_pat(&mut self, p
: &ast
::Pat
) {
882 PatKind
::Struct(ref path
, ref fields
, _
) => {
883 visit
::walk_path(self, path
);
884 let adt
= self.tcx
.node_id_to_type(p
.id
).ty_adt_def().unwrap();
885 let def
= self.tcx
.def_map
.borrow()[&p
.id
].full_def();
886 let variant
= adt
.variant_of_def(def
);
888 for &Spanned { node: ref field, span }
in fields
{
889 let sub_span
= self.span
.span_for_first_ident(span
);
890 if let Some(f
) = variant
.find_field_named(field
.ident
.name
) {
891 if !self.span
.filter_generated(sub_span
, span
) {
892 self.dumper
.variable_ref(span
, VariableRefData
{
893 span
: sub_span
.expect("No span fund for var ref"),
895 scope
: self.cur_scope
,
897 }.normalize(&self.tcx
));
900 self.visit_pat(&field
.pat
);
903 _
=> visit
::walk_pat(self, p
),
908 fn process_var_decl(&mut self, p
: &ast
::Pat
, value
: String
) {
909 // The local could declare multiple new vars, we must walk the
910 // pattern and collect them all.
911 let mut collector
= PathCollector
::new();
912 collector
.visit_pat(&p
);
915 for &(id
, ref p
, immut
, _
) in &collector
.collected_paths
{
916 let value
= if immut
== ast
::Mutability
::Immutable
{
919 "<mutable>".to_string()
921 let types
= self.tcx
.node_types();
922 let typ
= types
.get(&id
).map(|t
| t
.to_string()).unwrap_or(String
::new());
923 // Get the span only for the name of the variable (I hope the path
924 // is only ever a variable name, but who knows?).
925 let sub_span
= self.span
.span_for_last_ident(p
.span
);
926 // Rust uses the id of the pattern for var lookups, so we'll use it too.
927 if !self.span
.filter_generated(sub_span
, p
.span
) {
928 self.dumper
.variable(p
.span
, VariableData
{
929 span
: sub_span
.expect("No span found for variable"),
931 name
: path_to_string(p
),
932 qualname
: format
!("{}${}", path_to_string(p
), id
),
936 }.normalize(&self.tcx
));
941 /// Extract macro use and definition information from the AST node defined
942 /// by the given NodeId, using the expansion information from the node's
945 /// If the span is not macro-generated, do nothing, else use callee and
946 /// callsite spans to record macro definition and use data, using the
947 /// mac_uses and mac_defs sets to prevent multiples.
948 fn process_macro_use(&mut self, span
: Span
, id
: NodeId
) {
949 let data
= match self.save_ctxt
.get_macro_use_data(span
, id
) {
953 let mut hasher
= SipHasher
::new();
954 data
.callee_span
.hash(&mut hasher
);
955 let hash
= hasher
.finish();
956 let qualname
= format
!("{}::{}", data
.name
, hash
);
957 // Don't write macro definition for imported macros
958 if !self.mac_defs
.contains(&data
.callee_span
)
960 self.mac_defs
.insert(data
.callee_span
);
961 if let Some(sub_span
) = self.span
.span_for_macro_def_name(data
.callee_span
) {
962 self.dumper
.macro_data(data
.callee_span
, MacroData
{
964 name
: data
.name
.clone(),
965 qualname
: qualname
.clone()
969 if !self.mac_uses
.contains(&data
.span
) {
970 self.mac_uses
.insert(data
.span
);
971 if let Some(sub_span
) = self.span
.span_for_macro_use_name(data
.span
) {
972 self.dumper
.macro_use(data
.span
, MacroUseData
{
977 callee_span
: data
.callee_span
,
978 imported
: data
.imported
979 }.normalize(&self.tcx
));
985 impl<'l
, 'tcx
, 'v
, D
: Dump
+ 'l
> Visitor
<'v
> for DumpVisitor
<'l
, 'tcx
, D
> {
986 fn visit_item(&mut self, item
: &ast
::Item
) {
987 use syntax
::ast
::ItemKind
::*;
988 self.process_macro_use(item
.span
, item
.id
);
990 Use(ref use_item
) => {
991 match use_item
.node
{
992 ast
::ViewPathSimple(ident
, ref path
) => {
993 let sub_span
= self.span
.span_for_last_ident(path
.span
);
994 let mod_id
= match self.lookup_type_ref(item
.id
) {
996 let scope
= self.cur_scope
;
997 self.process_def_kind(item
.id
, path
.span
, sub_span
, def_id
, scope
);
1004 // 'use' always introduces an alias, if there is not an explicit
1005 // one, there is an implicit one.
1006 let sub_span
= match self.span
.sub_span_after_keyword(use_item
.span
,
1008 Some(sub_span
) => Some(sub_span
),
1012 if !self.span
.filter_generated(sub_span
, path
.span
) {
1013 self.dumper
.use_data(path
.span
, UseData
{
1014 span
: sub_span
.expect("No span found for use"),
1017 name
: ident
.name
.to_string(),
1018 scope
: self.cur_scope
1019 }.normalize(&self.tcx
));
1021 self.write_sub_paths_truncated(path
, true);
1023 ast
::ViewPathGlob(ref path
) => {
1024 // Make a comma-separated list of names of imported modules.
1025 let mut names
= vec
![];
1026 let glob_map
= &self.analysis
.glob_map
;
1027 let glob_map
= glob_map
.as_ref().unwrap();
1028 if glob_map
.contains_key(&item
.id
) {
1029 for n
in glob_map
.get(&item
.id
).unwrap() {
1030 names
.push(n
.to_string());
1034 let sub_span
= self.span
1035 .sub_span_of_token(path
.span
, token
::BinOp(token
::Star
));
1036 if !self.span
.filter_generated(sub_span
, path
.span
) {
1037 self.dumper
.use_glob(path
.span
, UseGlobData
{
1038 span
: sub_span
.expect("No span found for use glob"),
1041 scope
: self.cur_scope
1042 }.normalize(&self.tcx
));
1044 self.write_sub_paths(path
, true);
1046 ast
::ViewPathList(ref path
, ref list
) => {
1049 ast
::PathListItemKind
::Ident { id, .. }
=> {
1050 let scope
= self.cur_scope
;
1051 if let Some(def_id
) = self.lookup_type_ref(id
) {
1052 self.process_def_kind(id
,
1059 ast
::PathListItemKind
::Mod { .. }
=> (),
1063 self.write_sub_paths(path
, true);
1067 ExternCrate(ref s
) => {
1068 let location
= match *s
{
1069 Some(s
) => s
.to_string(),
1070 None
=> item
.ident
.to_string(),
1072 let alias_span
= self.span
.span_for_last_ident(item
.span
);
1073 let cnum
= match self.sess
.cstore
.extern_mod_stmt_cnum(item
.id
) {
1078 if !self.span
.filter_generated(alias_span
, item
.span
) {
1079 self.dumper
.extern_crate(item
.span
, ExternCrateData
{
1081 name
: item
.ident
.name
.to_string(),
1084 span
: alias_span
.expect("No span found for extern crate"),
1085 scope
: self.cur_scope
,
1086 }.normalize(&self.tcx
));
1089 Fn(ref decl
, _
, _
, _
, ref ty_params
, ref body
) =>
1090 self.process_fn(item
, &decl
, ty_params
, &body
),
1091 Static(ref typ
, _
, ref expr
) =>
1092 self.process_static_or_const_item(item
, typ
, expr
),
1093 Const(ref typ
, ref expr
) =>
1094 self.process_static_or_const_item(item
, &typ
, &expr
),
1095 Struct(ref def
, ref ty_params
) => self.process_struct(item
, def
, ty_params
),
1096 Enum(ref def
, ref ty_params
) => self.process_enum(item
, def
, ty_params
),
1101 ref impl_items
) => {
1102 self.process_impl(item
, ty_params
, trait_ref
, &typ
, impl_items
)
1104 Trait(_
, ref generics
, ref trait_refs
, ref methods
) =>
1105 self.process_trait(item
, generics
, trait_refs
, methods
),
1107 self.process_mod(item
);
1108 self.nest(item
.id
, |v
| visit
::walk_mod(v
, m
));
1110 Ty(ref ty
, ref ty_params
) => {
1111 let qualname
= format
!("::{}", self.tcx
.node_path_str(item
.id
));
1112 let value
= ty_to_string(&ty
);
1113 let sub_span
= self.span
.sub_span_after_keyword(item
.span
, keywords
::Type
);
1114 if !self.span
.filter_generated(sub_span
, item
.span
) {
1115 self.dumper
.typedef(item
.span
, TypedefData
{
1116 span
: sub_span
.expect("No span found for typedef"),
1118 qualname
: qualname
.clone(),
1120 }.normalize(&self.tcx
));
1124 self.process_generic_params(ty_params
, item
.span
, &qualname
, item
.id
);
1127 _
=> visit
::walk_item(self, item
),
1131 fn visit_generics(&mut self, generics
: &ast
::Generics
) {
1132 for param
in generics
.ty_params
.iter() {
1133 for bound
in param
.bounds
.iter() {
1134 if let ast
::TraitTyParamBound(ref trait_ref
, _
) = *bound
{
1135 self.process_trait_ref(&trait_ref
.trait_ref
);
1138 if let Some(ref ty
) = param
.default {
1144 fn visit_trait_item(&mut self, trait_item
: &ast
::TraitItem
) {
1145 self.process_macro_use(trait_item
.span
, trait_item
.id
);
1146 match trait_item
.node
{
1147 ast
::TraitItemKind
::Const(ref ty
, Some(ref expr
)) => {
1148 self.process_const(trait_item
.id
,
1149 trait_item
.ident
.name
,
1154 ast
::TraitItemKind
::Method(ref sig
, ref body
) => {
1155 self.process_method(sig
,
1156 body
.as_ref().map(|x
| &**x
),
1158 trait_item
.ident
.name
,
1161 ast
::TraitItemKind
::Const(_
, None
) |
1162 ast
::TraitItemKind
::Type(..) => {}
1166 fn visit_impl_item(&mut self, impl_item
: &ast
::ImplItem
) {
1167 self.process_macro_use(impl_item
.span
, impl_item
.id
);
1168 match impl_item
.node
{
1169 ast
::ImplItemKind
::Const(ref ty
, ref expr
) => {
1170 self.process_const(impl_item
.id
,
1171 impl_item
.ident
.name
,
1176 ast
::ImplItemKind
::Method(ref sig
, ref body
) => {
1177 self.process_method(sig
,
1180 impl_item
.ident
.name
,
1183 ast
::ImplItemKind
::Type(_
) |
1184 ast
::ImplItemKind
::Macro(_
) => {}
1188 fn visit_ty(&mut self, t
: &ast
::Ty
) {
1189 self.process_macro_use(t
.span
, t
.id
);
1191 ast
::TyKind
::Path(_
, ref path
) => {
1192 if let Some(id
) = self.lookup_type_ref(t
.id
) {
1193 let sub_span
= self.span
.sub_span_for_type_name(t
.span
);
1194 if !self.span
.filter_generated(sub_span
, t
.span
) {
1195 self.dumper
.type_ref(t
.span
, TypeRefData
{
1196 span
: sub_span
.expect("No span found for type ref"),
1198 scope
: self.cur_scope
,
1199 qualname
: String
::new()
1200 }.normalize(&self.tcx
));
1204 self.write_sub_paths_truncated(path
, false);
1206 visit
::walk_path(self, path
);
1208 _
=> visit
::walk_ty(self, t
),
1212 fn visit_expr(&mut self, ex
: &ast
::Expr
) {
1213 self.process_macro_use(ex
.span
, ex
.id
);
1215 ast
::ExprKind
::Call(ref _f
, ref _args
) => {
1216 // Don't need to do anything for function calls,
1217 // because just walking the callee path does what we want.
1218 visit
::walk_expr(self, ex
);
1220 ast
::ExprKind
::Path(_
, ref path
) => {
1221 self.process_path(ex
.id
, path
, None
);
1222 visit
::walk_expr(self, ex
);
1224 ast
::ExprKind
::Struct(ref path
, ref fields
, ref base
) => {
1225 let hir_expr
= lower_expr(self.save_ctxt
.lcx
, ex
);
1226 let adt
= self.tcx
.expr_ty(&hir_expr
).ty_adt_def().unwrap();
1227 let def
= self.tcx
.resolve_expr(&hir_expr
);
1228 self.process_struct_lit(ex
, path
, fields
, adt
.variant_of_def(def
), base
)
1230 ast
::ExprKind
::MethodCall(_
, _
, ref args
) => self.process_method_call(ex
, args
),
1231 ast
::ExprKind
::Field(ref sub_ex
, _
) => {
1232 self.visit_expr(&sub_ex
);
1234 if let Some(field_data
) = self.save_ctxt
.get_expr_data(ex
) {
1235 down_cast_data
!(field_data
, VariableRefData
, ex
.span
);
1236 if !self.span
.filter_generated(Some(field_data
.span
), ex
.span
) {
1237 self.dumper
.variable_ref(ex
.span
, field_data
.normalize(&self.tcx
));
1241 ast
::ExprKind
::TupField(ref sub_ex
, idx
) => {
1242 self.visit_expr(&sub_ex
);
1244 let hir_node
= lower_expr(self.save_ctxt
.lcx
, sub_ex
);
1245 let ty
= &self.tcx
.expr_ty_adjusted(&hir_node
).sty
;
1247 ty
::TyStruct(def
, _
) => {
1248 let sub_span
= self.span
.sub_span_after_token(ex
.span
, token
::Dot
);
1249 if !self.span
.filter_generated(sub_span
, ex
.span
) {
1250 self.dumper
.variable_ref(ex
.span
, VariableRefData
{
1251 span
: sub_span
.expect("No span found for var ref"),
1252 ref_id
: def
.struct_variant().fields
[idx
.node
].did
,
1253 scope
: self.cur_scope
,
1255 }.normalize(&self.tcx
));
1258 ty
::TyTuple(_
) => {}
1259 _
=> span_bug
!(ex
.span
,
1260 "Expected struct or tuple type, found {:?}",
1264 ast
::ExprKind
::Closure(_
, ref decl
, ref body
) => {
1265 let mut id
= String
::from("$");
1266 id
.push_str(&ex
.id
.to_string());
1267 self.process_formals(&decl
.inputs
, &id
);
1269 // walk arg and return types
1270 for arg
in &decl
.inputs
{
1271 self.visit_ty(&arg
.ty
);
1274 if let ast
::FunctionRetTy
::Ty(ref ret_ty
) = decl
.output
{
1275 self.visit_ty(&ret_ty
);
1279 self.nest(ex
.id
, |v
| v
.visit_block(&body
));
1281 ast
::ExprKind
::ForLoop(ref pattern
, ref subexpression
, ref block
, _
) |
1282 ast
::ExprKind
::WhileLet(ref pattern
, ref subexpression
, ref block
, _
) => {
1283 let value
= self.span
.snippet(mk_sp(ex
.span
.lo
, subexpression
.span
.hi
));
1284 self.process_var_decl(pattern
, value
);
1285 visit
::walk_expr(self, subexpression
);
1286 visit
::walk_block(self, block
);
1288 ast
::ExprKind
::IfLet(ref pattern
, ref subexpression
, ref block
, ref opt_else
) => {
1289 let value
= self.span
.snippet(mk_sp(ex
.span
.lo
, subexpression
.span
.hi
));
1290 self.process_var_decl(pattern
, value
);
1291 visit
::walk_expr(self, subexpression
);
1292 visit
::walk_block(self, block
);
1293 opt_else
.as_ref().map(|el
| visit
::walk_expr(self, el
));
1296 visit
::walk_expr(self, ex
)
1301 fn visit_mac(&mut self, mac
: &ast
::Mac
) {
1302 // These shouldn't exist in the AST at this point, log a span bug.
1303 span_bug
!(mac
.span
, "macro invocation should have been expanded out of AST");
1306 fn visit_pat(&mut self, p
: &ast
::Pat
) {
1307 self.process_macro_use(p
.span
, p
.id
);
1308 self.process_pat(p
);
1311 fn visit_arm(&mut self, arm
: &ast
::Arm
) {
1312 let mut collector
= PathCollector
::new();
1313 for pattern
in &arm
.pats
{
1314 // collect paths from the arm's patterns
1315 collector
.visit_pat(&pattern
);
1316 self.visit_pat(&pattern
);
1319 // This is to get around borrow checking, because we need mut self to call process_path.
1320 let mut paths_to_process
= vec
![];
1322 // process collected paths
1323 for &(id
, ref p
, immut
, ref_kind
) in &collector
.collected_paths
{
1324 let def_map
= self.tcx
.def_map
.borrow();
1325 if !def_map
.contains_key(&id
) {
1326 span_bug
!(p
.span
, "def_map has no key for {} in visit_arm", id
);
1328 let def
= def_map
.get(&id
).unwrap().full_def();
1330 Def
::Local(_
, id
) => {
1331 let value
= if immut
== ast
::Mutability
::Immutable
{
1332 self.span
.snippet(p
.span
).to_string()
1334 "<mutable>".to_string()
1337 assert
!(p
.segments
.len() == 1,
1338 "qualified path for local variable def in arm");
1339 if !self.span
.filter_generated(Some(p
.span
), p
.span
) {
1340 self.dumper
.variable(p
.span
, VariableData
{
1343 name
: path_to_string(p
),
1344 qualname
: format
!("{}${}", path_to_string(p
), id
),
1346 type_value
: String
::new(),
1348 }.normalize(&self.tcx
));
1351 Def
::Variant(..) | Def
::Enum(..) |
1352 Def
::TyAlias(..) | Def
::Struct(..) => {
1353 paths_to_process
.push((id
, p
.clone(), Some(ref_kind
)))
1355 // FIXME(nrc) what are these doing here?
1358 Def
::AssociatedConst(..) => {}
1359 _
=> error
!("unexpected definition kind when processing collected paths: {:?}",
1364 for &(id
, ref path
, ref_kind
) in &paths_to_process
{
1365 self.process_path(id
, path
, ref_kind
);
1367 walk_list
!(self, visit_expr
, &arm
.guard
);
1368 self.visit_expr(&arm
.body
);
1371 fn visit_stmt(&mut self, s
: &ast
::Stmt
) {
1372 let id
= s
.node
.id();
1373 self.process_macro_use(s
.span
, id
.unwrap());
1374 visit
::walk_stmt(self, s
)
1377 fn visit_local(&mut self, l
: &ast
::Local
) {
1378 self.process_macro_use(l
.span
, l
.id
);
1379 let value
= self.span
.snippet(l
.span
);
1380 self.process_var_decl(&l
.pat
, value
);
1382 // Just walk the initialiser and type (don't want to walk the pattern again).
1383 walk_list
!(self, visit_ty
, &l
.ty
);
1384 walk_list
!(self, visit_expr
, &l
.init
);