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