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