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