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