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