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