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