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