rust_analyzer/cli/
diagnostics.rs1use 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, progress_report::ProgressReport};
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 let min_severity = self.severity.unwrap_or(flags::Severity::Weak);
54
55 let work = all_modules(db)
56 .into_iter()
57 .filter(|module| {
58 let file_id = module.definition_source_file_id(db).original_file(db);
59 let source_root = db.file_source_root(file_id.file_id(db)).source_root_id(db);
60 let source_root = db.source_root(source_root).source_root(db);
61 !source_root.is_library
62 })
63 .collect::<Vec<_>>();
64
65 let mut bar = ProgressReport::new(work.len());
66 for module in work {
67 let file_id = module.definition_source_file_id(db).original_file(db);
68 if !visited_files.contains(&file_id) {
69 let message = format!("processing {}", _vfs.file_path(file_id.file_id(db)));
70 bar.set_message(move || message.clone());
71 let crate_name = module
72 .krate(db)
73 .display_name(db)
74 .as_deref()
75 .unwrap_or(&sym::unknown)
76 .to_owned();
77 for diagnostic in analysis
78 .full_diagnostics(
79 &DiagnosticsConfig::test_sample(),
80 AssistResolveStrategy::None,
81 file_id.file_id(db),
82 )
83 .unwrap()
84 {
85 let severity = match diagnostic.severity {
86 Severity::Error => flags::Severity::Error,
87 Severity::Warning => flags::Severity::Warning,
88 Severity::WeakWarning => flags::Severity::Weak,
89 Severity::Allow => continue,
90 };
91 if severity < min_severity {
92 continue;
93 }
94
95 if matches!(diagnostic.severity, Severity::Error) {
96 found_error = true;
97 }
98
99 let Diagnostic { code, message, range, severity, .. } = diagnostic;
100 let line_index = db.line_index(range.file_id);
101 let start = line_index.line_col(range.range.start());
102 let end = line_index.line_col(range.range.end());
103 bar.println(format!(
104 "at crate {crate_name}, file {}: {severity:?} {code:?} from {start:?} to {end:?}: {message}",
105 _vfs.file_path(file_id.file_id(db))
106 ));
107 }
108
109 visited_files.insert(file_id);
110 }
111 bar.inc(1);
112 }
113 bar.finish_and_clear();
114
115 println!();
116 println!("diagnostic scan complete");
117
118 if found_error {
119 println!();
120 anyhow::bail!("diagnostic error detected")
121 }
122
123 Ok(())
124 }
125}
126
127fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
128 let mut worklist: Vec<_> =
129 Crate::all(db).into_iter().map(|krate| krate.root_module(db)).collect();
130 let mut modules = Vec::new();
131
132 while let Some(module) = worklist.pop() {
133 modules.push(module);
134 worklist.extend(module.children(db));
135 }
136
137 modules
138}