Skip to main content

rust_analyzer/cli/
analysis_stats.rs

1//! Fully type-check project and print various stats, like the number of type
2//! errors.
3
4use std::{
5    cell::LazyCell,
6    env, fmt,
7    ops::AddAssign,
8    panic::{AssertUnwindSafe, catch_unwind},
9    time::{SystemTime, UNIX_EPOCH},
10};
11
12use cfg::{CfgAtom, CfgDiff};
13use hir::{
14    Adt, AssocItem, Crate, DefWithBody, FindPathConfig, GenericDef, HasCrate, HasSource,
15    HirDisplay, ModuleDef, Name, Variant, crate_lang_items, db::HirDatabase,
16};
17use hir_def::{
18    DefWithBodyId, ExpressionStoreOwnerId, GenericDefId, SyntheticSyntax,
19    expr_store::{Body, BodySourceMap, ExpressionStore},
20    hir::{ExprId, PatId, generics::GenericParams},
21};
22use hir_ty::{InferenceResult, next_solver::GenericArgs};
23use ide::{
24    Analysis, AnalysisHost, AnnotationConfig, DiagnosticsConfig, Edition, InlayFieldsToResolve,
25    InlayHintsConfig, LineCol, RaFixtureConfig, RootDatabase,
26};
27use ide_db::{
28    EditionedFileId, SnippetCap,
29    base_db::{SourceDatabase, salsa::Database},
30    line_index,
31};
32use itertools::Itertools;
33use load_cargo::{LoadCargoConfig, ProcMacroServerChoice, load_workspace};
34use oorandom::Rand32;
35use profile::StopWatch;
36use project_model::{CargoConfig, CfgOverrides, ProjectManifest, ProjectWorkspace, RustLibSource};
37use rayon::prelude::*;
38use rustc_hash::{FxHashMap, FxHashSet};
39use rustc_type_ir::inherent::Ty as _;
40use syntax::AstNode;
41use vfs::{AbsPathBuf, Vfs, VfsPath};
42
43use crate::cli::{
44    Verbosity,
45    flags::{self, OutputFormat},
46    full_name_of_item, print_memory_usage,
47    progress_report::ProgressReport,
48    report_metric,
49};
50
51impl flags::AnalysisStats {
52    pub fn run(self, verbosity: Verbosity) -> anyhow::Result<()> {
53        let mut rayon_pool = rayon::ThreadPoolBuilder::new()
54            .thread_name(|ix| format!("RayonWorker{}", ix))
55            .stack_size(stdx::thread::DEFAULT_STACK_SIZE);
56        if !self.parallel {
57            rayon_pool = rayon_pool.num_threads(1);
58        }
59        rayon_pool.build_global().unwrap();
60
61        let mut rng = {
62            let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
63            Rand32::new(seed)
64        };
65
66        let cargo_config = CargoConfig {
67            sysroot: match self.no_sysroot {
68                true => None,
69                false => Some(RustLibSource::Discover),
70            },
71            all_targets: true,
72            set_test: !self.no_test,
73            cfg_overrides: CfgOverrides {
74                global: CfgDiff::new(vec![CfgAtom::Flag(hir::sym::miri)], vec![]),
75                selective: Default::default(),
76            },
77            ..Default::default()
78        };
79        let no_progress = &|_| ();
80
81        let mut db_load_sw = self.stop_watch();
82
83        let path = AbsPathBuf::assert_utf8(env::current_dir()?.join(&self.path));
84        let manifest = ProjectManifest::discover_single(&path)?;
85
86        let mut workspace = ProjectWorkspace::load(manifest, &cargo_config, no_progress)?;
87        let metadata_time = db_load_sw.elapsed();
88        let load_cargo_config = LoadCargoConfig {
89            load_out_dirs_from_check: !self.disable_build_scripts,
90            with_proc_macro_server: if self.disable_proc_macros {
91                ProcMacroServerChoice::None
92            } else {
93                match self.proc_macro_srv {
94                    Some(ref path) => {
95                        let path = vfs::AbsPathBuf::assert_utf8(path.to_owned());
96                        ProcMacroServerChoice::Explicit(path)
97                    }
98                    None => ProcMacroServerChoice::Sysroot,
99                }
100            },
101            prefill_caches: false,
102            num_worker_threads: 1,
103            proc_macro_processes: 1,
104        };
105
106        let build_scripts_time = if self.disable_build_scripts {
107            None
108        } else {
109            let mut build_scripts_sw = self.stop_watch();
110            let bs = workspace.run_build_scripts(&cargo_config, no_progress)?;
111            workspace.set_build_scripts(bs);
112            Some(build_scripts_sw.elapsed())
113        };
114
115        let (db, vfs, _proc_macro) =
116            load_workspace(workspace.clone(), &cargo_config.extra_env, &load_cargo_config)?;
117        eprint!("{:<20} {}", "Database loaded:", db_load_sw.elapsed());
118        eprint!(" (metadata {metadata_time}");
119        if let Some(build_scripts_time) = build_scripts_time {
120            eprint!("; build {build_scripts_time}");
121        }
122        eprintln!(")");
123
124        let mut host = AnalysisHost::with_database(db);
125        let db = host.raw_database();
126
127        let mut analysis_sw = self.stop_watch();
128
129        let mut krates = Crate::all(db);
130        if self.randomize {
131            shuffle(&mut rng, &mut krates);
132        }
133
134        let mut item_tree_sw = self.stop_watch();
135        let source_roots = krates
136            .iter()
137            .cloned()
138            .map(|krate| (db.file_source_root(krate.root_file(db)).source_root_id(db), krate))
139            .unique_by(|(source_root_id, _)| *source_root_id);
140
141        let mut dep_loc = 0;
142        let mut workspace_loc = 0;
143        let mut dep_item_trees = 0;
144        let mut workspace_item_trees = 0;
145
146        let mut workspace_item_stats = PrettyItemStats::default();
147        let mut dep_item_stats = PrettyItemStats::default();
148
149        for (source_root_id, krate) in source_roots {
150            let source_root = db.source_root(source_root_id).source_root(db);
151            for file_id in source_root.iter() {
152                if let Some(p) = source_root.path_for_file(&file_id)
153                    && let Some((_, Some("rs"))) = p.name_and_extension()
154                {
155                    // measure workspace/project code
156                    if !source_root.is_library || self.with_deps {
157                        let length = db.file_text(file_id).text(db).lines().count();
158                        let item_stats = hir::db::file_item_tree(
159                            db,
160                            EditionedFileId::current_edition(db, file_id).into(),
161                            krate.into(),
162                        )
163                        .item_tree_stats()
164                        .into();
165
166                        workspace_loc += length;
167                        workspace_item_trees += 1;
168                        workspace_item_stats += item_stats;
169                    } else {
170                        let length = db.file_text(file_id).text(db).lines().count();
171                        let item_stats = hir::db::file_item_tree(
172                            db,
173                            EditionedFileId::current_edition(db, file_id).into(),
174                            krate.into(),
175                        )
176                        .item_tree_stats()
177                        .into();
178
179                        dep_loc += length;
180                        dep_item_trees += 1;
181                        dep_item_stats += item_stats;
182                    }
183                }
184            }
185        }
186        eprintln!("  item trees: {workspace_item_trees}");
187        let item_tree_time = item_tree_sw.elapsed();
188
189        eprintln!(
190            "  dependency lines of code: {}, item trees: {}",
191            UsizeWithUnderscore(dep_loc),
192            UsizeWithUnderscore(dep_item_trees),
193        );
194        eprintln!("  dependency item stats: {dep_item_stats}");
195
196        // FIXME(salsa-transition): bring back stats for ParseQuery (file size)
197        // and ParseMacroExpansionQuery (macro expansion "file") size whenever we implement
198        // Salsa's memory usage tracking works with tracked functions.
199
200        // let mut total_file_size = Bytes::default();
201        // for e in ide_db::base_db::ParseQuery.in_db(db).entries::<Vec<_>>() {
202        //     total_file_size += syntax_len(db.parse(e.key).syntax_node())
203        // }
204
205        // let mut total_macro_file_size = Bytes::default();
206        // for e in hir::db::ParseMacroExpansionQuery.in_db(db).entries::<Vec<_>>() {
207        //     let val = db.parse_macro_expansion(e.key).value.0;
208        //     total_macro_file_size += syntax_len(val.syntax_node())
209        // }
210        // eprintln!("source files: {total_file_size}, macro files: {total_macro_file_size}");
211
212        eprintln!("{:<20} {}", "Item Tree Collection:", item_tree_time);
213        report_metric("item tree time", item_tree_time.time.as_millis() as u64, "ms");
214        eprintln!("  Total Statistics:");
215
216        let mut crate_def_map_sw = self.stop_watch();
217        let mut num_crates = 0;
218        let mut visited_modules = FxHashSet::default();
219        let mut visit_queue = Vec::new();
220        for &krate in &krates {
221            let module = krate.root_module(db);
222            let file_id = module.definition_source_file_id(db);
223            let file_id = file_id.original_file(db);
224
225            let source_root = db.file_source_root(file_id.file_id(db)).source_root_id(db);
226            let source_root = db.source_root(source_root).source_root(db);
227            if !source_root.is_library || self.with_deps {
228                num_crates += 1;
229                visit_queue.push(module);
230            }
231        }
232
233        if self.randomize {
234            shuffle(&mut rng, &mut visit_queue);
235        }
236
237        eprint!("    crates: {num_crates}");
238        let mut num_decls = 0;
239        let mut bodies = Vec::new();
240        let mut signatures = Vec::new();
241        let mut variants = Vec::new();
242        let mut adts = Vec::new();
243        let mut file_ids = Vec::new();
244
245        let mut num_traits = 0;
246        let mut num_macro_rules_macros = 0;
247        let mut num_proc_macros = 0;
248
249        while let Some(module) = visit_queue.pop() {
250            if visited_modules.insert(module) {
251                file_ids.extend(module.as_source_file_id(db));
252                visit_queue.extend(module.children(db));
253
254                for decl in module.declarations(db) {
255                    num_decls += 1;
256                    match decl {
257                        ModuleDef::Function(f) => bodies.push(DefWithBody::from(f)),
258                        ModuleDef::Adt(a) => {
259                            match a {
260                                Adt::Enum(e) => {
261                                    for v in e.variants(db) {
262                                        bodies.push(DefWithBody::from(v));
263                                        variants.push(Variant::EnumVariant(v));
264                                    }
265                                }
266                                Adt::Struct(it) => variants.push(Variant::Struct(it)),
267                                Adt::Union(it) => variants.push(Variant::Union(it)),
268                            }
269                            adts.push(a)
270                        }
271                        ModuleDef::Const(c) => {
272                            bodies.push(DefWithBody::from(c));
273                        }
274                        ModuleDef::Static(s) => bodies.push(DefWithBody::from(s)),
275                        ModuleDef::Trait(_) => num_traits += 1,
276                        ModuleDef::Macro(m) => match m.kind(db) {
277                            hir::MacroKind::Declarative => num_macro_rules_macros += 1,
278                            hir::MacroKind::Derive
279                            | hir::MacroKind::Attr
280                            | hir::MacroKind::ProcMacro => num_proc_macros += 1,
281                            _ => (),
282                        },
283                        _ => (),
284                    };
285                    if let Some(g) = decl.as_generic_def() {
286                        signatures.push(g);
287                    }
288                }
289
290                for impl_def in module.impl_defs(db) {
291                    signatures.push(impl_def.into());
292                    for item in impl_def.items(db) {
293                        num_decls += 1;
294                        match item {
295                            AssocItem::Function(f) => {
296                                bodies.push(DefWithBody::from(f));
297                                signatures.push(f.into())
298                            }
299                            AssocItem::Const(c) => {
300                                bodies.push(DefWithBody::from(c));
301                                signatures.push(c.into());
302                            }
303                            AssocItem::TypeAlias(t) => signatures.push(t.into()),
304                        }
305                    }
306                }
307            }
308        }
309        eprintln!(
310            ", mods: {}, decls: {num_decls}, bodies: {}, adts: {}, consts: {}, signatures: {}, variants: {}",
311            visited_modules.len(),
312            bodies.len(),
313            adts.len(),
314            bodies
315                .iter()
316                .filter(|it| matches!(it, DefWithBody::Const(_) | DefWithBody::Static(_)))
317                .count(),
318            signatures.len(),
319            variants.len()
320        );
321
322        eprintln!("  Workspace:");
323        eprintln!(
324            "    traits: {num_traits}, macro_rules macros: {num_macro_rules_macros}, proc_macros: {num_proc_macros}"
325        );
326        eprintln!(
327            "    lines of code: {}, item trees: {}",
328            UsizeWithUnderscore(workspace_loc),
329            UsizeWithUnderscore(workspace_item_trees),
330        );
331        eprintln!("    usages: {workspace_item_stats}");
332
333        eprintln!("  Dependencies:");
334        eprintln!(
335            "    lines of code: {}, item trees: {}",
336            UsizeWithUnderscore(dep_loc),
337            UsizeWithUnderscore(dep_item_trees),
338        );
339        eprintln!("    declarations: {dep_item_stats}");
340
341        let crate_def_map_time = crate_def_map_sw.elapsed();
342        eprintln!("{:<20} {}", "Item Collection:", crate_def_map_time);
343        report_metric("crate def map time", crate_def_map_time.time.as_millis() as u64, "ms");
344
345        if self.randomize {
346            shuffle(&mut rng, &mut bodies);
347        }
348
349        hir::attach_db(db, || {
350            if !self.skip_lang_items {
351                self.run_lang_items(db, &krates, verbosity);
352            }
353
354            if !self.skip_lowering {
355                self.run_body_lowering(db, &vfs, &bodies, &signatures, &variants, verbosity);
356            }
357
358            if !self.skip_inference {
359                self.run_inference(db, &vfs, &bodies, &signatures, &variants, verbosity);
360            }
361
362            if !self.skip_mir_stats {
363                self.run_mir_lowering(db, &bodies, &signatures, &variants, verbosity);
364            }
365
366            if !self.skip_data_layout {
367                self.run_data_layout(db, &adts, verbosity);
368            }
369
370            if !self.skip_const_eval {
371                self.run_const_eval(db, &bodies, &signatures, &variants, verbosity);
372            }
373        });
374
375        file_ids.sort();
376        file_ids.dedup();
377
378        if self.run_all_ide_things {
379            self.run_ide_things(host.analysis(), &file_ids, db, &vfs, verbosity);
380        }
381
382        if self.run_term_search {
383            self.run_term_search(&workspace, db, &vfs, &file_ids, verbosity);
384        }
385
386        let db = host.raw_database_mut();
387        db.trigger_lru_eviction();
388        hir::clear_tls_solver_cache();
389        unsafe { hir::collect_ty_garbage() };
390
391        let total_span = analysis_sw.elapsed();
392        eprintln!("{:<20} {total_span}", "Total:");
393        report_metric("total time", total_span.time.as_millis() as u64, "ms");
394        if let Some(instructions) = total_span.instructions {
395            report_metric("total instructions", instructions, "#instr");
396        }
397        report_metric("total memory", total_span.memory.allocated.megabytes() as u64, "MB");
398
399        if verbosity.is_verbose() {
400            print_memory_usage(host, vfs);
401        }
402
403        Ok(())
404    }
405
406    fn run_data_layout(&self, db: &RootDatabase, adts: &[hir::Adt], verbosity: Verbosity) {
407        let mut sw = self.stop_watch();
408        let mut all = 0;
409        let mut fail = 0;
410        for &a in adts {
411            let generic_params = GenericParams::of(db, a.into());
412            if generic_params.iter_type_or_consts().next().is_some()
413                || generic_params.iter_lt().next().is_some()
414            {
415                // Data types with generics don't have layout.
416                continue;
417            }
418            all += 1;
419            let Err(e) = db.layout_of_adt(
420                hir_def::AdtId::from(a),
421                GenericArgs::empty().store(),
422                hir_ty::ParamEnvAndCrate {
423                    param_env: db.trait_environment(a.into()),
424                    krate: a.krate(db).into(),
425                }
426                .store(),
427            ) else {
428                continue;
429            };
430            if verbosity.is_spammy() {
431                let full_name = full_name_of_item(db, a.module(db), a.name(db));
432                println!("Data layout for {full_name} failed due {e:?}");
433            }
434            fail += 1;
435        }
436        let data_layout_time = sw.elapsed();
437        eprintln!("{:<20} {}", "Data layouts:", data_layout_time);
438        eprintln!("Failed data layouts: {fail} ({}%)", percentage(fail, all));
439        report_metric("failed data layouts", fail, "#");
440        report_metric("data layout time", data_layout_time.time.as_millis() as u64, "ms");
441    }
442
443    fn run_const_eval(
444        &self,
445        db: &RootDatabase,
446        bodies: &[DefWithBody],
447        _signatures: &[GenericDef],
448        _variants: &[Variant],
449        verbosity: Verbosity,
450    ) {
451        let len = bodies
452            .iter()
453            .filter(|body| matches!(body, DefWithBody::Const(_) | DefWithBody::Static(_)))
454            .count();
455        let mut bar = match verbosity {
456            Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
457            _ if self.parallel || self.output.is_some() => ProgressReport::hidden(),
458            _ => ProgressReport::new(len),
459        };
460
461        let mut sw = self.stop_watch();
462        let mut all = 0;
463        let mut fail = 0;
464        for &b in bodies {
465            bar.set_message(move || {
466                format!("const eval: {}", full_name(db, || b.name(db), b.module(db)))
467            });
468            let res = match b {
469                DefWithBody::Const(c) => c.eval(db),
470                DefWithBody::Static(s) => s.eval(db),
471                _ => continue,
472            };
473            bar.inc(1);
474            all += 1;
475            let Err(error) = res else {
476                continue;
477            };
478            if verbosity.is_spammy() {
479                let full_name =
480                    full_name_of_item(db, b.module(db), b.name(db).unwrap_or(Name::missing()));
481                bar.println(format!("Const eval for {full_name} failed due {error:?}"));
482            }
483            fail += 1;
484        }
485        bar.finish_and_clear();
486        let const_eval_time = sw.elapsed();
487        eprintln!("{:<20} {}", "Const evaluation:", const_eval_time);
488        eprintln!("Failed const evals: {fail} ({}%)", percentage(fail, all));
489        report_metric("failed const evals", fail, "#");
490        report_metric("const eval time", const_eval_time.time.as_millis() as u64, "ms");
491    }
492
493    /// Invariant: `file_ids` must be sorted and deduped before passing into here
494    fn run_term_search(
495        &self,
496        ws: &ProjectWorkspace,
497        db: &RootDatabase,
498        vfs: &Vfs,
499        file_ids: &[EditionedFileId],
500        verbosity: Verbosity,
501    ) {
502        let cargo_config = CargoConfig {
503            sysroot: match self.no_sysroot {
504                true => None,
505                false => Some(RustLibSource::Discover),
506            },
507            all_targets: true,
508            ..Default::default()
509        };
510
511        let mut bar = match verbosity {
512            Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
513            _ if self.parallel || self.output.is_some() => ProgressReport::hidden(),
514            _ => ProgressReport::new(file_ids.len()),
515        };
516
517        #[derive(Debug, Default)]
518        struct Acc {
519            tail_expr_syntax_hits: u64,
520            tail_expr_no_term: u64,
521            total_tail_exprs: u64,
522            error_codes: FxHashMap<String, u32>,
523            syntax_errors: u32,
524        }
525
526        let mut acc: Acc = Default::default();
527        bar.tick();
528        let mut sw = self.stop_watch();
529
530        for &file_id in file_ids {
531            let file_id = file_id.span_file_id(db);
532            let sema = hir::Semantics::new(db);
533            let display_target = match sema.first_crate(file_id.file_id()) {
534                Some(krate) => krate.to_display_target(sema.db),
535                None => continue,
536            };
537
538            let parse = sema.parse_guess_edition(file_id.into());
539            let file_txt = db.file_text(file_id.into());
540            let path = vfs.file_path(file_id.into()).as_path().unwrap();
541            let line_endings = vfs.line_endings(file_id.into());
542
543            for node in parse.syntax().descendants() {
544                let expr = match syntax::ast::Expr::cast(node.clone()) {
545                    Some(it) => it,
546                    None => continue,
547                };
548                let block = match syntax::ast::BlockExpr::cast(expr.syntax().clone()) {
549                    Some(it) => it,
550                    None => continue,
551                };
552                let target_ty = match sema.type_of_expr(&expr) {
553                    Some(it) => it.adjusted(),
554                    None => continue, // Failed to infer type
555                };
556
557                let expected_tail = match block.tail_expr() {
558                    Some(it) => it,
559                    None => continue,
560                };
561
562                if expected_tail.is_block_like() {
563                    continue;
564                }
565
566                let range = sema.original_range(expected_tail.syntax()).range;
567                let original_text: String = db
568                    .file_text(file_id.into())
569                    .text(db)
570                    .chars()
571                    .skip(usize::from(range.start()))
572                    .take(usize::from(range.end()) - usize::from(range.start()))
573                    .collect();
574
575                let scope = match sema.scope(expected_tail.syntax()) {
576                    Some(it) => it,
577                    None => continue,
578                };
579
580                let ctx = hir::term_search::TermSearchCtx {
581                    sema: &sema,
582                    scope: &scope,
583                    goal: target_ty,
584                    config: hir::term_search::TermSearchConfig::default(),
585                };
586                let found_terms = hir::term_search::term_search(&ctx);
587
588                if found_terms.is_empty() {
589                    acc.tail_expr_no_term += 1;
590                    acc.total_tail_exprs += 1;
591                    // println!("\n{original_text}\n");
592                    continue;
593                };
594
595                fn drop_whitespace(s: &str) -> String {
596                    s.chars().filter(|c| !parser::is_rust_whitespace(*c)).collect()
597                }
598
599                let todo = syntax::ast::make::ext::expr_todo().to_string();
600                let mut formatter = |_: &hir::Type<'_>| todo.clone();
601                let mut syntax_hit_found = false;
602                for term in found_terms {
603                    let generated = term
604                        .gen_source_code(
605                            &scope,
606                            &mut formatter,
607                            FindPathConfig {
608                                prefer_no_std: false,
609                                prefer_prelude: true,
610                                prefer_absolute: false,
611                                allow_unstable: true,
612                            },
613                            display_target,
614                        )
615                        .unwrap();
616                    syntax_hit_found |=
617                        drop_whitespace(&original_text) == drop_whitespace(&generated);
618
619                    // Validate if type-checks
620                    let mut txt = file_txt.text(db).to_string();
621
622                    let edit = ide::TextEdit::replace(range, generated.clone());
623                    edit.apply(&mut txt);
624
625                    if self.validate_term_search {
626                        if line_endings == Some(vfs::LineEndings::Dos) {
627                            txt = txt.replace('\n', "\r\n");
628                        }
629                        std::fs::write(path, txt).unwrap();
630
631                        let res = ws.run_build_scripts(&cargo_config, &|_| ()).unwrap();
632                        if let Some(err) = res.error()
633                            && err.contains("error: could not compile")
634                        {
635                            if let Some(mut err_idx) = err.find("error[E") {
636                                err_idx += 7;
637                                let err_code = &err[err_idx..err_idx + 4];
638                                match err_code {
639                                    "0282" | "0283" => continue, // Byproduct of testing method
640                                    "0277" | "0308" if generated.contains(&todo) => continue, // See https://github.com/rust-lang/rust/issues/69882
641                                    // FIXME: In some rare cases `AssocItem::container_or_implemented_trait` returns `None` for trait methods.
642                                    // Generated code is valid in case traits are imported
643                                    "0599"
644                                        if err.contains(
645                                            "the following trait is implemented but not in scope",
646                                        ) =>
647                                    {
648                                        continue;
649                                    }
650                                    _ => (),
651                                }
652                                bar.println(err);
653                                bar.println(generated);
654                                acc.error_codes
655                                    .entry(err_code.to_owned())
656                                    .and_modify(|n| *n += 1)
657                                    .or_insert(1);
658                            } else {
659                                acc.syntax_errors += 1;
660                                bar.println(format!("Syntax error: \n{err}"));
661                            }
662                        }
663                    }
664                }
665
666                if syntax_hit_found {
667                    acc.tail_expr_syntax_hits += 1;
668                }
669                acc.total_tail_exprs += 1;
670
671                let msg = move || {
672                    format!(
673                        "processing: {:<50}",
674                        drop_whitespace(&original_text).chars().take(50).collect::<String>()
675                    )
676                };
677                if verbosity.is_spammy() {
678                    bar.println(msg());
679                }
680                bar.set_message(msg);
681            }
682            // Restore the original text using the detected line-ending convention.
683            // Files with mixed line endings are restored with uniform CRLF.
684            if self.validate_term_search {
685                let mut text = file_txt.text(db).to_string();
686                if line_endings == Some(vfs::LineEndings::Dos) {
687                    text = text.replace('\n', "\r\n");
688                }
689                std::fs::write(path, text).unwrap();
690            }
691
692            bar.inc(1);
693        }
694        let term_search_time = sw.elapsed();
695
696        bar.println(format!(
697            "Tail Expr syntactic hits: {}/{} ({}%)",
698            acc.tail_expr_syntax_hits,
699            acc.total_tail_exprs,
700            percentage(acc.tail_expr_syntax_hits, acc.total_tail_exprs)
701        ));
702        bar.println(format!(
703            "Tail Exprs found: {}/{} ({}%)",
704            acc.total_tail_exprs - acc.tail_expr_no_term,
705            acc.total_tail_exprs,
706            percentage(acc.total_tail_exprs - acc.tail_expr_no_term, acc.total_tail_exprs)
707        ));
708        if self.validate_term_search {
709            bar.println(format!(
710                "Tail Exprs total errors: {}, syntax errors: {}, error codes:",
711                acc.error_codes.values().sum::<u32>() + acc.syntax_errors,
712                acc.syntax_errors,
713            ));
714            for (err, count) in acc.error_codes {
715                bar.println(format!(
716                    "    E{err}: {count:>5}  (https://doc.rust-lang.org/error_codes/E{err}.html)"
717                ));
718            }
719        }
720        bar.println(format!(
721            "Term search avg time: {}ms",
722            term_search_time.time.as_millis() as u64 / acc.total_tail_exprs
723        ));
724        bar.println(format!("{:<20} {}", "Term search:", term_search_time));
725        report_metric("term search time", term_search_time.time.as_millis() as u64, "ms");
726
727        bar.finish_and_clear();
728    }
729
730    fn run_mir_lowering(
731        &self,
732        db: &RootDatabase,
733        bodies: &[DefWithBody],
734        _signatures: &[GenericDef],
735        _variants: &[Variant],
736        verbosity: Verbosity,
737    ) {
738        let mut bar = match verbosity {
739            Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
740            _ if self.parallel || self.output.is_some() => ProgressReport::hidden(),
741            _ => ProgressReport::new(bodies.len()),
742        };
743        let mut sw = self.stop_watch();
744        let mut all = 0;
745        let mut fail = 0;
746        for &body in bodies {
747            bar.set_message(move || {
748                format!("mir lowering: {}", full_name(db, || body.name(db), body.module(db)))
749            });
750            bar.inc(1);
751            if matches!(body, DefWithBody::EnumVariant(_)) {
752                continue;
753            }
754            let module = body.module(db);
755            if !self.should_process(db, || body.name(db), module) {
756                continue;
757            }
758
759            all += 1;
760            #[expect(deprecated)]
761            let Err(e) = body.run_mir_body(db) else {
762                continue;
763            };
764            if verbosity.is_spammy() {
765                let full_name = module
766                    .path_segments(db)
767                    .chain(Some(body.name(db).unwrap_or_else(Name::missing)))
768                    .map(|it| it.display(db, Edition::LATEST).to_string())
769                    .join("::");
770                bar.println(format!("Mir body for {full_name} failed due {e:?}"));
771            }
772            fail += 1;
773            bar.tick();
774        }
775        let mir_lowering_time = sw.elapsed();
776        bar.finish_and_clear();
777        eprintln!("{:<20} {}", "MIR lowering:", mir_lowering_time);
778        eprintln!("Mir failed bodies: {fail} ({}%)", percentage(fail, all));
779        report_metric("mir failed bodies", fail, "#");
780        report_metric("mir lowering time", mir_lowering_time.time.as_millis() as u64, "ms");
781    }
782
783    fn run_inference(
784        &self,
785        db: &RootDatabase,
786        vfs: &Vfs,
787        bodies: &[DefWithBody],
788        signatures: &[GenericDef],
789        _variants: &[Variant],
790        verbosity: Verbosity,
791    ) {
792        let mut bar = match verbosity {
793            Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
794            _ if self.parallel || self.output.is_some() => ProgressReport::hidden(),
795            _ => ProgressReport::new(bodies.len()),
796        };
797
798        if self.parallel {
799            let mut inference_sw = self.stop_watch();
800            let bodies = bodies
801                .iter()
802                .filter_map(|&body| body.try_into().ok())
803                .collect::<Vec<DefWithBodyId>>();
804            bodies
805                .par_iter()
806                .map_with(db.clone(), |snap, &body| {
807                    hir::attach_db(snap, || {
808                        InferenceResult::of(snap, body);
809                    });
810                })
811                .count();
812            let _signatures = signatures
813                .iter()
814                .filter_map(|&signatures| signatures.try_into().ok())
815                .collect::<Vec<GenericDefId>>();
816            // FIXME: We don't have access to the necessary types here (nor we should have).
817            // signatures
818            //     .par_iter()
819            //     .map_with(db.clone(), |snap, &signatures| {
820            //         InferenceResult::of(snap, signatures);
821            //     })
822            //     .count();
823            // let variants = variants.iter().copied().map(Into::into).collect::<Vec<VariantId>>();
824            // variants
825            //     .par_iter()
826            //     .map_with(db.clone(), |snap, &variants| {
827            //         InferenceResult::of(snap, variants);
828            //     })
829            //     .count();
830            eprintln!("{:<20} {}", "Parallel Inference:", inference_sw.elapsed());
831        }
832
833        let mut inference_sw = self.stop_watch();
834        bar.tick();
835        let mut num_exprs = 0;
836        let mut num_exprs_unknown = 0;
837        let mut num_exprs_partially_unknown = 0;
838        let mut num_expr_type_mismatches = 0;
839        let mut num_pats = 0;
840        let mut num_pats_unknown = 0;
841        let mut num_pats_partially_unknown = 0;
842        let mut num_pat_type_mismatches = 0;
843        let mut panics = 0;
844        for &body_id in bodies {
845            let Ok(body_def_id) = body_id.try_into() else { continue };
846            let name = body_id.name(db).unwrap_or_else(Name::missing);
847            let module = body_id.module(db);
848            let display_target = module.krate(db).to_display_target(db);
849            if let Some(only_name) = self.only.as_deref()
850                && name.display(db, Edition::LATEST).to_string() != only_name
851                && full_name(db, || body_id.name(db), module) != only_name
852            {
853                continue;
854            }
855            let msg = move || {
856                if verbosity.is_verbose() {
857                    let source = match body_id {
858                        DefWithBody::Function(it) => it.source(db).map(|it| it.syntax().cloned()),
859                        DefWithBody::Static(it) => it.source(db).map(|it| it.syntax().cloned()),
860                        DefWithBody::Const(it) => it.source(db).map(|it| it.syntax().cloned()),
861                        DefWithBody::EnumVariant(it) => {
862                            it.source(db).map(|it| it.syntax().cloned())
863                        }
864                    };
865                    if let Some(src) = source {
866                        let original_file = src.file_id.original_file(db);
867                        let path = vfs.file_path(original_file.file_id(db));
868                        let syntax_range = src.text_range();
869                        format!(
870                            "processing: {} ({} {:?})",
871                            full_name(db, || body_id.name(db), module),
872                            path,
873                            syntax_range
874                        )
875                    } else {
876                        format!("processing: {}", full_name(db, || body_id.name(db), module))
877                    }
878                } else {
879                    format!("processing: {}", full_name(db, || body_id.name(db), module))
880                }
881            };
882            if verbosity.is_spammy() {
883                bar.println(msg());
884            }
885            bar.set_message(msg);
886            let body = Body::of(db, body_def_id);
887            let inference_result =
888                catch_unwind(AssertUnwindSafe(|| InferenceResult::of(db, body_def_id)));
889            let inference_result = match inference_result {
890                Ok(inference_result) => inference_result,
891                Err(p) => {
892                    if let Some(s) = p.downcast_ref::<&str>() {
893                        eprintln!(
894                            "infer panicked for {}: {}",
895                            full_name(db, || body_id.name(db), module),
896                            s
897                        );
898                    } else if let Some(s) = p.downcast_ref::<String>() {
899                        eprintln!(
900                            "infer panicked for {}: {}",
901                            full_name(db, || body_id.name(db), module),
902                            s
903                        );
904                    } else {
905                        eprintln!(
906                            "infer panicked for {}",
907                            full_name(db, || body_id.name(db), module)
908                        );
909                    }
910                    panics += 1;
911                    bar.inc(1);
912                    continue;
913                }
914            };
915            // This query is LRU'd, so actually calling it will skew the timing results.
916            let sm = || &Body::with_source_map(db, body_def_id).1;
917
918            // region:expressions
919            let (previous_exprs, previous_unknown, previous_partially_unknown) =
920                (num_exprs, num_exprs_unknown, num_exprs_partially_unknown);
921            let type_mismatch_for_node = LazyCell::new(|| {
922                inference_result
923                    .diagnostics()
924                    .iter()
925                    .filter_map(|diag| match diag {
926                        hir_ty::InferenceDiagnostic::TypeMismatch { node, expected, found } => {
927                            Some((*node, (expected.as_ref(), found.as_ref())))
928                        }
929                        _ => None,
930                    })
931                    .collect::<FxHashMap<_, _>>()
932            });
933            for (expr_id, _) in body.exprs() {
934                let ty = inference_result.expr_ty(expr_id);
935                num_exprs += 1;
936                let unknown_or_partial = if ty.is_ty_error() {
937                    num_exprs_unknown += 1;
938                    if verbosity.is_spammy() {
939                        if let Some((path, start, end)) = expr_syntax_range(db, vfs, sm(), expr_id)
940                        {
941                            bar.println(format!(
942                                "{} {}:{}-{}:{}: Unknown type",
943                                path,
944                                start.line + 1,
945                                start.col,
946                                end.line + 1,
947                                end.col,
948                            ));
949                        } else {
950                            bar.println(format!(
951                                "{}: Unknown type",
952                                name.display(db, Edition::LATEST)
953                            ));
954                        }
955                    }
956                    true
957                } else {
958                    let is_partially_unknown = ty.references_non_lt_error();
959                    if is_partially_unknown {
960                        num_exprs_partially_unknown += 1;
961                    }
962                    is_partially_unknown
963                };
964                if self.only.is_some() && verbosity.is_spammy() {
965                    // in super-verbose mode for just one function, we print every single expression
966                    if let Some((_, start, end)) = expr_syntax_range(db, vfs, sm(), expr_id) {
967                        bar.println(format!(
968                            "{}:{}-{}:{}: {}",
969                            start.line + 1,
970                            start.col,
971                            end.line + 1,
972                            end.col,
973                            ty.display(db, display_target)
974                        ));
975                    } else {
976                        bar.println(format!(
977                            "unknown location: {}",
978                            ty.display(db, display_target)
979                        ));
980                    }
981                }
982                if unknown_or_partial && self.output == Some(OutputFormat::Csv) {
983                    println!(
984                        r#"{},type,"{}""#,
985                        location_csv_expr(db, vfs, sm(), expr_id),
986                        ty.display(db, display_target)
987                    );
988                }
989                if inference_result.expr_has_type_mismatch(expr_id) {
990                    num_expr_type_mismatches += 1;
991                    if verbosity.is_verbose() {
992                        let (expected, actual) = type_mismatch_for_node[&expr_id.into()];
993                        if let Some((path, start, end)) = expr_syntax_range(db, vfs, sm(), expr_id)
994                        {
995                            bar.println(format!(
996                                "{} {}:{}-{}:{}: Expected {}, got {}",
997                                path,
998                                start.line + 1,
999                                start.col,
1000                                end.line + 1,
1001                                end.col,
1002                                expected.display(db, display_target),
1003                                actual.display(db, display_target)
1004                            ));
1005                        } else {
1006                            bar.println(format!(
1007                                "{}: Expected {}, got {}",
1008                                name.display(db, Edition::LATEST),
1009                                expected.display(db, display_target),
1010                                actual.display(db, display_target)
1011                            ));
1012                        }
1013                    }
1014                    if self.output == Some(OutputFormat::Csv) {
1015                        let (expected, actual) = type_mismatch_for_node[&expr_id.into()];
1016                        println!(
1017                            r#"{},mismatch,"{}","{}""#,
1018                            location_csv_expr(db, vfs, sm(), expr_id),
1019                            expected.display(db, display_target),
1020                            actual.display(db, display_target)
1021                        );
1022                    }
1023                }
1024            }
1025            if verbosity.is_spammy() {
1026                bar.println(format!(
1027                    "In {}: {} exprs, {} unknown, {} partial",
1028                    full_name(db, || body_id.name(db), module),
1029                    num_exprs - previous_exprs,
1030                    num_exprs_unknown - previous_unknown,
1031                    num_exprs_partially_unknown - previous_partially_unknown
1032                ));
1033            }
1034            // endregion:expressions
1035
1036            // region:patterns
1037            let (previous_pats, previous_unknown, previous_partially_unknown) =
1038                (num_pats, num_pats_unknown, num_pats_partially_unknown);
1039            for (pat_id, _) in body.pats() {
1040                let ty = inference_result.pat_ty(pat_id);
1041                num_pats += 1;
1042                let unknown_or_partial = if ty.is_ty_error() {
1043                    num_pats_unknown += 1;
1044                    if verbosity.is_spammy() {
1045                        if let Some((path, start, end)) = pat_syntax_range(db, vfs, sm(), pat_id) {
1046                            bar.println(format!(
1047                                "{} {}:{}-{}:{}: Unknown type",
1048                                path,
1049                                start.line + 1,
1050                                start.col,
1051                                end.line + 1,
1052                                end.col,
1053                            ));
1054                        } else {
1055                            bar.println(format!(
1056                                "{}: Unknown type",
1057                                name.display(db, Edition::LATEST)
1058                            ));
1059                        }
1060                    }
1061                    true
1062                } else {
1063                    let is_partially_unknown = ty.references_non_lt_error();
1064                    if is_partially_unknown {
1065                        num_pats_partially_unknown += 1;
1066                    }
1067                    is_partially_unknown
1068                };
1069                if self.only.is_some() && verbosity.is_spammy() {
1070                    // in super-verbose mode for just one function, we print every single pattern
1071                    if let Some((_, start, end)) = pat_syntax_range(db, vfs, sm(), pat_id) {
1072                        bar.println(format!(
1073                            "{}:{}-{}:{}: {}",
1074                            start.line + 1,
1075                            start.col,
1076                            end.line + 1,
1077                            end.col,
1078                            ty.display(db, display_target)
1079                        ));
1080                    } else {
1081                        bar.println(format!(
1082                            "unknown location: {}",
1083                            ty.display(db, display_target)
1084                        ));
1085                    }
1086                }
1087                if unknown_or_partial && self.output == Some(OutputFormat::Csv) {
1088                    println!(
1089                        r#"{},type,"{}""#,
1090                        location_csv_pat(db, vfs, sm(), pat_id),
1091                        ty.display(db, display_target)
1092                    );
1093                }
1094                if inference_result.pat_has_type_mismatch(pat_id) {
1095                    num_pat_type_mismatches += 1;
1096                    if verbosity.is_verbose() {
1097                        let (expected, actual) = type_mismatch_for_node[&pat_id.into()];
1098                        if let Some((path, start, end)) = pat_syntax_range(db, vfs, sm(), pat_id) {
1099                            bar.println(format!(
1100                                "{} {}:{}-{}:{}: Expected {}, got {}",
1101                                path,
1102                                start.line + 1,
1103                                start.col,
1104                                end.line + 1,
1105                                end.col,
1106                                expected.display(db, display_target),
1107                                actual.display(db, display_target)
1108                            ));
1109                        } else {
1110                            bar.println(format!(
1111                                "{}: Expected {}, got {}",
1112                                name.display(db, Edition::LATEST),
1113                                expected.display(db, display_target),
1114                                actual.display(db, display_target)
1115                            ));
1116                        }
1117                    }
1118                    if self.output == Some(OutputFormat::Csv) {
1119                        let (expected, actual) = type_mismatch_for_node[&pat_id.into()];
1120                        println!(
1121                            r#"{},mismatch,"{}","{}""#,
1122                            location_csv_pat(db, vfs, sm(), pat_id),
1123                            expected.display(db, display_target),
1124                            actual.display(db, display_target)
1125                        );
1126                    }
1127                }
1128            }
1129            if verbosity.is_spammy() {
1130                bar.println(format!(
1131                    "In {}: {} pats, {} unknown, {} partial",
1132                    full_name(db, || body_id.name(db), module),
1133                    num_pats - previous_pats,
1134                    num_pats_unknown - previous_unknown,
1135                    num_pats_partially_unknown - previous_partially_unknown
1136                ));
1137            }
1138            // endregion:patterns
1139            bar.inc(1);
1140        }
1141
1142        bar.finish_and_clear();
1143        let inference_time = inference_sw.elapsed();
1144        eprintln!(
1145            "  exprs: {}, ??ty: {} ({}%), ?ty: {} ({}%), !ty: {}",
1146            num_exprs,
1147            num_exprs_unknown,
1148            percentage(num_exprs_unknown, num_exprs),
1149            num_exprs_partially_unknown,
1150            percentage(num_exprs_partially_unknown, num_exprs),
1151            num_expr_type_mismatches
1152        );
1153        eprintln!(
1154            "  pats: {}, ??ty: {} ({}%), ?ty: {} ({}%), !ty: {}",
1155            num_pats,
1156            num_pats_unknown,
1157            percentage(num_pats_unknown, num_pats),
1158            num_pats_partially_unknown,
1159            percentage(num_pats_partially_unknown, num_pats),
1160            num_pat_type_mismatches
1161        );
1162        eprintln!("  panics: {panics}");
1163        eprintln!("{:<20} {}", "Inference:", inference_time);
1164        report_metric("unknown type", num_exprs_unknown, "#");
1165        report_metric("type mismatches", num_expr_type_mismatches, "#");
1166        report_metric("pattern unknown type", num_pats_unknown, "#");
1167        report_metric("pattern type mismatches", num_pat_type_mismatches, "#");
1168        report_metric("inference time", inference_time.time.as_millis() as u64, "ms");
1169    }
1170
1171    fn run_body_lowering(
1172        &self,
1173        db: &RootDatabase,
1174        vfs: &Vfs,
1175        bodies: &[DefWithBody],
1176        signatures: &[GenericDef],
1177        variants: &[Variant],
1178        verbosity: Verbosity,
1179    ) {
1180        let mut bar = match verbosity {
1181            Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
1182            _ if self.output.is_some() => ProgressReport::hidden(),
1183            _ => ProgressReport::new(bodies.len() + signatures.len() + variants.len()),
1184        };
1185
1186        let mut sw = self.stop_watch();
1187        bar.tick();
1188        for &signature in signatures {
1189            let Ok(signature_id) = signature.try_into() else { continue };
1190            let module = signature.module(db);
1191            if !self.should_process(db, || signature.name(db), module) {
1192                continue;
1193            }
1194            let msg = move || {
1195                if verbosity.is_verbose() {
1196                    let source = match signature {
1197                        GenericDef::Function(it) => it.source(db).map(|it| it.syntax().cloned()),
1198                        GenericDef::Static(it) => it.source(db).map(|it| it.syntax().cloned()),
1199                        GenericDef::Const(it) => it.source(db).map(|it| it.syntax().cloned()),
1200                        GenericDef::Adt(adt) => adt.source(db).map(|it| it.syntax().cloned()),
1201                        GenericDef::Trait(it) => it.source(db).map(|it| it.syntax().cloned()),
1202                        GenericDef::TypeAlias(type_alias) => {
1203                            type_alias.source(db).map(|it| it.syntax().cloned())
1204                        }
1205                        GenericDef::Impl(it) => it.source(db).map(|it| it.syntax().cloned()),
1206                    };
1207                    if let Some(src) = source {
1208                        let original_file = src.file_id.original_file(db);
1209                        let path = vfs.file_path(original_file.file_id(db));
1210                        let syntax_range = src.text_range();
1211                        format!(
1212                            "processing: {} ({} {:?})",
1213                            full_name(db, || signature.name(db), module),
1214                            path,
1215                            syntax_range
1216                        )
1217                    } else {
1218                        format!("processing: {}", full_name(db, || signature.name(db), module))
1219                    }
1220                } else {
1221                    format!("processing: {}", full_name(db, || signature.name(db), module))
1222                }
1223            };
1224            if verbosity.is_spammy() {
1225                bar.println(msg());
1226            }
1227            bar.set_message(msg);
1228            ExpressionStore::of(db, ExpressionStoreOwnerId::Signature(signature_id));
1229            bar.inc(1);
1230        }
1231
1232        for &variant in variants {
1233            let variant_id = variant.into();
1234            let module = variant.module(db);
1235            if !self.should_process(db, || Some(variant.name(db)), module) {
1236                continue;
1237            }
1238            let msg = move || {
1239                if verbosity.is_verbose() {
1240                    let source = match variant {
1241                        Variant::EnumVariant(it) => it.source(db).map(|it| it.syntax().cloned()),
1242                        Variant::Struct(it) => it.source(db).map(|it| it.syntax().cloned()),
1243                        Variant::Union(it) => it.source(db).map(|it| it.syntax().cloned()),
1244                    };
1245                    if let Some(src) = source {
1246                        let original_file = src.file_id.original_file(db);
1247                        let path = vfs.file_path(original_file.file_id(db));
1248                        let syntax_range = src.text_range();
1249                        format!(
1250                            "processing: {} ({} {:?})",
1251                            full_name(db, || Some(variant.name(db)), module),
1252                            path,
1253                            syntax_range
1254                        )
1255                    } else {
1256                        format!("processing: {}", full_name(db, || Some(variant.name(db)), module))
1257                    }
1258                } else {
1259                    format!("processing: {}", full_name(db, || Some(variant.name(db)), module))
1260                }
1261            };
1262            if verbosity.is_spammy() {
1263                bar.println(msg());
1264            }
1265            bar.set_message(msg);
1266            ExpressionStore::of(db, ExpressionStoreOwnerId::VariantFields(variant_id));
1267            bar.inc(1);
1268        }
1269
1270        for &body_id in bodies {
1271            let Ok(body_def_id) = body_id.try_into() else { continue };
1272            let module = body_id.module(db);
1273            if !self.should_process(db, || body_id.name(db), module) {
1274                continue;
1275            }
1276            let msg = move || {
1277                if verbosity.is_verbose() {
1278                    let source = match body_id {
1279                        DefWithBody::Function(it) => it.source(db).map(|it| it.syntax().cloned()),
1280                        DefWithBody::Static(it) => it.source(db).map(|it| it.syntax().cloned()),
1281                        DefWithBody::Const(it) => it.source(db).map(|it| it.syntax().cloned()),
1282                        DefWithBody::EnumVariant(it) => {
1283                            it.source(db).map(|it| it.syntax().cloned())
1284                        }
1285                    };
1286                    if let Some(src) = source {
1287                        let original_file = src.file_id.original_file(db);
1288                        let path = vfs.file_path(original_file.file_id(db));
1289                        let syntax_range = src.text_range();
1290                        format!(
1291                            "processing: {} ({} {:?})",
1292                            full_name(db, || body_id.name(db), module),
1293                            path,
1294                            syntax_range
1295                        )
1296                    } else {
1297                        format!("processing: {}", full_name(db, || body_id.name(db), module))
1298                    }
1299                } else {
1300                    format!("processing: {}", full_name(db, || body_id.name(db), module))
1301                }
1302            };
1303            if verbosity.is_spammy() {
1304                bar.println(msg());
1305            }
1306            bar.set_message(msg);
1307            Body::of(db, body_def_id);
1308            bar.inc(1);
1309        }
1310
1311        bar.finish_and_clear();
1312        let body_lowering_time = sw.elapsed();
1313        eprintln!("{:<20} {}", "Expression Store Lowering:", body_lowering_time);
1314        report_metric("body lowering time", body_lowering_time.time.as_millis() as u64, "ms");
1315    }
1316
1317    fn run_lang_items(&self, db: &RootDatabase, crates: &[Crate], verbosity: Verbosity) {
1318        let mut bar = match verbosity {
1319            Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
1320            _ if self.output.is_some() => ProgressReport::hidden(),
1321            _ => ProgressReport::new(crates.len()),
1322        };
1323
1324        let mut sw = self.stop_watch();
1325        bar.tick();
1326        for &krate in crates {
1327            crate_lang_items(db, krate.into());
1328            bar.inc(1);
1329        }
1330
1331        bar.finish_and_clear();
1332        let time = sw.elapsed();
1333        eprintln!("{:<20} {}", "Crate lang items:", time);
1334        report_metric("crate lang items time", time.time.as_millis() as u64, "ms");
1335    }
1336
1337    /// Invariant: `file_ids` must be sorted and deduped before passing into here
1338    fn run_ide_things(
1339        &self,
1340        analysis: Analysis,
1341        file_ids: &[EditionedFileId],
1342        db: &RootDatabase,
1343        vfs: &Vfs,
1344        verbosity: Verbosity,
1345    ) {
1346        let len = file_ids.len();
1347        let create_bar = || match verbosity {
1348            Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
1349            _ if self.parallel || self.output.is_some() => ProgressReport::hidden(),
1350            _ => ProgressReport::new(len),
1351        };
1352
1353        let mut sw = self.stop_watch();
1354
1355        let mut bar = create_bar();
1356        for &file_id in file_ids {
1357            let msg = format!("diagnostics: {}", vfs.file_path(file_id.file_id(db)));
1358            bar.set_message(move || msg.clone());
1359            _ = analysis.full_diagnostics(
1360                &DiagnosticsConfig {
1361                    enabled: true,
1362                    proc_macros_enabled: true,
1363                    proc_attr_macros_enabled: true,
1364                    disable_experimental: false,
1365                    disabled: Default::default(),
1366                    expr_fill_default: Default::default(),
1367                    snippet_cap: SnippetCap::new(true),
1368                    insert_use: ide_db::imports::insert_use::InsertUseConfig {
1369                        granularity: ide_db::imports::insert_use::ImportGranularity::Crate,
1370                        enforce_granularity: true,
1371                        prefix_kind: hir::PrefixKind::ByCrate,
1372                        group: true,
1373                        skip_glob_imports: true,
1374                    },
1375                    prefer_no_std: false,
1376                    prefer_prelude: true,
1377                    prefer_absolute: false,
1378                    style_lints: false,
1379                    term_search_fuel: 400,
1380                    show_rename_conflicts: true,
1381                },
1382                ide::AssistResolveStrategy::All,
1383                analysis.editioned_file_id_to_vfs(file_id),
1384            );
1385            bar.inc(1);
1386        }
1387        bar.finish_and_clear();
1388
1389        let mut bar = create_bar();
1390        for &file_id in file_ids {
1391            let msg = format!("inlay hints: {}", vfs.file_path(file_id.file_id(db)));
1392            bar.set_message(move || msg.clone());
1393            _ = analysis.inlay_hints(
1394                &InlayHintsConfig {
1395                    render_colons: false,
1396                    type_hints: true,
1397                    type_hints_placement: ide::TypeHintsPlacement::Inline,
1398                    sized_bound: false,
1399                    discriminant_hints: ide::DiscriminantHints::Always,
1400                    parameter_hints: true,
1401                    parameter_hints_for_missing_arguments: false,
1402                    generic_parameter_hints: ide::GenericParameterHints {
1403                        type_hints: true,
1404                        lifetime_hints: true,
1405                        const_hints: true,
1406                    },
1407                    chaining_hints: true,
1408                    adjustment_hints: ide::AdjustmentHints::Always,
1409                    adjustment_hints_disable_reborrows: true,
1410                    adjustment_hints_mode: ide::AdjustmentHintsMode::Postfix,
1411                    adjustment_hints_hide_outside_unsafe: false,
1412                    closure_return_type_hints: ide::ClosureReturnTypeHints::Always,
1413                    closure_capture_hints: true,
1414                    binding_mode_hints: true,
1415                    implicit_drop_hints: ide::ImplicitDropHints::Always,
1416                    implied_dyn_trait_hints: true,
1417                    lifetime_elision_hints: ide::LifetimeElisionHints::Always,
1418                    param_names_for_lifetime_elision_hints: true,
1419                    hide_inferred_type_hints: false,
1420                    hide_named_constructor_hints: false,
1421                    hide_closure_initialization_hints: false,
1422                    hide_closure_parameter_hints: false,
1423                    closure_style: hir::ClosureStyle::ImplFn,
1424                    max_length: Some(25),
1425                    closing_brace_hints_min_lines: Some(20),
1426                    fields_to_resolve: InlayFieldsToResolve::empty(),
1427                    range_exclusive_hints: true,
1428                    ra_fixture: RaFixtureConfig::default(),
1429                },
1430                analysis.editioned_file_id_to_vfs(file_id),
1431                None,
1432            );
1433            bar.inc(1);
1434        }
1435        bar.finish_and_clear();
1436
1437        let mut bar = create_bar();
1438        let annotation_config = AnnotationConfig {
1439            binary_target: true,
1440            annotate_runnables: true,
1441            annotate_impls: true,
1442            annotate_references: false,
1443            annotate_method_references: false,
1444            annotate_enum_variant_references: false,
1445            references_exclude_imports: false,
1446            references_exclude_tests: false,
1447            location: ide::AnnotationLocation::AboveName,
1448            filter_adjacent_derive_implementations: false,
1449            ra_fixture: RaFixtureConfig::default(),
1450        };
1451        for &file_id in file_ids {
1452            let msg = format!("annotations: {}", vfs.file_path(file_id.file_id(db)));
1453            bar.set_message(move || msg.clone());
1454            analysis
1455                .annotations(&annotation_config, analysis.editioned_file_id_to_vfs(file_id))
1456                .unwrap()
1457                .into_iter()
1458                .for_each(|annotation| {
1459                    _ = analysis.resolve_annotation(&annotation_config, annotation);
1460                });
1461            bar.inc(1);
1462        }
1463        bar.finish_and_clear();
1464
1465        let ide_time = sw.elapsed();
1466        eprintln!("{:<20} {} ({} files)", "IDE:", ide_time, file_ids.len());
1467    }
1468
1469    fn should_process(
1470        &self,
1471        db: &RootDatabase,
1472        name_fn: impl Fn() -> Option<Name>,
1473        module: hir::Module,
1474    ) -> bool {
1475        if let Some(only_name) = self.only.as_deref() {
1476            let name = name_fn().unwrap_or_else(Name::missing);
1477
1478            if name.display(db, Edition::LATEST).to_string() != only_name
1479                && full_name(db, name_fn, module) != only_name
1480            {
1481                return false;
1482            }
1483        }
1484        true
1485    }
1486
1487    fn stop_watch(&self) -> StopWatch {
1488        StopWatch::start()
1489    }
1490}
1491
1492fn full_name(db: &RootDatabase, name: impl Fn() -> Option<Name>, module: hir::Module) -> String {
1493    module
1494        .krate(db)
1495        .display_name(db)
1496        .map(|it| it.canonical_name().as_str().to_owned())
1497        .into_iter()
1498        .chain(
1499            module
1500                .path_segments(db)
1501                .chain(Some(name().unwrap_or_else(Name::missing)))
1502                .map(|it| it.display(db, Edition::LATEST).to_string()),
1503        )
1504        .join("::")
1505}
1506
1507fn location_csv_expr(db: &RootDatabase, vfs: &Vfs, sm: &BodySourceMap, expr_id: ExprId) -> String {
1508    let src = match sm.expr_syntax(expr_id) {
1509        Ok(s) => s,
1510        Err(SyntheticSyntax) => return "synthetic,,".to_owned(),
1511    };
1512    let root = src.file_id.parse_or_expand(db);
1513    let node = src.map(|e| e.to_node(&root).syntax().clone());
1514    let original_range = node.as_ref().original_file_range_rooted(db);
1515    let path = vfs.file_path(original_range.file_id.file_id(db));
1516    let line_index = line_index(db, original_range.file_id.file_id(db));
1517    let text_range = original_range.range;
1518    let (start, end) =
1519        (line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
1520    format!("{path},{}:{},{}:{}", start.line + 1, start.col, end.line + 1, end.col)
1521}
1522
1523fn location_csv_pat(db: &RootDatabase, vfs: &Vfs, sm: &BodySourceMap, pat_id: PatId) -> String {
1524    let src = match sm.pat_syntax(pat_id) {
1525        Ok(s) => s,
1526        Err(SyntheticSyntax) => return "synthetic,,".to_owned(),
1527    };
1528    let root = src.file_id.parse_or_expand(db);
1529    let node = src.map(|e| e.to_node(&root).syntax().clone());
1530    let original_range = node.as_ref().original_file_range_rooted(db);
1531    let path = vfs.file_path(original_range.file_id.file_id(db));
1532    let line_index = line_index(db, original_range.file_id.file_id(db));
1533    let text_range = original_range.range;
1534    let (start, end) =
1535        (line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
1536    format!("{path},{}:{},{}:{}", start.line + 1, start.col, end.line + 1, end.col)
1537}
1538
1539fn expr_syntax_range<'a>(
1540    db: &RootDatabase,
1541    vfs: &'a Vfs,
1542    sm: &BodySourceMap,
1543    expr_id: ExprId,
1544) -> Option<(&'a VfsPath, LineCol, LineCol)> {
1545    let src = sm.expr_syntax(expr_id);
1546    if let Ok(src) = src {
1547        let root = src.file_id.parse_or_expand(db);
1548        let node = src.map(|e| e.to_node(&root).syntax().clone());
1549        let original_range = node.as_ref().original_file_range_rooted(db);
1550        let path = vfs.file_path(original_range.file_id.file_id(db));
1551        let line_index = line_index(db, original_range.file_id.file_id(db));
1552        let text_range = original_range.range;
1553        let (start, end) =
1554            (line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
1555        Some((path, start, end))
1556    } else {
1557        None
1558    }
1559}
1560fn pat_syntax_range<'a>(
1561    db: &RootDatabase,
1562    vfs: &'a Vfs,
1563    sm: &BodySourceMap,
1564    pat_id: PatId,
1565) -> Option<(&'a VfsPath, LineCol, LineCol)> {
1566    let src = sm.pat_syntax(pat_id);
1567    if let Ok(src) = src {
1568        let root = src.file_id.parse_or_expand(db);
1569        let node = src.map(|e| e.to_node(&root).syntax().clone());
1570        let original_range = node.as_ref().original_file_range_rooted(db);
1571        let path = vfs.file_path(original_range.file_id.file_id(db));
1572        let line_index = line_index(db, original_range.file_id.file_id(db));
1573        let text_range = original_range.range;
1574        let (start, end) =
1575            (line_index.line_col(text_range.start()), line_index.line_col(text_range.end()));
1576        Some((path, start, end))
1577    } else {
1578        None
1579    }
1580}
1581
1582fn shuffle<T>(rng: &mut Rand32, slice: &mut [T]) {
1583    for i in 0..slice.len() {
1584        randomize_first(rng, &mut slice[i..]);
1585    }
1586
1587    fn randomize_first<T>(rng: &mut Rand32, slice: &mut [T]) {
1588        assert!(!slice.is_empty());
1589        let idx = rng.rand_range(0..slice.len() as u32) as usize;
1590        slice.swap(0, idx);
1591    }
1592}
1593
1594fn percentage(n: u64, total: u64) -> u64 {
1595    (n * 100).checked_div(total).unwrap_or(100)
1596}
1597
1598#[derive(Default, Debug, Eq, PartialEq)]
1599struct UsizeWithUnderscore(usize);
1600
1601impl fmt::Display for UsizeWithUnderscore {
1602    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1603        let num_str = self.0.to_string();
1604
1605        if num_str.len() <= 3 {
1606            return write!(f, "{num_str}");
1607        }
1608
1609        let mut result = String::new();
1610
1611        for (count, ch) in num_str.chars().rev().enumerate() {
1612            if count > 0 && count % 3 == 0 {
1613                result.push('_');
1614            }
1615            result.push(ch);
1616        }
1617
1618        let result = result.chars().rev().collect::<String>();
1619        write!(f, "{result}")
1620    }
1621}
1622
1623impl std::ops::AddAssign for UsizeWithUnderscore {
1624    fn add_assign(&mut self, other: UsizeWithUnderscore) {
1625        self.0 += other.0;
1626    }
1627}
1628
1629#[derive(Default, Debug, Eq, PartialEq)]
1630struct PrettyItemStats {
1631    traits: UsizeWithUnderscore,
1632    impls: UsizeWithUnderscore,
1633    mods: UsizeWithUnderscore,
1634    macro_calls: UsizeWithUnderscore,
1635    macro_rules: UsizeWithUnderscore,
1636}
1637
1638impl From<hir_def::item_tree::ItemTreeDataStats> for PrettyItemStats {
1639    fn from(value: hir_def::item_tree::ItemTreeDataStats) -> Self {
1640        Self {
1641            traits: UsizeWithUnderscore(value.traits),
1642            impls: UsizeWithUnderscore(value.impls),
1643            mods: UsizeWithUnderscore(value.mods),
1644            macro_calls: UsizeWithUnderscore(value.macro_calls),
1645            macro_rules: UsizeWithUnderscore(value.macro_rules),
1646        }
1647    }
1648}
1649
1650impl AddAssign for PrettyItemStats {
1651    fn add_assign(&mut self, rhs: Self) {
1652        self.traits += rhs.traits;
1653        self.impls += rhs.impls;
1654        self.mods += rhs.mods;
1655        self.macro_calls += rhs.macro_calls;
1656        self.macro_rules += rhs.macro_rules;
1657    }
1658}
1659
1660impl fmt::Display for PrettyItemStats {
1661    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1662        write!(
1663            f,
1664            "traits: {}, impl: {}, mods: {}, macro calls: {}, macro rules: {}",
1665            self.traits, self.impls, self.mods, self.macro_calls, self.macro_rules
1666        )
1667    }
1668}
1669
1670// FIXME(salsa-transition): bring this back whenever we implement
1671// Salsa's memory usage tracking to work with tracked functions.
1672// fn syntax_len(node: SyntaxNode) -> usize {
1673//     // Macro expanded code doesn't contain whitespace, so erase *all* whitespace
1674//     // to make macro and non-macro code comparable.
1675//     drop_whitespace(&node.to_string()).len()
1676// }