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