]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/lib.rs
Rename `Item.node` to `Item.kind`
[rust.git] / src / librustc_save_analysis / lib.rs
1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
2 #![feature(nll)]
3 #![feature(inner_deref)]
4
5 #![recursion_limit="256"]
6
7 mod dumper;
8 mod dump_visitor;
9 #[macro_use]
10 mod span_utils;
11 mod sig;
12
13 use rustc::hir;
14 use rustc::hir::def::{CtorOf, Res, DefKind as HirDefKind};
15 use rustc::hir::Node;
16 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
17 use rustc::middle::privacy::AccessLevels;
18 use rustc::middle::cstore::ExternCrate;
19 use rustc::session::config::{CrateType, Input, OutputType};
20 use rustc::ty::{self, DefIdTree, TyCtxt};
21 use rustc::{bug, span_bug};
22 use rustc_codegen_utils::link::{filename_for_metadata, out_filename};
23
24 use std::cell::Cell;
25 use std::default::Default;
26 use std::env;
27 use std::fs::File;
28 use std::io::BufWriter;
29 use std::path::{Path, PathBuf};
30
31 use syntax::ast::{self, Attribute, DUMMY_NODE_ID, NodeId, PatKind};
32 use syntax::source_map::Spanned;
33 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
34 use syntax::print::pprust;
35 use syntax::visit::{self, Visitor};
36 use syntax::print::pprust::{param_to_string, ty_to_string};
37 use syntax_pos::*;
38
39 use dump_visitor::DumpVisitor;
40 use span_utils::SpanUtils;
41
42 use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
43                RelationKind, SpanData, Impl, ImplKind, Analysis};
44 use rls_data::config::Config;
45
46 use log::{debug, error, info};
47
48
49 pub struct SaveContext<'l, 'tcx> {
50     tcx: TyCtxt<'tcx>,
51     tables: &'l ty::TypeckTables<'tcx>,
52     access_levels: &'l AccessLevels,
53     span_utils: SpanUtils<'tcx>,
54     config: Config,
55     impl_counter: Cell<u32>,
56 }
57
58 #[derive(Debug)]
59 pub enum Data {
60     RefData(Ref),
61     DefData(Def),
62     RelationData(Relation, Impl),
63 }
64
65 impl<'l, 'tcx> SaveContext<'l, 'tcx> {
66     fn span_from_span(&self, span: Span) -> SpanData {
67         use rls_span::{Column, Row};
68
69         let cm = self.tcx.sess.source_map();
70         let start = cm.lookup_char_pos(span.lo());
71         let end = cm.lookup_char_pos(span.hi());
72
73         SpanData {
74             file_name: start.file.name.to_string().into(),
75             byte_start: span.lo().0,
76             byte_end: span.hi().0,
77             line_start: Row::new_one_indexed(start.line as u32),
78             line_end: Row::new_one_indexed(end.line as u32),
79             column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
80             column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
81         }
82     }
83
84     // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
85     pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
86         let sess = &self.tcx.sess;
87         // Save-analysis is emitted per whole session, not per each crate type
88         let crate_type = sess.crate_types.borrow()[0];
89         let outputs = &*self.tcx.output_filenames(LOCAL_CRATE);
90
91         if outputs.outputs.contains_key(&OutputType::Metadata) {
92             filename_for_metadata(sess, crate_name, outputs)
93         } else if outputs.outputs.should_codegen() {
94             out_filename(sess, crate_type, outputs, crate_name)
95         } else {
96             // Otherwise it's only a DepInfo, in which case we return early and
97             // not even reach the analysis stage.
98             unreachable!()
99         }
100     }
101
102     // List external crates used by the current crate.
103     pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
104         let mut result = Vec::with_capacity(self.tcx.crates().len());
105
106         for &n in self.tcx.crates().iter() {
107             let span = match self.tcx.extern_crate(n.as_def_id()) {
108                 Some(&ExternCrate { span, .. }) => span,
109                 None => {
110                     debug!("skipping crate {}, no data", n);
111                     continue;
112                 }
113             };
114             let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
115             result.push(ExternalCrateData {
116                 // FIXME: change file_name field to PathBuf in rls-data
117                 // https://github.com/nrc/rls-data/issues/7
118                 file_name: self.span_utils.make_filename_string(&lo_loc.file),
119                 num: n.as_u32(),
120                 id: GlobalCrateId {
121                     name: self.tcx.crate_name(n).to_string(),
122                     disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
123                 },
124             });
125         }
126
127         result
128     }
129
130     pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
131         let qualname = format!("::{}",
132             self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
133         match item.node {
134             ast::ForeignItemKind::Fn(ref decl, ref generics) => {
135                 filter!(self.span_utils, item.ident.span);
136
137                 Some(Data::DefData(Def {
138                     kind: DefKind::ForeignFunction,
139                     id: id_from_node_id(item.id, self),
140                     span: self.span_from_span(item.ident.span),
141                     name: item.ident.to_string(),
142                     qualname,
143                     value: make_signature(decl, generics),
144                     parent: None,
145                     children: vec![],
146                     decl_id: None,
147                     docs: self.docs_for_attrs(&item.attrs),
148                     sig: sig::foreign_item_signature(item, self),
149                     attributes: lower_attributes(item.attrs.clone(), self),
150                 }))
151             }
152             ast::ForeignItemKind::Static(ref ty, _) => {
153                 filter!(self.span_utils, item.ident.span);
154
155                 let id = id_from_node_id(item.id, self);
156                 let span = self.span_from_span(item.ident.span);
157
158                 Some(Data::DefData(Def {
159                     kind: DefKind::ForeignStatic,
160                     id,
161                     span,
162                     name: item.ident.to_string(),
163                     qualname,
164                     value: ty_to_string(ty),
165                     parent: None,
166                     children: vec![],
167                     decl_id: None,
168                     docs: self.docs_for_attrs(&item.attrs),
169                     sig: sig::foreign_item_signature(item, self),
170                     attributes: lower_attributes(item.attrs.clone(), self),
171                 }))
172             }
173             // FIXME(plietar): needs a new DefKind in rls-data
174             ast::ForeignItemKind::Ty => None,
175             ast::ForeignItemKind::Macro(..) => None,
176         }
177     }
178
179     pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
180         match item.kind {
181             ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
182                 let qualname = format!("::{}",
183                     self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
184                 filter!(self.span_utils, item.ident.span);
185                 Some(Data::DefData(Def {
186                     kind: DefKind::Function,
187                     id: id_from_node_id(item.id, self),
188                     span: self.span_from_span(item.ident.span),
189                     name: item.ident.to_string(),
190                     qualname,
191                     value: make_signature(decl, generics),
192                     parent: None,
193                     children: vec![],
194                     decl_id: None,
195                     docs: self.docs_for_attrs(&item.attrs),
196                     sig: sig::item_signature(item, self),
197                     attributes: lower_attributes(item.attrs.clone(), self),
198                 }))
199             }
200             ast::ItemKind::Static(ref typ, ..) => {
201                 let qualname = format!("::{}",
202                     self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
203
204                 filter!(self.span_utils, item.ident.span);
205
206                 let id = id_from_node_id(item.id, self);
207                 let span = self.span_from_span(item.ident.span);
208
209                 Some(Data::DefData(Def {
210                     kind: DefKind::Static,
211                     id,
212                     span,
213                     name: item.ident.to_string(),
214                     qualname,
215                     value: ty_to_string(&typ),
216                     parent: None,
217                     children: vec![],
218                     decl_id: None,
219                     docs: self.docs_for_attrs(&item.attrs),
220                     sig: sig::item_signature(item, self),
221                     attributes: lower_attributes(item.attrs.clone(), self),
222                 }))
223             }
224             ast::ItemKind::Const(ref typ, _) => {
225                 let qualname = format!("::{}",
226                     self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
227                 filter!(self.span_utils, item.ident.span);
228
229                 let id = id_from_node_id(item.id, self);
230                 let span = self.span_from_span(item.ident.span);
231
232                 Some(Data::DefData(Def {
233                     kind: DefKind::Const,
234                     id,
235                     span,
236                     name: item.ident.to_string(),
237                     qualname,
238                     value: ty_to_string(typ),
239                     parent: None,
240                     children: vec![],
241                     decl_id: None,
242                     docs: self.docs_for_attrs(&item.attrs),
243                     sig: sig::item_signature(item, self),
244                     attributes: lower_attributes(item.attrs.clone(), self),
245                 }))
246             }
247             ast::ItemKind::Mod(ref m) => {
248                 let qualname = format!("::{}",
249                     self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
250
251                 let cm = self.tcx.sess.source_map();
252                 let filename = cm.span_to_filename(m.inner);
253
254                 filter!(self.span_utils, item.ident.span);
255
256                 Some(Data::DefData(Def {
257                     kind: DefKind::Mod,
258                     id: id_from_node_id(item.id, self),
259                     name: item.ident.to_string(),
260                     qualname,
261                     span: self.span_from_span(item.ident.span),
262                     value: filename.to_string(),
263                     parent: None,
264                     children: m.items
265                         .iter()
266                         .map(|i| id_from_node_id(i.id, self))
267                         .collect(),
268                     decl_id: None,
269                     docs: self.docs_for_attrs(&item.attrs),
270                     sig: sig::item_signature(item, self),
271                     attributes: lower_attributes(item.attrs.clone(), self),
272                 }))
273             }
274             ast::ItemKind::Enum(ref def, _) => {
275                 let name = item.ident.to_string();
276                 let qualname = format!("::{}",
277                     self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id)));
278                 filter!(self.span_utils, item.ident.span);
279                 let variants_str = def.variants
280                     .iter()
281                     .map(|v| v.ident.to_string())
282                     .collect::<Vec<_>>()
283                     .join(", ");
284                 let value = format!("{}::{{{}}}", name, variants_str);
285                 Some(Data::DefData(Def {
286                     kind: DefKind::Enum,
287                     id: id_from_node_id(item.id, self),
288                     span: self.span_from_span(item.ident.span),
289                     name,
290                     qualname,
291                     value,
292                     parent: None,
293                     children: def.variants
294                         .iter()
295                         .map(|v| id_from_node_id(v.id, self))
296                         .collect(),
297                     decl_id: None,
298                     docs: self.docs_for_attrs(&item.attrs),
299                     sig: sig::item_signature(item, self),
300                     attributes: lower_attributes(item.attrs.clone(), self),
301                 }))
302             }
303             ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
304                 if let ast::TyKind::Path(None, ref path) = typ.kind {
305                     // Common case impl for a struct or something basic.
306                     if generated_code(path.span) {
307                         return None;
308                     }
309                     let sub_span = path.segments.last().unwrap().ident.span;
310                     filter!(self.span_utils, sub_span);
311
312                     let impl_id = self.next_impl_id();
313                     let span = self.span_from_span(sub_span);
314
315                     let type_data = self.lookup_def_id(typ.id);
316                     type_data.map(|type_data| {
317                         Data::RelationData(Relation {
318                             kind: RelationKind::Impl {
319                                 id: impl_id,
320                             },
321                             span: span.clone(),
322                             from: id_from_def_id(type_data),
323                             to: trait_ref
324                                 .as_ref()
325                                 .and_then(|t| self.lookup_def_id(t.ref_id))
326                                 .map(id_from_def_id)
327                                 .unwrap_or_else(|| null_id()),
328                         },
329                         Impl {
330                             id: impl_id,
331                             kind: match *trait_ref {
332                                 Some(_) => ImplKind::Direct,
333                                 None => ImplKind::Inherent,
334                             },
335                             span: span,
336                             value: String::new(),
337                             parent: None,
338                             children: impls
339                                 .iter()
340                                 .map(|i| id_from_node_id(i.id, self))
341                                 .collect(),
342                             docs: String::new(),
343                             sig: None,
344                             attributes: vec![],
345                         })
346                     })
347                 } else {
348                     None
349                 }
350             }
351             _ => {
352                 // FIXME
353                 bug!();
354             }
355         }
356     }
357
358     pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
359         if let Some(ident) = field.ident {
360             let name = ident.to_string();
361             let qualname = format!("::{}::{}",
362                 self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(scope)),
363                 ident);
364             filter!(self.span_utils, ident.span);
365             let def_id = self.tcx.hir().local_def_id_from_node_id(field.id);
366             let typ = self.tcx.type_of(def_id).to_string();
367
368
369             let id = id_from_node_id(field.id, self);
370             let span = self.span_from_span(ident.span);
371
372             Some(Def {
373                 kind: DefKind::Field,
374                 id,
375                 span,
376                 name,
377                 qualname,
378                 value: typ,
379                 parent: Some(id_from_node_id(scope, self)),
380                 children: vec![],
381                 decl_id: None,
382                 docs: self.docs_for_attrs(&field.attrs),
383                 sig: sig::field_signature(field, self),
384                 attributes: lower_attributes(field.attrs.clone(), self),
385             })
386         } else {
387             None
388         }
389     }
390
391     // FIXME would be nice to take a MethodItem here, but the ast provides both
392     // trait and impl flavours, so the caller must do the disassembly.
393     pub fn get_method_data(&self, id: ast::NodeId, ident: ast::Ident, span: Span) -> Option<Def> {
394         // The qualname for a method is the trait name or name of the struct in an impl in
395         // which the method is declared in, followed by the method's name.
396         let (qualname, parent_scope, decl_id, docs, attributes) =
397             match self.tcx.impl_of_method(self.tcx.hir().local_def_id_from_node_id(id)) {
398                 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
399                     Some(Node::Item(item)) => match item.kind {
400                         hir::ItemKind::Impl(.., ref ty, _) => {
401                             let mut qualname = String::from("<");
402                             qualname.push_str(&self.tcx.hir().hir_to_pretty_string(ty.hir_id));
403
404                             let trait_id = self.tcx.trait_id_of_impl(impl_id);
405                             let mut decl_id = None;
406                             let mut docs = String::new();
407                             let mut attrs = vec![];
408                             let hir_id = self.tcx.hir().node_to_hir_id(id);
409                             if let Some(Node::ImplItem(item)) =
410                                 self.tcx.hir().find(hir_id)
411                             {
412                                 docs = self.docs_for_attrs(&item.attrs);
413                                 attrs = item.attrs.to_vec();
414                             }
415
416                             if let Some(def_id) = trait_id {
417                                 // A method in a trait impl.
418                                 qualname.push_str(" as ");
419                                 qualname.push_str(&self.tcx.def_path_str(def_id));
420                                 self.tcx
421                                     .associated_items(def_id)
422                                     .find(|item| item.ident.name == ident.name)
423                                     .map(|item| decl_id = Some(item.def_id));
424                             }
425                             qualname.push_str(">");
426
427                             (qualname, trait_id, decl_id, docs, attrs)
428                         }
429                         _ => {
430                             span_bug!(
431                                 span,
432                                 "Container {:?} for method {} not an impl?",
433                                 impl_id,
434                                 id
435                             );
436                         }
437                     },
438                     r => {
439                         span_bug!(
440                             span,
441                             "Container {:?} for method {} is not a node item {:?}",
442                             impl_id,
443                             id,
444                             r
445                         );
446                     }
447                 },
448                 None => match self.tcx.trait_of_item(self.tcx.hir().local_def_id_from_node_id(id)) {
449                     Some(def_id) => {
450                         let mut docs = String::new();
451                         let mut attrs = vec![];
452                         let hir_id = self.tcx.hir().node_to_hir_id(id);
453
454                         if let Some(Node::TraitItem(item)) = self.tcx.hir().find(hir_id) {
455                             docs = self.docs_for_attrs(&item.attrs);
456                             attrs = item.attrs.to_vec();
457                         }
458
459                         (
460                             format!("::{}", self.tcx.def_path_str(def_id)),
461                             Some(def_id),
462                             None,
463                             docs,
464                             attrs,
465                         )
466                     }
467                     None => {
468                         debug!("could not find container for method {} at {:?}", id, span);
469                         // This is not necessarily a bug, if there was a compilation error,
470                         // the tables we need might not exist.
471                         return None;
472                     }
473                 },
474             };
475
476         let qualname = format!("{}::{}", qualname, ident.name);
477
478         filter!(self.span_utils, ident.span);
479
480         Some(Def {
481             kind: DefKind::Method,
482             id: id_from_node_id(id, self),
483             span: self.span_from_span(ident.span),
484             name: ident.name.to_string(),
485             qualname,
486             // FIXME you get better data here by using the visitor.
487             value: String::new(),
488             parent: parent_scope.map(|id| id_from_def_id(id)),
489             children: vec![],
490             decl_id: decl_id.map(|id| id_from_def_id(id)),
491             docs,
492             sig: None,
493             attributes: lower_attributes(attributes, self),
494         })
495     }
496
497     pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
498         self.lookup_def_id(trait_ref.ref_id).and_then(|def_id| {
499             let span = trait_ref.path.span;
500             if generated_code(span) {
501                 return None;
502             }
503             let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
504             filter!(self.span_utils, sub_span);
505             let span = self.span_from_span(sub_span);
506             Some(Ref {
507                 kind: RefKind::Type,
508                 span,
509                 ref_id: id_from_def_id(def_id),
510             })
511         })
512     }
513
514     pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
515         let expr_hir_id = self.tcx.hir().node_to_hir_id(expr.id);
516         let hir_node = self.tcx.hir().expect_expr(expr_hir_id);
517         let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
518         if ty.is_none() || ty.unwrap().kind == ty::Error {
519             return None;
520         }
521         match expr.kind {
522             ast::ExprKind::Field(ref sub_ex, ident) => {
523                 let sub_ex_hir_id = self.tcx.hir().node_to_hir_id(sub_ex.id);
524                 let hir_node = match self.tcx.hir().find(sub_ex_hir_id) {
525                     Some(Node::Expr(expr)) => expr,
526                     _ => {
527                         debug!(
528                             "Missing or weird node for sub-expression {} in {:?}",
529                             sub_ex.id,
530                             expr
531                         );
532                         return None;
533                     }
534                 };
535                 match self.tables.expr_ty_adjusted(&hir_node).kind {
536                     ty::Adt(def, _) if !def.is_enum() => {
537                         let variant = &def.non_enum_variant();
538                         let index = self.tcx.find_field_index(ident, variant).unwrap();
539                         filter!(self.span_utils, ident.span);
540                         let span = self.span_from_span(ident.span);
541                         return Some(Data::RefData(Ref {
542                             kind: RefKind::Variable,
543                             span,
544                             ref_id: id_from_def_id(variant.fields[index].did),
545                         }));
546                     }
547                     ty::Tuple(..) => None,
548                     _ => {
549                         debug!("expected struct or union type, found {:?}", ty);
550                         None
551                     }
552                 }
553             }
554             ast::ExprKind::Struct(ref path, ..) => {
555                 match self.tables.expr_ty_adjusted(&hir_node).kind {
556                     ty::Adt(def, _) if !def.is_enum() => {
557                         let sub_span = path.segments.last().unwrap().ident.span;
558                         filter!(self.span_utils, sub_span);
559                         let span = self.span_from_span(sub_span);
560                         Some(Data::RefData(Ref {
561                             kind: RefKind::Type,
562                             span,
563                             ref_id: id_from_def_id(def.did),
564                         }))
565                     }
566                     _ => {
567                         // FIXME ty could legitimately be an enum, but then we will fail
568                         // later if we try to look up the fields.
569                         debug!("expected struct or union, found {:?}", ty);
570                         None
571                     }
572                 }
573             }
574             ast::ExprKind::MethodCall(ref seg, ..) => {
575                 let expr_hir_id = self.tcx.hir().definitions().node_to_hir_id(expr.id);
576                 let method_id = match self.tables.type_dependent_def_id(expr_hir_id) {
577                     Some(id) => id,
578                     None => {
579                         debug!("could not resolve method id for {:?}", expr);
580                         return None;
581                     }
582                 };
583                 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
584                     ty::ImplContainer(_) => (Some(method_id), None),
585                     ty::TraitContainer(_) => (None, Some(method_id)),
586                 };
587                 let sub_span = seg.ident.span;
588                 filter!(self.span_utils, sub_span);
589                 let span = self.span_from_span(sub_span);
590                 Some(Data::RefData(Ref {
591                     kind: RefKind::Function,
592                     span,
593                     ref_id: def_id
594                         .or(decl_id)
595                         .map(|id| id_from_def_id(id))
596                         .unwrap_or_else(|| null_id()),
597                 }))
598             }
599             ast::ExprKind::Path(_, ref path) => {
600                 self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
601             }
602             _ => {
603                 // FIXME
604                 bug!();
605             }
606         }
607     }
608
609     pub fn get_path_res(&self, id: NodeId) -> Res {
610         let hir_id = self.tcx.hir().node_to_hir_id(id);
611         match self.tcx.hir().get(hir_id) {
612             Node::TraitRef(tr) => tr.path.res,
613
614             Node::Item(&hir::Item {
615                 kind: hir::ItemKind::Use(ref path, _),
616                 ..
617             }) |
618             Node::Visibility(&Spanned {
619                 node: hir::VisibilityKind::Restricted { ref path, .. }, .. }) => path.res,
620
621             Node::PathSegment(seg) => {
622                 match seg.res {
623                     Some(res) if res != Res::Err => res,
624                     _ => {
625                         let parent_node = self.tcx.hir().get_parent_node(hir_id);
626                         self.get_path_res(self.tcx.hir().hir_to_node_id(parent_node))
627                     },
628                 }
629             }
630
631             Node::Expr(&hir::Expr {
632                 kind: hir::ExprKind::Struct(ref qpath, ..),
633                 ..
634             }) => {
635                 self.tables.qpath_res(qpath, hir_id)
636             }
637
638             Node::Expr(&hir::Expr {
639                 kind: hir::ExprKind::Path(ref qpath),
640                 ..
641             }) |
642             Node::Pat(&hir::Pat {
643                 kind: hir::PatKind::Path(ref qpath),
644                 ..
645             }) |
646             Node::Pat(&hir::Pat {
647                 kind: hir::PatKind::Struct(ref qpath, ..),
648                 ..
649             }) |
650             Node::Pat(&hir::Pat {
651                 kind: hir::PatKind::TupleStruct(ref qpath, ..),
652                 ..
653             }) |
654             Node::Ty(&hir::Ty {
655                 kind: hir::TyKind::Path(ref qpath),
656                 ..
657             }) => {
658                 self.tables.qpath_res(qpath, hir_id)
659             }
660
661             Node::Binding(&hir::Pat {
662                 kind: hir::PatKind::Binding(_, canonical_id, ..),
663                 ..
664             }) => Res::Local(canonical_id),
665
666             _ => Res::Err,
667         }
668     }
669
670     pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
671         path.segments
672             .last()
673             .and_then(|seg| {
674                 self.get_path_segment_data(seg)
675                     .or_else(|| self.get_path_segment_data_with_id(seg, id))
676             })
677     }
678
679     pub fn get_path_segment_data(&self, path_seg: &ast::PathSegment) -> Option<Ref> {
680         self.get_path_segment_data_with_id(path_seg, path_seg.id)
681     }
682
683     fn get_path_segment_data_with_id(
684         &self,
685         path_seg: &ast::PathSegment,
686         id: NodeId,
687     ) -> Option<Ref> {
688         // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
689         fn fn_type(seg: &ast::PathSegment) -> bool {
690             if let Some(ref generic_args) = seg.args {
691                 if let ast::GenericArgs::Parenthesized(_) = **generic_args {
692                     return true;
693                 }
694             }
695             false
696         }
697
698         if id == DUMMY_NODE_ID {
699             return None;
700         }
701
702         let res = self.get_path_res(id);
703         let span = path_seg.ident.span;
704         filter!(self.span_utils, span);
705         let span = self.span_from_span(span);
706
707         match res {
708             Res::Local(id) => {
709                 Some(Ref {
710                     kind: RefKind::Variable,
711                     span,
712                     ref_id: id_from_node_id(self.tcx.hir().hir_to_node_id(id), self),
713                 })
714             }
715             Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
716                 Some(Ref {
717                     kind: RefKind::Type,
718                     span,
719                     ref_id: id_from_def_id(def_id),
720                 })
721             }
722             Res::Def(HirDefKind::Struct, def_id) |
723             Res::Def(HirDefKind::Variant, def_id) |
724             Res::Def(HirDefKind::Union, def_id) |
725             Res::Def(HirDefKind::Enum, def_id) |
726             Res::Def(HirDefKind::TyAlias, def_id) |
727             Res::Def(HirDefKind::ForeignTy, def_id) |
728             Res::Def(HirDefKind::TraitAlias, def_id) |
729             Res::Def(HirDefKind::AssocOpaqueTy, def_id) |
730             Res::Def(HirDefKind::AssocTy, def_id) |
731             Res::Def(HirDefKind::Trait, def_id) |
732             Res::Def(HirDefKind::OpaqueTy, def_id) |
733             Res::Def(HirDefKind::TyParam, def_id) => {
734                 Some(Ref {
735                     kind: RefKind::Type,
736                     span,
737                     ref_id: id_from_def_id(def_id),
738                 })
739             }
740             Res::Def(HirDefKind::ConstParam, def_id) => {
741                 Some(Ref {
742                     kind: RefKind::Variable,
743                     span,
744                     ref_id: id_from_def_id(def_id),
745                 })
746             }
747             Res::Def(HirDefKind::Ctor(CtorOf::Struct, ..), def_id) => {
748                 // This is a reference to a tuple struct where the def_id points
749                 // to an invisible constructor function. That is not a very useful
750                 // def, so adjust to point to the tuple struct itself.
751                 let parent_def_id = self.tcx.parent(def_id).unwrap();
752                 Some(Ref {
753                     kind: RefKind::Type,
754                     span,
755                     ref_id: id_from_def_id(parent_def_id),
756                 })
757             }
758             Res::Def(HirDefKind::Static, _) |
759             Res::Def(HirDefKind::Const, _) |
760             Res::Def(HirDefKind::AssocConst, _) |
761             Res::Def(HirDefKind::Ctor(..), _) => {
762                 Some(Ref {
763                     kind: RefKind::Variable,
764                     span,
765                     ref_id: id_from_def_id(res.def_id()),
766                 })
767             }
768             Res::Def(HirDefKind::Method, decl_id) => {
769                 let def_id = if decl_id.is_local() {
770                     let ti = self.tcx.associated_item(decl_id);
771                     self.tcx
772                         .associated_items(ti.container.id())
773                         .find(|item| item.ident.name == ti.ident.name &&
774                                      item.defaultness.has_value())
775                         .map(|item| item.def_id)
776                 } else {
777                     None
778                 };
779                 Some(Ref {
780                     kind: RefKind::Function,
781                     span,
782                     ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
783                 })
784             }
785             Res::Def(HirDefKind::Fn, def_id) => {
786                 Some(Ref {
787                     kind: RefKind::Function,
788                     span,
789                     ref_id: id_from_def_id(def_id),
790                 })
791             }
792             Res::Def(HirDefKind::Mod, def_id) => {
793                 Some(Ref {
794                     kind: RefKind::Mod,
795                     span,
796                     ref_id: id_from_def_id(def_id),
797                 })
798             }
799             Res::PrimTy(..) |
800             Res::SelfTy(..) |
801             Res::Def(HirDefKind::Macro(..), _) |
802             Res::ToolMod |
803             Res::NonMacroAttr(..) |
804             Res::SelfCtor(..) |
805             Res::Err => None,
806         }
807     }
808
809     pub fn get_field_ref_data(
810         &self,
811         field_ref: &ast::Field,
812         variant: &ty::VariantDef,
813     ) -> Option<Ref> {
814         filter!(self.span_utils, field_ref.ident.span);
815         self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
816             let span = self.span_from_span(field_ref.ident.span);
817             Ref {
818                 kind: RefKind::Variable,
819                 span,
820                 ref_id: id_from_def_id(variant.fields[index].did),
821             }
822         })
823     }
824
825     /// Attempt to return MacroRef for any AST node.
826     ///
827     /// For a given piece of AST defined by the supplied Span and NodeId,
828     /// returns `None` if the node is not macro-generated or the span is malformed,
829     /// else uses the expansion callsite and callee to return some MacroRef.
830     pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
831         if !generated_code(span) {
832             return None;
833         }
834         // Note we take care to use the source callsite/callee, to handle
835         // nested expansions and ensure we only generate data for source-visible
836         // macro uses.
837         let callsite = span.source_callsite();
838         let callsite_span = self.span_from_span(callsite);
839         let callee = span.source_callee()?;
840
841         // Ignore attribute macros, their spans are usually mangled
842         if let ExpnKind::Macro(MacroKind::Attr, _) |
843                ExpnKind::Macro(MacroKind::Derive, _) = callee.kind {
844             return None;
845         }
846
847         // If the callee is an imported macro from an external crate, need to get
848         // the source span and name from the session, as their spans are localized
849         // when read in, and no longer correspond to the source.
850         if let Some(mac) = self.tcx
851             .sess
852             .imported_macro_spans
853             .borrow()
854             .get(&callee.def_site)
855         {
856             let &(ref mac_name, mac_span) = mac;
857             let mac_span = self.span_from_span(mac_span);
858             return Some(MacroRef {
859                 span: callsite_span,
860                 qualname: mac_name.clone(), // FIXME: generate the real qualname
861                 callee_span: mac_span,
862             });
863         }
864
865         let callee_span = self.span_from_span(callee.def_site);
866         Some(MacroRef {
867             span: callsite_span,
868             qualname: callee.kind.descr().to_string(), // FIXME: generate the real qualname
869             callee_span,
870         })
871     }
872
873     fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
874         match self.get_path_res(ref_id) {
875             Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
876             def => Some(def.def_id()),
877         }
878     }
879
880     fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
881         let mut result = String::new();
882
883         for attr in attrs {
884             if attr.check_name(sym::doc) {
885                 if let Some(val) = attr.value_str() {
886                     if attr.is_sugared_doc {
887                         result.push_str(&strip_doc_comment_decoration(&val.as_str()));
888                     } else {
889                         result.push_str(&val.as_str());
890                     }
891                     result.push('\n');
892                 } else if let Some(meta_list) = attr.meta_item_list() {
893                     meta_list.into_iter()
894                              .filter(|it| it.check_name(sym::include))
895                              .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
896                              .flat_map(|it| it)
897                              .filter(|meta| meta.check_name(sym::contents))
898                              .filter_map(|meta| meta.value_str())
899                              .for_each(|val| {
900                                  result.push_str(&val.as_str());
901                                  result.push('\n');
902                              });
903                 }
904             }
905         }
906
907         if !self.config.full_docs {
908             if let Some(index) = result.find("\n\n") {
909                 result.truncate(index);
910             }
911         }
912
913         result
914     }
915
916     fn next_impl_id(&self) -> u32 {
917         let next = self.impl_counter.get();
918         self.impl_counter.set(next + 1);
919         next
920     }
921 }
922
923 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
924     let mut sig = "fn ".to_owned();
925     if !generics.params.is_empty() {
926         sig.push('<');
927         sig.push_str(&generics
928             .params
929             .iter()
930             .map(|param| param.ident.to_string())
931             .collect::<Vec<_>>()
932             .join(", "));
933         sig.push_str("> ");
934     }
935     sig.push('(');
936     sig.push_str(&decl.inputs
937         .iter()
938         .map(param_to_string)
939         .collect::<Vec<_>>()
940         .join(", "));
941     sig.push(')');
942     match decl.output {
943         ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
944         ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
945     }
946
947     sig
948 }
949
950 // An AST visitor for collecting paths (e.g., the names of structs) and formal
951 // variables (idents) from patterns.
952 struct PathCollector<'l> {
953     collected_paths: Vec<(NodeId, &'l ast::Path)>,
954     collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
955 }
956
957 impl<'l> PathCollector<'l> {
958     fn new() -> PathCollector<'l> {
959         PathCollector {
960             collected_paths: vec![],
961             collected_idents: vec![],
962         }
963     }
964 }
965
966 impl<'l> Visitor<'l> for PathCollector<'l> {
967     fn visit_pat(&mut self, p: &'l ast::Pat) {
968         match p.kind {
969             PatKind::Struct(ref path, ..) => {
970                 self.collected_paths.push((p.id, path));
971             }
972             PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
973                 self.collected_paths.push((p.id, path));
974             }
975             PatKind::Ident(bm, ident, _) => {
976                 debug!(
977                     "PathCollector, visit ident in pat {}: {:?} {:?}",
978                     ident,
979                     p.span,
980                     ident.span
981                 );
982                 let immut = match bm {
983                     // Even if the ref is mut, you can't change the ref, only
984                     // the data pointed at, so showing the initialising expression
985                     // is still worthwhile.
986                     ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
987                     ast::BindingMode::ByValue(mt) => mt,
988                 };
989                 self.collected_idents
990                     .push((p.id, ident, immut));
991             }
992             _ => {}
993         }
994         visit::walk_pat(self, p);
995     }
996 }
997
998 /// Defines what to do with the results of saving the analysis.
999 pub trait SaveHandler {
1000     fn save(
1001         &mut self,
1002         save_ctxt: &SaveContext<'_, '_>,
1003         analysis: &Analysis,
1004     );
1005 }
1006
1007 /// Dump the save-analysis results to a file.
1008 pub struct DumpHandler<'a> {
1009     odir: Option<&'a Path>,
1010     cratename: String,
1011 }
1012
1013 impl<'a> DumpHandler<'a> {
1014     pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
1015         DumpHandler {
1016             odir,
1017             cratename: cratename.to_owned(),
1018         }
1019     }
1020
1021     fn output_file(&self, ctx: &SaveContext<'_, '_>) -> (BufWriter<File>, PathBuf) {
1022         let sess = &ctx.tcx.sess;
1023         let file_name = match ctx.config.output_file {
1024             Some(ref s) => PathBuf::from(s),
1025             None => {
1026                 let mut root_path = match self.odir {
1027                     Some(val) => val.join("save-analysis"),
1028                     None => PathBuf::from("save-analysis-temp"),
1029                 };
1030
1031                 if let Err(e) = std::fs::create_dir_all(&root_path) {
1032                     error!("Could not create directory {}: {}", root_path.display(), e);
1033                 }
1034
1035                 let executable = sess.crate_types
1036                     .borrow()
1037                     .iter()
1038                     .any(|ct| *ct == CrateType::Executable);
1039                 let mut out_name = if executable {
1040                     String::new()
1041                 } else {
1042                     "lib".to_owned()
1043                 };
1044                 out_name.push_str(&self.cratename);
1045                 out_name.push_str(&sess.opts.cg.extra_filename);
1046                 out_name.push_str(".json");
1047                 root_path.push(&out_name);
1048
1049                 root_path
1050             }
1051         };
1052
1053         info!("Writing output to {}", file_name.display());
1054
1055         let output_file = BufWriter::new(File::create(&file_name).unwrap_or_else(
1056             |e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
1057         ));
1058
1059         (output_file, file_name)
1060     }
1061 }
1062
1063 impl SaveHandler for DumpHandler<'_> {
1064     fn save(
1065         &mut self,
1066         save_ctxt: &SaveContext<'_, '_>,
1067         analysis: &Analysis,
1068     ) {
1069         let sess = &save_ctxt.tcx.sess;
1070         let (output, file_name) = self.output_file(&save_ctxt);
1071         if let Err(e) = serde_json::to_writer(output, &analysis) {
1072             error!("Can't serialize save-analysis: {:?}", e);
1073         }
1074
1075         if sess.opts.json_artifact_notifications {
1076             sess.parse_sess.span_diagnostic
1077                 .emit_artifact_notification(&file_name, "save-analysis");
1078         }
1079     }
1080 }
1081
1082 /// Call a callback with the results of save-analysis.
1083 pub struct CallbackHandler<'b> {
1084     pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
1085 }
1086
1087 impl SaveHandler for CallbackHandler<'_> {
1088     fn save(
1089         &mut self,
1090         _: &SaveContext<'_, '_>,
1091         analysis: &Analysis,
1092     ) {
1093         (self.callback)(analysis)
1094     }
1095 }
1096
1097 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1098     tcx: TyCtxt<'tcx>,
1099     krate: &ast::Crate,
1100     cratename: &str,
1101     input: &'l Input,
1102     config: Option<Config>,
1103     mut handler: H,
1104 ) {
1105     tcx.dep_graph.with_ignore(|| {
1106         info!("Dumping crate {}", cratename);
1107
1108         // Privacy checking requires and is done after type checking; use a
1109         // fallback in case the access levels couldn't have been correctly computed.
1110         let access_levels = match tcx.sess.compile_status() {
1111             Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1112             Err(..) => tcx.arena.alloc(AccessLevels::default()),
1113         };
1114
1115         let save_ctxt = SaveContext {
1116             tcx,
1117             tables: &ty::TypeckTables::empty(None),
1118             access_levels: &access_levels,
1119             span_utils: SpanUtils::new(&tcx.sess),
1120             config: find_config(config),
1121             impl_counter: Cell::new(0),
1122         };
1123
1124         let mut visitor = DumpVisitor::new(save_ctxt);
1125
1126         visitor.dump_crate_info(cratename, krate);
1127         visitor.dump_compilation_options(input, cratename);
1128         visit::walk_crate(&mut visitor, krate);
1129
1130         handler.save(&visitor.save_ctxt, &visitor.analysis())
1131     })
1132 }
1133
1134 fn find_config(supplied: Option<Config>) -> Config {
1135     if let Some(config) = supplied {
1136         return config;
1137     }
1138
1139     match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1140         None => Config::default(),
1141         Some(config) => config.to_str()
1142             .ok_or(())
1143             .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1144             .and_then(|cfg|  serde_json::from_str(cfg)
1145                 .map_err(|_| error!("Could not deserialize save-analysis config"))
1146             ).unwrap_or_default()
1147     }
1148 }
1149
1150 // Utility functions for the module.
1151
1152 // Helper function to escape quotes in a string
1153 fn escape(s: String) -> String {
1154     s.replace("\"", "\"\"")
1155 }
1156
1157 // Helper function to determine if a span came from a
1158 // macro expansion or syntax extension.
1159 fn generated_code(span: Span) -> bool {
1160     span.from_expansion() || span.is_dummy()
1161 }
1162
1163 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1164 // we use our own Id which is the same, but without the newtype.
1165 fn id_from_def_id(id: DefId) -> rls_data::Id {
1166     rls_data::Id {
1167         krate: id.krate.as_u32(),
1168         index: id.index.as_u32(),
1169     }
1170 }
1171
1172 fn id_from_node_id(id: NodeId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
1173     let def_id = scx.tcx.hir().opt_local_def_id_from_node_id(id);
1174     def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
1175         // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
1176         // out of the maximum u32 value. This will work unless you have *billions*
1177         // of definitions in a single crate (very unlikely to actually happen).
1178         rls_data::Id {
1179             krate: LOCAL_CRATE.as_u32(),
1180             index: !id.as_u32(),
1181         }
1182     })
1183 }
1184
1185 fn null_id() -> rls_data::Id {
1186     rls_data::Id {
1187         krate: u32::max_value(),
1188         index: u32::max_value(),
1189     }
1190 }
1191
1192 fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> {
1193     attrs.into_iter()
1194     // Only retain real attributes. Doc comments are lowered separately.
1195     .filter(|attr| attr.path != sym::doc)
1196     .map(|mut attr| {
1197         // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1198         // attribute. First normalize all inner attribute (#![..]) to outer
1199         // ones (#[..]), then remove the two leading and the one trailing character.
1200         attr.style = ast::AttrStyle::Outer;
1201         let value = pprust::attribute_to_string(&attr);
1202         // This str slicing works correctly, because the leading and trailing characters
1203         // are in the ASCII range and thus exactly one byte each.
1204         let value = value[2..value.len()-1].to_string();
1205
1206         rls_data::Attribute {
1207             value,
1208             span: scx.span_from_span(attr.span),
1209         }
1210     }).collect()
1211 }