rust_analyzer/cli/
diagnostics.rs

1//! Analyze all modules in a project for diagnostics. Exits with a non-zero
2//! status code if any errors are found.
3
4use project_model::{CargoConfig, RustLibSource};
5use rustc_hash::FxHashSet;
6
7use hir::{Crate, Module, db::HirDatabase, sym};
8use ide::{AnalysisHost, AssistResolveStrategy, Diagnostic, DiagnosticsConfig, Severity};
9use ide_db::{LineIndexDatabase, base_db::SourceDatabase};
10use load_cargo::{LoadCargoConfig, ProcMacroServerChoice, load_workspace_at};
11
12use crate::cli::flags;
13
14impl flags::Diagnostics {
15    pub fn run(self) -> anyhow::Result<()> {
16        const STACK_SIZE: usize = 1024 * 1024 * 8;
17
18        let handle = stdx::thread::Builder::new(
19            stdx::thread::ThreadIntent::LatencySensitive,
20            "BIG_STACK_THREAD",
21        )
22        .stack_size(STACK_SIZE)
23        .spawn(|| self.run_())
24        .unwrap();
25
26        handle.join()
27    }
28    fn run_(self) -> anyhow::Result<()> {
29        let cargo_config = CargoConfig {
30            sysroot: Some(RustLibSource::Discover),
31            all_targets: true,
32            ..Default::default()
33        };
34        let with_proc_macro_server = if let Some(p) = &self.proc_macro_srv {
35            let path = vfs::AbsPathBuf::assert_utf8(std::env::current_dir()?.join(p));
36            ProcMacroServerChoice::Explicit(path)
37        } else {
38            ProcMacroServerChoice::Sysroot
39        };
40        let load_cargo_config = LoadCargoConfig {
41            load_out_dirs_from_check: !self.disable_build_scripts,
42            with_proc_macro_server,
43            prefill_caches: false,
44        };
45        let (db, _vfs, _proc_macro) =
46            load_workspace_at(&self.path, &cargo_config, &load_cargo_config, &|_| {})?;
47        let host = AnalysisHost::with_database(db);
48        let db = host.raw_database();
49        let analysis = host.analysis();
50
51        let mut found_error = false;
52        let mut visited_files = FxHashSet::default();
53
54        let work = all_modules(db).into_iter().filter(|module| {
55            let file_id = module.definition_source_file_id(db).original_file(db);
56            let source_root = db.file_source_root(file_id.file_id(db)).source_root_id(db);
57            let source_root = db.source_root(source_root).source_root(db);
58            !source_root.is_library
59        });
60
61        for module in work {
62            let file_id = module.definition_source_file_id(db).original_file(db);
63            if !visited_files.contains(&file_id) {
64                let crate_name =
65                    module.krate().display_name(db).as_deref().unwrap_or(&sym::unknown).to_owned();
66                println!(
67                    "processing crate: {crate_name}, module: {}",
68                    _vfs.file_path(file_id.file_id(db))
69                );
70                for diagnostic in analysis
71                    .full_diagnostics(
72                        &DiagnosticsConfig::test_sample(),
73                        AssistResolveStrategy::None,
74                        file_id.file_id(db),
75                    )
76                    .unwrap()
77                {
78                    if matches!(diagnostic.severity, Severity::Error) {
79                        found_error = true;
80                    }
81
82                    let Diagnostic { code, message, range, severity, .. } = diagnostic;
83                    let line_index = db.line_index(range.file_id);
84                    let start = line_index.line_col(range.range.start());
85                    let end = line_index.line_col(range.range.end());
86                    println!("{severity:?} {code:?} from {start:?} to {end:?}: {message}");
87                }
88
89                visited_files.insert(file_id);
90            }
91        }
92
93        println!();
94        println!("diagnostic scan complete");
95
96        if found_error {
97            println!();
98            anyhow::bail!("diagnostic error detected")
99        }
100
101        Ok(())
102    }
103}
104
105fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
106    let mut worklist: Vec<_> =
107        Crate::all(db).into_iter().map(|krate| krate.root_module()).collect();
108    let mut modules = Vec::new();
109
110    while let Some(module) = worklist.pop() {
111        modules.push(module);
112        worklist.extend(module.children(db));
113    }
114
115    modules
116}