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