-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
dump_visitor.rs
1785 lines (1638 loc) · 67.5 KB
/
dump_visitor.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Write the output of rustc's analysis to an implementor of Dump.
//!
//! Dumping the analysis is implemented by walking the AST and getting a bunch of
//! info out from all over the place. We use Def IDs to identify objects. The
//! tricky part is getting syntactic (span, source text) and semantic (reference
//! Def IDs) information for parts of expressions which the compiler has discarded.
//! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
//! path and a reference to `baz`, but we want spans and references for all three
//! idents.
//!
//! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
//! from spans (e.g., the span for `bar` from the above example path).
//! DumpVisitor walks the AST and processes it, and an implementor of Dump
//! is used for recording the output in a format-agnostic way (see CsvDumper
//! for an example).
use rustc::hir::def::Def as HirDef;
use rustc::hir::def_id::DefId;
use rustc::hir::map::Node;
use rustc::ty::{self, TyCtxt};
use rustc_data_structures::fx::FxHashSet;
use std::path::Path;
use syntax::ast::{self, Attribute, NodeId, PatKind, CRATE_NODE_ID};
use syntax::parse::token;
use syntax::symbol::keywords;
use syntax::visit::{self, Visitor};
use syntax::print::pprust::{bounds_to_string, generics_to_string, path_to_string, ty_to_string};
use syntax::ptr::P;
use syntax::codemap::{Spanned, DUMMY_SP};
use syntax_pos::*;
use {escape, generated_code, lower_attributes, PathCollector, SaveContext};
use json_dumper::{Access, DumpOutput, JsonDumper};
use span_utils::SpanUtils;
use sig;
use rls_data::{CratePreludeData, Def, DefKind, GlobalCrateId, Import, ImportKind, Ref, RefKind,
Relation, RelationKind, SpanData};
macro_rules! down_cast_data {
($id:ident, $kind:ident, $sp:expr) => {
let $id = if let super::Data::$kind(data) = $id {
data
} else {
span_bug!($sp, "unexpected data kind: {:?}", $id);
};
};
}
macro_rules! access_from {
($save_ctxt:expr, $item:expr) => {
Access {
public: $item.vis == ast::Visibility::Public,
reachable: $save_ctxt.analysis.access_levels.is_reachable($item.id),
}
}
}
pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> {
save_ctxt: SaveContext<'l, 'tcx>,
tcx: TyCtxt<'l, 'tcx, 'tcx>,
dumper: &'ll mut JsonDumper<O>,
span: SpanUtils<'l>,
cur_scope: NodeId,
// Set of macro definition (callee) spans, and the set
// of macro use (callsite) spans. We store these to ensure
// we only write one macro def per unique macro definition, and
// one macro use per unique callsite span.
// mac_defs: HashSet<Span>,
macro_calls: FxHashSet<Span>,
}
impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> {
pub fn new(
save_ctxt: SaveContext<'l, 'tcx>,
dumper: &'ll mut JsonDumper<O>,
) -> DumpVisitor<'l, 'tcx, 'll, O> {
let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
DumpVisitor {
tcx: save_ctxt.tcx,
save_ctxt,
dumper,
span: span_utils.clone(),
cur_scope: CRATE_NODE_ID,
// mac_defs: HashSet::new(),
macro_calls: FxHashSet(),
}
}
fn nest_scope<F>(&mut self, scope_id: NodeId, f: F)
where
F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
{
let parent_scope = self.cur_scope;
self.cur_scope = scope_id;
f(self);
self.cur_scope = parent_scope;
}
fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
where
F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, O>),
{
let item_def_id = self.tcx.hir.local_def_id(item_id);
if self.tcx.has_typeck_tables(item_def_id) {
let tables = self.tcx.typeck_tables_of(item_def_id);
let old_tables = self.save_ctxt.tables;
self.save_ctxt.tables = tables;
f(self);
self.save_ctxt.tables = old_tables;
} else {
f(self);
}
}
fn span_from_span(&self, span: Span) -> SpanData {
self.save_ctxt.span_from_span(span)
}
pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
let source_file = self.tcx.sess.local_crate_source_file.as_ref();
let crate_root = source_file.map(|source_file| {
let source_file = Path::new(source_file);
match source_file.file_name() {
Some(_) => source_file.parent().unwrap().display().to_string(),
None => source_file.display().to_string(),
}
});
let data = CratePreludeData {
crate_id: GlobalCrateId {
name: name.into(),
disambiguator: self.tcx
.sess
.local_crate_disambiguator()
.to_fingerprint()
.as_value(),
},
crate_root: crate_root.unwrap_or("<no source>".to_owned()),
external_crates: self.save_ctxt.get_external_crates(),
span: self.span_from_span(krate.span),
};
self.dumper.crate_prelude(data);
}
// Return all non-empty prefixes of a path.
// For each prefix, we return the span for the last segment in the prefix and
// a str representation of the entire prefix.
fn process_path_prefixes(&self, path: &ast::Path) -> Vec<(Span, String)> {
let segments = &path.segments[if path.is_global() { 1 } else { 0 }..];
let mut result = Vec::with_capacity(segments.len());
let mut segs = vec![];
for (i, seg) in segments.iter().enumerate() {
segs.push(seg.clone());
let sub_path = ast::Path {
span: seg.span, // span for the last segment
segments: segs,
};
let qualname = if i == 0 && path.is_global() {
format!("::{}", path_to_string(&sub_path))
} else {
path_to_string(&sub_path)
};
result.push((seg.span, qualname));
segs = sub_path.segments;
}
result
}
fn write_sub_paths(&mut self, path: &ast::Path) {
let sub_paths = self.process_path_prefixes(path);
for (span, _) in sub_paths {
let span = self.span_from_span(span);
self.dumper.dump_ref(Ref {
kind: RefKind::Mod,
span,
ref_id: ::null_id(),
});
}
}
// As write_sub_paths, but does not process the last ident in the path (assuming it
// will be processed elsewhere). See note on write_sub_paths about global.
fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
let sub_paths = self.process_path_prefixes(path);
let len = sub_paths.len();
if len <= 1 {
return;
}
for (span, _) in sub_paths.into_iter().take(len - 1) {
let span = self.span_from_span(span);
self.dumper.dump_ref(Ref {
kind: RefKind::Mod,
span,
ref_id: ::null_id(),
});
}
}
// As write_sub_paths, but expects a path of the form module_path::trait::method
// Where trait could actually be a struct too.
fn write_sub_path_trait_truncated(&mut self, path: &ast::Path) {
let sub_paths = self.process_path_prefixes(path);
let len = sub_paths.len();
if len <= 1 {
return;
}
let sub_paths = &sub_paths[..(len - 1)];
// write the trait part of the sub-path
let (ref span, _) = sub_paths[len - 2];
let span = self.span_from_span(*span);
self.dumper.dump_ref(Ref {
kind: RefKind::Type,
ref_id: ::null_id(),
span,
});
// write the other sub-paths
if len <= 2 {
return;
}
let sub_paths = &sub_paths[..len - 2];
for &(ref span, _) in sub_paths {
let span = self.span_from_span(*span);
self.dumper.dump_ref(Ref {
kind: RefKind::Mod,
span,
ref_id: ::null_id(),
});
}
}
fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
match self.save_ctxt.get_path_def(ref_id) {
HirDef::PrimTy(..) | HirDef::SelfTy(..) | HirDef::Err => None,
def => Some(def.def_id()),
}
}
fn process_def_kind(
&mut self,
ref_id: NodeId,
span: Span,
sub_span: Option<Span>,
def_id: DefId,
) {
if self.span.filter_generated(sub_span, span) {
return;
}
let def = self.save_ctxt.get_path_def(ref_id);
match def {
HirDef::Mod(_) => {
let span = self.span_from_span(sub_span.expect("No span found for mod ref"));
self.dumper.dump_ref(Ref {
kind: RefKind::Mod,
span,
ref_id: ::id_from_def_id(def_id),
});
}
HirDef::Struct(..) |
HirDef::Variant(..) |
HirDef::Union(..) |
HirDef::Enum(..) |
HirDef::TyAlias(..) |
HirDef::TyForeign(..) |
HirDef::TraitAlias(..) |
HirDef::Trait(_) => {
let span = self.span_from_span(sub_span.expect("No span found for type ref"));
self.dumper.dump_ref(Ref {
kind: RefKind::Type,
span,
ref_id: ::id_from_def_id(def_id),
});
}
HirDef::Static(..) |
HirDef::Const(..) |
HirDef::StructCtor(..) |
HirDef::VariantCtor(..) => {
let span = self.span_from_span(sub_span.expect("No span found for var ref"));
self.dumper.dump_ref(Ref {
kind: RefKind::Variable,
span,
ref_id: ::id_from_def_id(def_id),
});
}
HirDef::Fn(..) => {
let span = self.span_from_span(sub_span.expect("No span found for fn ref"));
self.dumper.dump_ref(Ref {
kind: RefKind::Function,
span,
ref_id: ::id_from_def_id(def_id),
});
}
// With macros 2.0, we can legitimately get a ref to a macro, but
// we don't handle it properly for now (FIXME).
HirDef::Macro(..) => {}
HirDef::Local(..) |
HirDef::Upvar(..) |
HirDef::SelfTy(..) |
HirDef::Label(_) |
HirDef::TyParam(..) |
HirDef::Method(..) |
HirDef::AssociatedTy(..) |
HirDef::AssociatedConst(..) |
HirDef::PrimTy(_) |
HirDef::GlobalAsm(_) |
HirDef::Err => {
span_bug!(span, "process_def_kind for unexpected item: {:?}", def);
}
}
}
fn process_formals(&mut self, formals: &'l [ast::Arg], qualname: &str) {
for arg in formals {
self.visit_pat(&arg.pat);
let mut collector = PathCollector::new();
collector.visit_pat(&arg.pat);
let span_utils = self.span.clone();
for (id, i, sp, ..) in collector.collected_idents {
let hir_id = self.tcx.hir.node_to_hir_id(id);
let typ = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
Some(s) => s.to_string(),
None => continue,
};
let sub_span = span_utils.span_for_last_ident(sp);
if !self.span.filter_generated(sub_span, sp) {
let id = ::id_from_node_id(id, &self.save_ctxt);
let span = self.span_from_span(sub_span.expect("No span found for variable"));
self.dumper.dump_def(
&Access {
public: false,
reachable: false,
},
Def {
kind: DefKind::Local,
id,
span,
name: i.to_string(),
qualname: format!("{}::{}", qualname, i.to_string()),
value: typ,
parent: None,
children: vec![],
decl_id: None,
docs: String::new(),
sig: None,
attributes: vec![],
},
);
}
}
}
}
fn process_method(
&mut self,
sig: &'l ast::MethodSig,
body: Option<&'l ast::Block>,
id: ast::NodeId,
name: ast::Ident,
generics: &'l ast::Generics,
vis: ast::Visibility,
span: Span,
) {
debug!("process_method: {}:{}", id, name);
if let Some(mut method_data) = self.save_ctxt.get_method_data(id, name.name, span) {
let sig_str = ::make_signature(&sig.decl, &generics);
if body.is_some() {
self.nest_tables(
id,
|v| v.process_formals(&sig.decl.inputs, &method_data.qualname),
);
}
self.process_generic_params(&generics, span, &method_data.qualname, id);
method_data.value = sig_str;
method_data.sig = sig::method_signature(id, name, generics, sig, &self.save_ctxt);
self.dumper.dump_def(
&Access {
public: vis == ast::Visibility::Public,
reachable: self.save_ctxt.analysis.access_levels.is_reachable(id),
},
method_data);
}
// walk arg and return types
for arg in &sig.decl.inputs {
self.visit_ty(&arg.ty);
}
if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
self.visit_ty(ret_ty);
}
// walk the fn body
if let Some(body) = body {
self.nest_tables(id, |v| v.nest_scope(id, |v| v.visit_block(body)));
}
}
fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
let field_data = self.save_ctxt.get_field_data(field, parent_id);
if let Some(field_data) = field_data {
self.dumper.dump_def(&access_from!(self.save_ctxt, field), field_data);
}
}
// Dump generic params bindings, then visit_generics
fn process_generic_params(
&mut self,
generics: &'l ast::Generics,
full_span: Span,
prefix: &str,
id: NodeId,
) {
for param in &generics.ty_params {
let param_ss = param.span;
let name = escape(self.span.snippet(param_ss));
// Append $id to name to make sure each one is unique
let qualname = format!("{}::{}${}", prefix, name, id);
if !self.span.filter_generated(Some(param_ss), full_span) {
let id = ::id_from_node_id(param.id, &self.save_ctxt);
let span = self.span_from_span(param_ss);
self.dumper.dump_def(
&Access {
public: false,
reachable: false,
},
Def {
kind: DefKind::Type,
id,
span,
name,
qualname,
value: String::new(),
parent: None,
children: vec![],
decl_id: None,
docs: String::new(),
sig: None,
attributes: vec![],
},
);
}
}
self.visit_generics(generics);
}
fn process_fn(
&mut self,
item: &'l ast::Item,
decl: &'l ast::FnDecl,
ty_params: &'l ast::Generics,
body: &'l ast::Block,
) {
if let Some(fn_data) = self.save_ctxt.get_item_data(item) {
down_cast_data!(fn_data, DefData, item.span);
self.nest_tables(
item.id,
|v| v.process_formals(&decl.inputs, &fn_data.qualname),
);
self.process_generic_params(ty_params, item.span, &fn_data.qualname, item.id);
self.dumper.dump_def(&access_from!(self.save_ctxt, item), fn_data);
}
for arg in &decl.inputs {
self.visit_ty(&arg.ty);
}
if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
self.visit_ty(&ret_ty);
}
self.nest_tables(item.id, |v| v.nest_scope(item.id, |v| v.visit_block(&body)));
}
fn process_static_or_const_item(
&mut self,
item: &'l ast::Item,
typ: &'l ast::Ty,
expr: &'l ast::Expr,
) {
self.nest_tables(item.id, |v| {
if let Some(var_data) = v.save_ctxt.get_item_data(item) {
down_cast_data!(var_data, DefData, item.span);
v.dumper.dump_def(&access_from!(v.save_ctxt, item), var_data);
}
v.visit_ty(&typ);
v.visit_expr(expr);
});
}
fn process_assoc_const(
&mut self,
id: ast::NodeId,
name: ast::Name,
span: Span,
typ: &'l ast::Ty,
expr: Option<&'l ast::Expr>,
parent_id: DefId,
vis: ast::Visibility,
attrs: &'l [Attribute],
) {
let qualname = format!("::{}", self.tcx.node_path_str(id));
let sub_span = self.span.sub_span_after_keyword(span, keywords::Const);
if !self.span.filter_generated(sub_span, span) {
let sig = sig::assoc_const_signature(id, name, typ, expr, &self.save_ctxt);
let span = self.span_from_span(sub_span.expect("No span found for variable"));
self.dumper.dump_def(
&Access {
public: vis == ast::Visibility::Public,
reachable: self.save_ctxt.analysis.access_levels.is_reachable(id),
},
Def {
kind: DefKind::Const,
id: ::id_from_node_id(id, &self.save_ctxt),
span,
name: name.to_string(),
qualname,
value: ty_to_string(&typ),
parent: Some(::id_from_def_id(parent_id)),
children: vec![],
decl_id: None,
docs: self.save_ctxt.docs_for_attrs(attrs),
sig,
attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
},
);
}
// walk type and init value
self.visit_ty(typ);
if let Some(expr) = expr {
self.visit_expr(expr);
}
}
// FIXME tuple structs should generate tuple-specific data.
fn process_struct(
&mut self,
item: &'l ast::Item,
def: &'l ast::VariantData,
ty_params: &'l ast::Generics,
) {
debug!("process_struct {:?} {:?}", item, item.span);
let name = item.ident.to_string();
let qualname = format!("::{}", self.tcx.node_path_str(item.id));
let (kind, keyword) = match item.node {
ast::ItemKind::Struct(_, _) => (DefKind::Struct, keywords::Struct),
ast::ItemKind::Union(_, _) => (DefKind::Union, keywords::Union),
_ => unreachable!(),
};
let sub_span = self.span.sub_span_after_keyword(item.span, keyword);
let (value, fields) = match item.node {
ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, _), _) |
ast::ItemKind::Union(ast::VariantData::Struct(ref fields, _), _) => {
let include_priv_fields = !self.save_ctxt.config.pub_only;
let fields_str = fields
.iter()
.enumerate()
.filter_map(|(i, f)| {
if include_priv_fields || f.vis == ast::Visibility::Public {
f.ident
.map(|i| i.to_string())
.or_else(|| Some(i.to_string()))
} else {
None
}
})
.collect::<Vec<_>>()
.join(", ");
let value = format!("{} {{ {} }}", name, fields_str);
(
value,
fields
.iter()
.map(|f| ::id_from_node_id(f.id, &self.save_ctxt))
.collect(),
)
}
_ => (String::new(), vec![]),
};
if !self.span.filter_generated(sub_span, item.span) {
let span = self.span_from_span(sub_span.expect("No span found for struct"));
self.dumper.dump_def(
&access_from!(self.save_ctxt, item),
Def {
kind,
id: ::id_from_node_id(item.id, &self.save_ctxt),
span,
name,
qualname: qualname.clone(),
value,
parent: None,
children: fields,
decl_id: None,
docs: self.save_ctxt.docs_for_attrs(&item.attrs),
sig: sig::item_signature(item, &self.save_ctxt),
attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
},
);
}
for field in def.fields() {
self.process_struct_field_def(field, item.id);
self.visit_ty(&field.ty);
}
self.process_generic_params(ty_params, item.span, &qualname, item.id);
}
fn process_enum(
&mut self,
item: &'l ast::Item,
enum_definition: &'l ast::EnumDef,
ty_params: &'l ast::Generics,
) {
let enum_data = self.save_ctxt.get_item_data(item);
let enum_data = match enum_data {
None => return,
Some(data) => data,
};
down_cast_data!(enum_data, DefData, item.span);
let access = access_from!(self.save_ctxt, item);
for variant in &enum_definition.variants {
let name = variant.node.name.name.to_string();
let mut qualname = enum_data.qualname.clone();
qualname.push_str("::");
qualname.push_str(&name);
match variant.node.data {
ast::VariantData::Struct(ref fields, _) => {
let sub_span = self.span.span_for_first_ident(variant.span);
let fields_str = fields
.iter()
.enumerate()
.map(|(i, f)| {
f.ident.map(|i| i.to_string()).unwrap_or(i.to_string())
})
.collect::<Vec<_>>()
.join(", ");
let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
if !self.span.filter_generated(sub_span, variant.span) {
let span = self
.span_from_span(sub_span.expect("No span found for struct variant"));
let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
self.dumper.dump_def(
&access,
Def {
kind: DefKind::StructVariant,
id,
span,
name,
qualname,
value,
parent,
children: vec![],
decl_id: None,
docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
sig: sig::variant_signature(variant, &self.save_ctxt),
attributes: lower_attributes(
variant.node.attrs.clone(),
&self.save_ctxt,
),
},
);
}
}
ref v => {
let sub_span = self.span.span_for_first_ident(variant.span);
let mut value = format!("{}::{}", enum_data.name, name);
if let &ast::VariantData::Tuple(ref fields, _) = v {
value.push('(');
value.push_str(&fields
.iter()
.map(|f| ty_to_string(&f.ty))
.collect::<Vec<_>>()
.join(", "));
value.push(')');
}
if !self.span.filter_generated(sub_span, variant.span) {
let span =
self.span_from_span(sub_span.expect("No span found for tuple variant"));
let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
self.dumper.dump_def(
&access,
Def {
kind: DefKind::TupleVariant,
id,
span,
name,
qualname,
value,
parent,
children: vec![],
decl_id: None,
docs: self.save_ctxt.docs_for_attrs(&variant.node.attrs),
sig: sig::variant_signature(variant, &self.save_ctxt),
attributes: lower_attributes(
variant.node.attrs.clone(),
&self.save_ctxt,
),
},
);
}
}
}
for field in variant.node.data.fields() {
self.process_struct_field_def(field, variant.node.data.id());
self.visit_ty(&field.ty);
}
}
self.process_generic_params(ty_params, item.span, &enum_data.qualname, item.id);
self.dumper.dump_def(&access, enum_data);
}
fn process_impl(
&mut self,
item: &'l ast::Item,
type_parameters: &'l ast::Generics,
trait_ref: &'l Option<ast::TraitRef>,
typ: &'l ast::Ty,
impl_items: &'l [ast::ImplItem],
) {
if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
down_cast_data!(impl_data, RelationData, item.span);
self.dumper.dump_relation(impl_data);
}
self.visit_ty(&typ);
if let &Some(ref trait_ref) = trait_ref {
self.process_path(trait_ref.ref_id, &trait_ref.path);
}
self.process_generic_params(type_parameters, item.span, "", item.id);
for impl_item in impl_items {
let map = &self.tcx.hir;
self.process_impl_item(impl_item, map.local_def_id(item.id));
}
}
fn process_trait(
&mut self,
item: &'l ast::Item,
generics: &'l ast::Generics,
trait_refs: &'l ast::TyParamBounds,
methods: &'l [ast::TraitItem],
) {
let name = item.ident.to_string();
let qualname = format!("::{}", self.tcx.node_path_str(item.id));
let mut val = name.clone();
if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
val.push_str(&generics_to_string(generics));
}
if !trait_refs.is_empty() {
val.push_str(": ");
val.push_str(&bounds_to_string(trait_refs));
}
let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);
if !self.span.filter_generated(sub_span, item.span) {
let id = ::id_from_node_id(item.id, &self.save_ctxt);
let span = self.span_from_span(sub_span.expect("No span found for trait"));
let children = methods
.iter()
.map(|i| ::id_from_node_id(i.id, &self.save_ctxt))
.collect();
self.dumper.dump_def(
&access_from!(self.save_ctxt, item),
Def {
kind: DefKind::Trait,
id,
span,
name,
qualname: qualname.clone(),
value: val,
parent: None,
children,
decl_id: None,
docs: self.save_ctxt.docs_for_attrs(&item.attrs),
sig: sig::item_signature(item, &self.save_ctxt),
attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
},
);
}
// super-traits
for super_bound in trait_refs.iter() {
let trait_ref = match *super_bound {
ast::TraitTyParamBound(ref trait_ref, _) => trait_ref,
ast::RegionTyParamBound(..) => {
continue;
}
};
let trait_ref = &trait_ref.trait_ref;
if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
let sub_span = self.span.sub_span_for_type_name(trait_ref.path.span);
if !self.span.filter_generated(sub_span, trait_ref.path.span) {
let span = self.span_from_span(sub_span.expect("No span found for trait ref"));
self.dumper.dump_ref(Ref {
kind: RefKind::Type,
span,
ref_id: ::id_from_def_id(id),
});
}
if !self.span.filter_generated(sub_span, trait_ref.path.span) {
let sub_span = self.span_from_span(sub_span.expect("No span for inheritance"));
self.dumper.dump_relation(Relation {
kind: RelationKind::SuperTrait,
span: sub_span,
from: ::id_from_def_id(id),
to: ::id_from_node_id(item.id, &self.save_ctxt),
});
}
}
}
// walk generics and methods
self.process_generic_params(generics, item.span, &qualname, item.id);
for method in methods {
let map = &self.tcx.hir;
self.process_trait_item(method, map.local_def_id(item.id))
}
}
// `item` is the module in question, represented as an item.
fn process_mod(&mut self, item: &ast::Item) {
if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
down_cast_data!(mod_data, DefData, item.span);
self.dumper.dump_def(&access_from!(self.save_ctxt, item), mod_data);
}
}
fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
let path_data = self.save_ctxt.get_path_data(id, path);
if let Some(path_data) = path_data {
self.dumper.dump_ref(path_data);
}
}
fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
debug!("process_path {:?}", path);
if generated_code(path.span) {
return;
}
self.dump_path_ref(id, path);
// Type parameters
for seg in &path.segments {
if let Some(ref params) = seg.parameters {
match **params {
ast::PathParameters::AngleBracketed(ref data) => for t in &data.types {
self.visit_ty(t);
},
ast::PathParameters::Parenthesized(ref data) => {
for t in &data.inputs {
self.visit_ty(t);
}
if let Some(ref t) = data.output {
self.visit_ty(t);
}
}
}
}
}
// Modules or types in the path prefix.
match self.save_ctxt.get_path_def(id) {
HirDef::Method(did) => {
let ti = self.tcx.associated_item(did);
if ti.kind == ty::AssociatedKind::Method && ti.method_has_self_argument {
self.write_sub_path_trait_truncated(path);
}
}
HirDef::Fn(..) |
HirDef::Const(..) |
HirDef::Static(..) |
HirDef::StructCtor(..) |
HirDef::VariantCtor(..) |
HirDef::AssociatedConst(..) |
HirDef::Local(..) |
HirDef::Upvar(..) |
HirDef::Struct(..) |
HirDef::Union(..) |
HirDef::Variant(..) |
HirDef::TyAlias(..) |
HirDef::AssociatedTy(..) => self.write_sub_paths_truncated(path),
_ => {}
}
}
fn process_struct_lit(
&mut self,
ex: &'l ast::Expr,
path: &'l ast::Path,
fields: &'l [ast::Field],
variant: &'l ty::VariantDef,
base: &'l Option<P<ast::Expr>>,
) {
self.write_sub_paths_truncated(path);
if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
down_cast_data!(struct_lit_data, RefData, ex.span);
if !generated_code(ex.span) {
self.dumper.dump_ref(struct_lit_data);
}
for field in fields {
if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
self.dumper.dump_ref(field_data);
}
self.visit_expr(&field.expr)
}
}
walk_list!(self, visit_expr, base);
}
fn process_method_call(
&mut self,
ex: &'l ast::Expr,
seg: &'l ast::PathSegment,
args: &'l [P<ast::Expr>],
) {
debug!("process_method_call {:?} {:?}", ex, ex.span);
if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
down_cast_data!(mcd, RefData, ex.span);
if !generated_code(ex.span) {
self.dumper.dump_ref(mcd);
}
}
// Explicit types in the turbo-fish.
if let Some(ref params) = seg.parameters {
if let ast::PathParameters::AngleBracketed(ref data) = **params {
for t in &data.types {
self.visit_ty(t);
}
}
}
// walk receiver and args
walk_list!(self, visit_expr, args);
}
fn process_pat(&mut self, p: &'l ast::Pat) {
match p.node {
PatKind::Struct(ref _path, ref fields, _) => {
// FIXME do something with _path?
let hir_id = self.tcx.hir.node_to_hir_id(p.id);
let adt = match self.save_ctxt.tables.node_id_to_type_opt(hir_id) {
Some(ty) => ty.ty_adt_def().unwrap(),
None => {
visit::walk_pat(self, p);
return;
}
};
let variant = adt.variant_of_def(self.save_ctxt.get_path_def(p.id));
for &Spanned {