1 //! Fully type-check project and print various stats, like the number of type
6 time::{SystemTime, UNIX_EPOCH},
10 db::{AstDatabase, DefDatabase, HirDatabase},
11 AssocItem, Crate, Function, HasSource, HirDisplay, ModuleDef,
14 body::{BodySourceMap, SyntheticSyntax},
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,
24 use itertools::Itertools;
26 use profile::{Bytes, StopWatch};
27 use project_model::{CargoConfig, ProjectManifest, ProjectWorkspace, RustcSource};
28 use rayon::prelude::*;
29 use rustc_hash::FxHashSet;
31 use syntax::{AstNode, SyntaxNode};
32 use vfs::{AbsPathBuf, Vfs, VfsPath};
35 flags::{self, OutputFormat},
36 load_cargo::{load_workspace, LoadCargoConfig},
38 progress_report::ProgressReport,
39 report_metric, Result, Verbosity,
42 /// Need to wrap Snapshot to provide `Clone` impl for `map_with`
44 impl<DB: ParallelDatabase> Clone for Snap<salsa::Snapshot<DB>> {
45 fn clone(&self) -> Snap<salsa::Snapshot<DB>> {
46 Snap(self.0.snapshot())
50 impl flags::AnalysisStats {
51 pub fn run(self, verbosity: Verbosity) -> Result<()> {
53 let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
57 let mut cargo_config = CargoConfig::default();
58 cargo_config.sysroot = match self.no_sysroot {
60 false => Some(RustcSource::Discover),
62 let load_cargo_config = LoadCargoConfig {
63 load_out_dirs_from_check: !self.disable_build_scripts,
64 with_proc_macro: !self.disable_proc_macros,
65 prefill_caches: false,
67 let no_progress = &|_| ();
69 let mut db_load_sw = self.stop_watch();
71 let path = AbsPathBuf::assert(env::current_dir()?.join(&self.path));
72 let manifest = ProjectManifest::discover_single(&path)?;
74 let mut workspace = ProjectWorkspace::load(manifest, &cargo_config, no_progress)?;
75 let metadata_time = db_load_sw.elapsed();
77 let build_scripts_time = if self.disable_build_scripts {
80 let mut build_scripts_sw = self.stop_watch();
81 let bs = workspace.run_build_scripts(&cargo_config, no_progress)?;
82 workspace.set_build_scripts(bs);
83 Some(build_scripts_sw.elapsed())
86 let (host, vfs, _proc_macro) =
87 load_workspace(workspace, &cargo_config.extra_env, &load_cargo_config)?;
88 let db = host.raw_database();
89 eprint!("{:<20} {}", "Database loaded:", db_load_sw.elapsed());
90 eprint!(" (metadata {metadata_time}");
91 if let Some(build_scripts_time) = build_scripts_time {
92 eprint!("; build {build_scripts_time}");
96 let mut analysis_sw = self.stop_watch();
97 let mut num_crates = 0;
98 let mut visited_modules = FxHashSet::default();
99 let mut visit_queue = Vec::new();
101 let mut krates = Crate::all(db);
103 shuffle(&mut rng, &mut krates);
105 for krate in krates {
106 let module = krate.root_module(db);
107 let file_id = module.definition_source(db).file_id;
108 let file_id = file_id.original_file(db);
109 let source_root = db.file_source_root(file_id);
110 let source_root = db.source_root(source_root);
111 if !source_root.is_library || self.with_deps {
113 visit_queue.push(module);
118 shuffle(&mut rng, &mut visit_queue);
121 eprint!(" crates: {num_crates}");
122 let mut num_decls = 0;
123 let mut funcs = Vec::new();
124 while let Some(module) = visit_queue.pop() {
125 if visited_modules.insert(module) {
126 visit_queue.extend(module.children(db));
128 for decl in module.declarations(db) {
130 if let ModuleDef::Function(f) = decl {
135 for impl_def in module.impl_defs(db) {
136 for item in impl_def.items(db) {
138 if let AssocItem::Function(f) = item {
145 eprintln!(", mods: {}, decls: {num_decls}, fns: {}", visited_modules.len(), funcs.len());
146 eprintln!("{:<20} {}", "Item Collection:", analysis_sw.elapsed());
149 shuffle(&mut rng, &mut funcs);
152 if !self.skip_inference {
153 self.run_inference(&host, db, &vfs, &funcs, verbosity);
156 let total_span = analysis_sw.elapsed();
157 eprintln!("{:<20} {total_span}", "Total:");
158 report_metric("total time", total_span.time.as_millis() as u64, "ms");
159 if let Some(instructions) = total_span.instructions {
160 report_metric("total instructions", instructions, "#instr");
162 if let Some(memory) = total_span.memory {
163 report_metric("total memory", memory.allocated.megabytes() as u64, "MB");
166 if env::var("RA_COUNT").is_ok() {
167 eprintln!("{}", profile::countme::get_all());
170 if self.source_stats {
171 let mut total_file_size = Bytes::default();
172 for e in ide_db::base_db::ParseQuery.in_db(db).entries::<Vec<_>>() {
173 total_file_size += syntax_len(db.parse(e.key).syntax_node())
176 let mut total_macro_file_size = Bytes::default();
177 for e in hir::db::ParseMacroExpansionQuery.in_db(db).entries::<Vec<_>>() {
178 if let Some((val, _)) = db.parse_macro_expansion(e.key).value {
179 total_macro_file_size += syntax_len(val.syntax_node())
182 eprintln!("source files: {total_file_size}, macro files: {total_macro_file_size}");
185 if self.memory_usage && verbosity.is_verbose() {
186 print_memory_usage(host, vfs);
198 verbosity: Verbosity,
200 let mut bar = match verbosity {
201 Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
202 _ if self.parallel || self.output.is_some() => ProgressReport::hidden(),
203 _ => ProgressReport::new(funcs.len() as u64),
207 let mut inference_sw = self.stop_watch();
208 let snap = Snap(db.snapshot());
211 .map_with(snap, |snap, &f| {
212 let f_id = FunctionId::from(f);
213 snap.0.body(f_id.into());
214 snap.0.infer(f_id.into());
217 eprintln!("{:<20} {}", "Parallel Inference:", inference_sw.elapsed());
220 let mut inference_sw = self.stop_watch();
222 let mut num_exprs = 0;
223 let mut num_exprs_unknown = 0;
224 let mut num_exprs_partially_unknown = 0;
225 let mut num_type_mismatches = 0;
226 let analysis = host.analysis();
227 for f in funcs.iter().copied() {
228 let name = f.name(db);
234 .filter_map(|it| it.name(db))
235 .chain(Some(f.name(db)))
237 if let Some(only_name) = self.only.as_deref() {
238 if name.to_string() != only_name && full_name != only_name {
242 let mut msg = format!("processing: {full_name}");
243 if verbosity.is_verbose() {
244 if let Some(src) = f.source(db) {
245 let original_file = src.file_id.original_file(db);
246 let path = vfs.file_path(original_file);
247 let syntax_range = src.value.syntax().text_range();
248 format_to!(msg, " ({} {:?})", path, syntax_range);
251 if verbosity.is_spammy() {
252 bar.println(msg.to_string());
254 bar.set_message(&msg);
255 let f_id = FunctionId::from(f);
256 let (body, sm) = db.body_with_source_map(f_id.into());
257 let inference_result = db.infer(f_id.into());
258 let (previous_exprs, previous_unknown, previous_partially_unknown) =
259 (num_exprs, num_exprs_unknown, num_exprs_partially_unknown);
260 for (expr_id, _) in body.exprs.iter() {
261 let ty = &inference_result[expr_id];
263 let unknown_or_partial = if ty.is_unknown() {
264 num_exprs_unknown += 1;
265 if verbosity.is_spammy() {
266 if let Some((path, start, end)) =
267 expr_syntax_range(db, &analysis, vfs, &sm, expr_id)
270 "{} {}:{}-{}:{}: Unknown type",
278 bar.println(format!("{name}: Unknown type",));
283 let mut is_partially_unknown = false;
286 is_partially_unknown = true;
289 if is_partially_unknown {
290 num_exprs_partially_unknown += 1;
294 if self.only.is_some() && verbosity.is_spammy() {
295 // in super-verbose mode for just one function, we print every single expression
296 if let Some((_, start, end)) =
297 expr_syntax_range(db, &analysis, vfs, &sm, expr_id)
308 bar.println(format!("unknown location: {}", ty.display(db)));
311 if unknown_or_partial && self.output == Some(OutputFormat::Csv) {
314 location_csv(db, &analysis, vfs, &sm, expr_id),
318 if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr_id) {
319 num_type_mismatches += 1;
320 if verbosity.is_verbose() {
321 if let Some((path, start, end)) =
322 expr_syntax_range(db, &analysis, vfs, &sm, expr_id)
325 "{} {}:{}-{}:{}: Expected {}, got {}",
331 mismatch.expected.display(db),
332 mismatch.actual.display(db)
336 "{}: Expected {}, got {}",
338 mismatch.expected.display(db),
339 mismatch.actual.display(db)
343 if self.output == Some(OutputFormat::Csv) {
345 r#"{},mismatch,"{}","{}""#,
346 location_csv(db, &analysis, vfs, &sm, expr_id),
347 mismatch.expected.display(db),
348 mismatch.actual.display(db)
353 if verbosity.is_spammy() {
355 "In {}: {} exprs, {} unknown, {} partial",
357 num_exprs - previous_exprs,
358 num_exprs_unknown - previous_unknown,
359 num_exprs_partially_unknown - previous_partially_unknown
365 bar.finish_and_clear();
367 " exprs: {}, ??ty: {} ({}%), ?ty: {} ({}%), !ty: {}",
370 percentage(num_exprs_unknown, num_exprs),
371 num_exprs_partially_unknown,
372 percentage(num_exprs_partially_unknown, num_exprs),
375 report_metric("unknown type", num_exprs_unknown, "#");
376 report_metric("type mismatches", num_type_mismatches, "#");
378 eprintln!("{:<20} {}", "Inference:", inference_sw.elapsed());
381 fn stop_watch(&self) -> StopWatch {
382 StopWatch::start().memory(self.memory_usage)
393 let src = match sm.expr_syntax(expr_id) {
395 Err(SyntheticSyntax) => return "synthetic,,".to_string(),
397 let root = db.parse_or_expand(src.file_id).unwrap();
398 let node = src.map(|e| e.to_node(&root).syntax().clone());
399 let original_range = node.as_ref().original_file_range(db);
400 let path = vfs.file_path(original_range.file_id);
401 let line_index = analysis.file_line_index(original_range.file_id).unwrap();
402 let text_range = original_range.range;
404 (line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
405 format!("{path},{}:{},{}:{}", start.line + 1, start.col, end.line + 1, end.col)
408 fn expr_syntax_range(
414 ) -> Option<(VfsPath, LineCol, LineCol)> {
415 let src = sm.expr_syntax(expr_id);
416 if let Ok(src) = src {
417 let root = db.parse_or_expand(src.file_id).unwrap();
418 let node = src.map(|e| e.to_node(&root).syntax().clone());
419 let original_range = node.as_ref().original_file_range(db);
420 let path = vfs.file_path(original_range.file_id);
421 let line_index = analysis.file_line_index(original_range.file_id).unwrap();
422 let text_range = original_range.range;
424 (line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
425 Some((path, start, end))
431 fn shuffle<T>(rng: &mut Rand32, slice: &mut [T]) {
432 for i in 0..slice.len() {
433 randomize_first(rng, &mut slice[i..]);
436 fn randomize_first<T>(rng: &mut Rand32, slice: &mut [T]) {
437 assert!(!slice.is_empty());
438 let idx = rng.rand_range(0..slice.len() as u32) as usize;
443 fn percentage(n: u64, total: u64) -> u64 {
444 (n * 100).checked_div(total).unwrap_or(100)
447 fn syntax_len(node: SyntaxNode) -> usize {
448 // Macro expanded code doesn't contain whitespace, so erase *all* whitespace
449 // to make macro and non-macro code comparable.
450 node.to_string().replace(|it: char| it.is_ascii_whitespace(), "").len()