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