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