]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs
Rollup merge of #99671 - TaKO8Ki:suggest-dereferencing-index, r=compiler-errors
[rust.git] / src / tools / rust-analyzer / crates / rust-analyzer / src / cli / analysis_stats.rs
1 //! Fully type-check project and print various stats, like the number of type
2 //! errors.
3
4 use std::{
5     env,
6     time::{SystemTime, UNIX_EPOCH},
7 };
8
9 use hir::{
10     db::{AstDatabase, DefDatabase, HirDatabase},
11     AssocItem, Crate, Function, HasSource, HirDisplay, ModuleDef,
12 };
13 use hir_def::{
14     body::{BodySourceMap, SyntheticSyntax},
15     expr::ExprId,
16     FunctionId,
17 };
18 use hir_ty::{TyExt, TypeWalk};
19 use ide::{Analysis, AnalysisHost, LineCol, RootDatabase};
20 use ide_db::base_db::{
21     salsa::{self, debug::DebugQueryTable, ParallelDatabase},
22     SourceDatabase, SourceDatabaseExt,
23 };
24 use itertools::Itertools;
25 use oorandom::Rand32;
26 use profile::{Bytes, StopWatch};
27 use project_model::{CargoConfig, ProjectManifest, ProjectWorkspace};
28 use rayon::prelude::*;
29 use rustc_hash::FxHashSet;
30 use stdx::format_to;
31 use syntax::{AstNode, SyntaxNode};
32 use vfs::{AbsPathBuf, Vfs, VfsPath};
33
34 use crate::cli::{
35     flags::{self, OutputFormat},
36     load_cargo::{load_workspace, LoadCargoConfig},
37     print_memory_usage,
38     progress_report::ProgressReport,
39     report_metric, Result, Verbosity,
40 };
41
42 /// Need to wrap Snapshot to provide `Clone` impl for `map_with`
43 struct Snap<DB>(DB);
44 impl<DB: ParallelDatabase> Clone for Snap<salsa::Snapshot<DB>> {
45     fn clone(&self) -> Snap<salsa::Snapshot<DB>> {
46         Snap(self.0.snapshot())
47     }
48 }
49
50 impl flags::AnalysisStats {
51     pub fn run(self, verbosity: Verbosity) -> Result<()> {
52         let mut rng = {
53             let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
54             Rand32::new(seed)
55         };
56
57         let mut cargo_config = CargoConfig::default();
58         cargo_config.no_sysroot = self.no_sysroot;
59         let load_cargo_config = LoadCargoConfig {
60             load_out_dirs_from_check: !self.disable_build_scripts,
61             with_proc_macro: !self.disable_proc_macros,
62             prefill_caches: false,
63         };
64         let no_progress = &|_| ();
65
66         let mut db_load_sw = self.stop_watch();
67
68         let path = AbsPathBuf::assert(env::current_dir()?.join(&self.path));
69         let manifest = ProjectManifest::discover_single(&path)?;
70
71         let mut workspace = ProjectWorkspace::load(manifest, &cargo_config, no_progress)?;
72         let metadata_time = db_load_sw.elapsed();
73
74         let build_scripts_time = if self.disable_build_scripts {
75             None
76         } else {
77             let mut build_scripts_sw = self.stop_watch();
78             let bs = workspace.run_build_scripts(&cargo_config, no_progress)?;
79             workspace.set_build_scripts(bs);
80             Some(build_scripts_sw.elapsed())
81         };
82
83         let (host, vfs, _proc_macro) = load_workspace(workspace, &load_cargo_config)?;
84         let db = host.raw_database();
85         eprint!("{:<20} {}", "Database loaded:", db_load_sw.elapsed());
86         eprint!(" (metadata {}", metadata_time);
87         if let Some(build_scripts_time) = build_scripts_time {
88             eprint!("; build {}", build_scripts_time);
89         }
90         eprintln!(")");
91
92         let mut analysis_sw = self.stop_watch();
93         let mut num_crates = 0;
94         let mut visited_modules = FxHashSet::default();
95         let mut visit_queue = Vec::new();
96
97         let mut krates = Crate::all(db);
98         if self.randomize {
99             shuffle(&mut rng, &mut krates);
100         }
101         for krate in krates {
102             let module = krate.root_module(db);
103             let file_id = module.definition_source(db).file_id;
104             let file_id = file_id.original_file(db);
105             let source_root = db.file_source_root(file_id);
106             let source_root = db.source_root(source_root);
107             if !source_root.is_library || self.with_deps {
108                 num_crates += 1;
109                 visit_queue.push(module);
110             }
111         }
112
113         if self.randomize {
114             shuffle(&mut rng, &mut visit_queue);
115         }
116
117         eprint!("  crates: {}", num_crates);
118         let mut num_decls = 0;
119         let mut funcs = Vec::new();
120         while let Some(module) = visit_queue.pop() {
121             if visited_modules.insert(module) {
122                 visit_queue.extend(module.children(db));
123
124                 for decl in module.declarations(db) {
125                     num_decls += 1;
126                     if let ModuleDef::Function(f) = decl {
127                         funcs.push(f);
128                     }
129                 }
130
131                 for impl_def in module.impl_defs(db) {
132                     for item in impl_def.items(db) {
133                         num_decls += 1;
134                         if let AssocItem::Function(f) = item {
135                             funcs.push(f);
136                         }
137                     }
138                 }
139             }
140         }
141         eprintln!(", mods: {}, decls: {}, fns: {}", visited_modules.len(), num_decls, funcs.len());
142         eprintln!("{:<20} {}", "Item Collection:", analysis_sw.elapsed());
143
144         if self.randomize {
145             shuffle(&mut rng, &mut funcs);
146         }
147
148         if !self.skip_inference {
149             self.run_inference(&host, db, &vfs, &funcs, verbosity);
150         }
151
152         let total_span = analysis_sw.elapsed();
153         eprintln!("{:<20} {}", "Total:", total_span);
154         report_metric("total time", total_span.time.as_millis() as u64, "ms");
155         if let Some(instructions) = total_span.instructions {
156             report_metric("total instructions", instructions, "#instr");
157         }
158         if let Some(memory) = total_span.memory {
159             report_metric("total memory", memory.allocated.megabytes() as u64, "MB");
160         }
161
162         if env::var("RA_COUNT").is_ok() {
163             eprintln!("{}", profile::countme::get_all());
164         }
165
166         if self.source_stats {
167             let mut total_file_size = Bytes::default();
168             for e in ide_db::base_db::ParseQuery.in_db(db).entries::<Vec<_>>() {
169                 total_file_size += syntax_len(db.parse(e.key).syntax_node())
170             }
171
172             let mut total_macro_file_size = Bytes::default();
173             for e in hir::db::ParseMacroExpansionQuery.in_db(db).entries::<Vec<_>>() {
174                 if let Some((val, _)) = db.parse_macro_expansion(e.key).value {
175                     total_macro_file_size += syntax_len(val.syntax_node())
176                 }
177             }
178             eprintln!("source files: {}, macro files: {}", total_file_size, total_macro_file_size);
179         }
180
181         if self.memory_usage && verbosity.is_verbose() {
182             print_memory_usage(host, vfs);
183         }
184
185         Ok(())
186     }
187
188     fn run_inference(
189         &self,
190         host: &AnalysisHost,
191         db: &RootDatabase,
192         vfs: &Vfs,
193         funcs: &[Function],
194         verbosity: Verbosity,
195     ) {
196         let mut bar = match verbosity {
197             Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
198             _ if self.parallel || self.output.is_some() => ProgressReport::hidden(),
199             _ => ProgressReport::new(funcs.len() as u64),
200         };
201
202         if self.parallel {
203             let mut inference_sw = self.stop_watch();
204             let snap = Snap(db.snapshot());
205             funcs
206                 .par_iter()
207                 .map_with(snap, |snap, &f| {
208                     let f_id = FunctionId::from(f);
209                     snap.0.body(f_id.into());
210                     snap.0.infer(f_id.into());
211                 })
212                 .count();
213             eprintln!("{:<20} {}", "Parallel Inference:", inference_sw.elapsed());
214         }
215
216         let mut inference_sw = self.stop_watch();
217         bar.tick();
218         let mut num_exprs = 0;
219         let mut num_exprs_unknown = 0;
220         let mut num_exprs_partially_unknown = 0;
221         let mut num_type_mismatches = 0;
222         let analysis = host.analysis();
223         for f in funcs.iter().copied() {
224             let name = f.name(db);
225             let full_name = f
226                 .module(db)
227                 .path_to_root(db)
228                 .into_iter()
229                 .rev()
230                 .filter_map(|it| it.name(db))
231                 .chain(Some(f.name(db)))
232                 .join("::");
233             if let Some(only_name) = self.only.as_deref() {
234                 if name.to_string() != only_name && full_name != only_name {
235                     continue;
236                 }
237             }
238             let mut msg = format!("processing: {}", full_name);
239             if verbosity.is_verbose() {
240                 if let Some(src) = f.source(db) {
241                     let original_file = src.file_id.original_file(db);
242                     let path = vfs.file_path(original_file);
243                     let syntax_range = src.value.syntax().text_range();
244                     format_to!(msg, " ({} {:?})", path, syntax_range);
245                 }
246             }
247             if verbosity.is_spammy() {
248                 bar.println(msg.to_string());
249             }
250             bar.set_message(&msg);
251             let f_id = FunctionId::from(f);
252             let (body, sm) = db.body_with_source_map(f_id.into());
253             let inference_result = db.infer(f_id.into());
254             let (previous_exprs, previous_unknown, previous_partially_unknown) =
255                 (num_exprs, num_exprs_unknown, num_exprs_partially_unknown);
256             for (expr_id, _) in body.exprs.iter() {
257                 let ty = &inference_result[expr_id];
258                 num_exprs += 1;
259                 let unknown_or_partial = if ty.is_unknown() {
260                     num_exprs_unknown += 1;
261                     if verbosity.is_spammy() {
262                         if let Some((path, start, end)) =
263                             expr_syntax_range(db, &analysis, vfs, &sm, expr_id)
264                         {
265                             bar.println(format!(
266                                 "{} {}:{}-{}:{}: Unknown type",
267                                 path,
268                                 start.line + 1,
269                                 start.col,
270                                 end.line + 1,
271                                 end.col,
272                             ));
273                         } else {
274                             bar.println(format!("{}: Unknown type", name,));
275                         }
276                     }
277                     true
278                 } else {
279                     let mut is_partially_unknown = false;
280                     ty.walk(&mut |ty| {
281                         if ty.is_unknown() {
282                             is_partially_unknown = true;
283                         }
284                     });
285                     if is_partially_unknown {
286                         num_exprs_partially_unknown += 1;
287                     }
288                     is_partially_unknown
289                 };
290                 if self.only.is_some() && verbosity.is_spammy() {
291                     // in super-verbose mode for just one function, we print every single expression
292                     if let Some((_, start, end)) =
293                         expr_syntax_range(db, &analysis, vfs, &sm, expr_id)
294                     {
295                         bar.println(format!(
296                             "{}:{}-{}:{}: {}",
297                             start.line + 1,
298                             start.col,
299                             end.line + 1,
300                             end.col,
301                             ty.display(db)
302                         ));
303                     } else {
304                         bar.println(format!("unknown location: {}", ty.display(db)));
305                     }
306                 }
307                 if unknown_or_partial && self.output == Some(OutputFormat::Csv) {
308                     println!(
309                         r#"{},type,"{}""#,
310                         location_csv(db, &analysis, vfs, &sm, expr_id),
311                         ty.display(db)
312                     );
313                 }
314                 if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr_id) {
315                     num_type_mismatches += 1;
316                     if verbosity.is_verbose() {
317                         if let Some((path, start, end)) =
318                             expr_syntax_range(db, &analysis, vfs, &sm, expr_id)
319                         {
320                             bar.println(format!(
321                                 "{} {}:{}-{}:{}: Expected {}, got {}",
322                                 path,
323                                 start.line + 1,
324                                 start.col,
325                                 end.line + 1,
326                                 end.col,
327                                 mismatch.expected.display(db),
328                                 mismatch.actual.display(db)
329                             ));
330                         } else {
331                             bar.println(format!(
332                                 "{}: Expected {}, got {}",
333                                 name,
334                                 mismatch.expected.display(db),
335                                 mismatch.actual.display(db)
336                             ));
337                         }
338                     }
339                     if self.output == Some(OutputFormat::Csv) {
340                         println!(
341                             r#"{},mismatch,"{}","{}""#,
342                             location_csv(db, &analysis, vfs, &sm, expr_id),
343                             mismatch.expected.display(db),
344                             mismatch.actual.display(db)
345                         );
346                     }
347                 }
348             }
349             if verbosity.is_spammy() {
350                 bar.println(format!(
351                     "In {}: {} exprs, {} unknown, {} partial",
352                     full_name,
353                     num_exprs - previous_exprs,
354                     num_exprs_unknown - previous_unknown,
355                     num_exprs_partially_unknown - previous_partially_unknown
356                 ));
357             }
358             bar.inc(1);
359         }
360
361         bar.finish_and_clear();
362         eprintln!(
363             "  exprs: {}, ??ty: {} ({}%), ?ty: {} ({}%), !ty: {}",
364             num_exprs,
365             num_exprs_unknown,
366             percentage(num_exprs_unknown, num_exprs),
367             num_exprs_partially_unknown,
368             percentage(num_exprs_partially_unknown, num_exprs),
369             num_type_mismatches
370         );
371         report_metric("unknown type", num_exprs_unknown, "#");
372         report_metric("type mismatches", num_type_mismatches, "#");
373
374         eprintln!("{:<20} {}", "Inference:", inference_sw.elapsed());
375     }
376
377     fn stop_watch(&self) -> StopWatch {
378         StopWatch::start().memory(self.memory_usage)
379     }
380 }
381
382 fn location_csv(
383     db: &RootDatabase,
384     analysis: &Analysis,
385     vfs: &Vfs,
386     sm: &BodySourceMap,
387     expr_id: ExprId,
388 ) -> String {
389     let src = match sm.expr_syntax(expr_id) {
390         Ok(s) => s,
391         Err(SyntheticSyntax) => return "synthetic,,".to_string(),
392     };
393     let root = db.parse_or_expand(src.file_id).unwrap();
394     let node = src.map(|e| e.to_node(&root).syntax().clone());
395     let original_range = node.as_ref().original_file_range(db);
396     let path = vfs.file_path(original_range.file_id);
397     let line_index = analysis.file_line_index(original_range.file_id).unwrap();
398     let text_range = original_range.range;
399     let (start, end) =
400         (line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
401     format!("{},{}:{},{}:{}", path, start.line + 1, start.col, end.line + 1, end.col)
402 }
403
404 fn expr_syntax_range(
405     db: &RootDatabase,
406     analysis: &Analysis,
407     vfs: &Vfs,
408     sm: &BodySourceMap,
409     expr_id: ExprId,
410 ) -> Option<(VfsPath, LineCol, LineCol)> {
411     let src = sm.expr_syntax(expr_id);
412     if let Ok(src) = src {
413         let root = db.parse_or_expand(src.file_id).unwrap();
414         let node = src.map(|e| e.to_node(&root).syntax().clone());
415         let original_range = node.as_ref().original_file_range(db);
416         let path = vfs.file_path(original_range.file_id);
417         let line_index = analysis.file_line_index(original_range.file_id).unwrap();
418         let text_range = original_range.range;
419         let (start, end) =
420             (line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
421         Some((path, start, end))
422     } else {
423         None
424     }
425 }
426
427 fn shuffle<T>(rng: &mut Rand32, slice: &mut [T]) {
428     for i in 0..slice.len() {
429         randomize_first(rng, &mut slice[i..]);
430     }
431
432     fn randomize_first<T>(rng: &mut Rand32, slice: &mut [T]) {
433         assert!(!slice.is_empty());
434         let idx = rng.rand_range(0..slice.len() as u32) as usize;
435         slice.swap(0, idx);
436     }
437 }
438
439 fn percentage(n: u64, total: u64) -> u64 {
440     (n * 100).checked_div(total).unwrap_or(100)
441 }
442
443 fn syntax_len(node: SyntaxNode) -> usize {
444     // Macro expanded code doesn't contain whitespace, so erase *all* whitespace
445     // to make macro and non-macro code comparable.
446     node.to_string().replace(|it: char| it.is_ascii_whitespace(), "").len()
447 }