Skip to content

Commit 98fcc05

Browse files
committed
Clear flycheck diagnostics more granularly
1 parent 4aa34ab commit 98fcc05

File tree

4 files changed

+125
-48
lines changed

4 files changed

+125
-48
lines changed

src/tools/rust-analyzer/crates/rust-analyzer/src/diagnostics.rs

+41-10
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ pub(crate) mod to_proto;
33

44
use std::mem;
55

6+
use cargo_metadata::PackageId;
67
use ide::FileId;
78
use ide_db::FxHashMap;
89
use itertools::Itertools;
@@ -13,7 +14,8 @@ use triomphe::Arc;
1314

1415
use crate::{global_state::GlobalStateSnapshot, lsp, lsp_ext, main_loop::DiagnosticsTaskKind};
1516

16-
pub(crate) type CheckFixes = Arc<IntMap<usize, IntMap<FileId, Vec<Fix>>>>;
17+
pub(crate) type CheckFixes =
18+
Arc<IntMap<usize, FxHashMap<Option<PackageId>, IntMap<FileId, Vec<Fix>>>>>;
1719

1820
#[derive(Debug, Default, Clone)]
1921
pub struct DiagnosticsMapConfig {
@@ -31,7 +33,8 @@ pub(crate) struct DiagnosticCollection {
3133
pub(crate) native_syntax: IntMap<FileId, (DiagnosticsGeneration, Vec<lsp_types::Diagnostic>)>,
3234
pub(crate) native_semantic: IntMap<FileId, (DiagnosticsGeneration, Vec<lsp_types::Diagnostic>)>,
3335
// FIXME: should be Vec<flycheck::Diagnostic>
34-
pub(crate) check: IntMap<usize, IntMap<FileId, Vec<lsp_types::Diagnostic>>>,
36+
pub(crate) check:
37+
IntMap<usize, FxHashMap<Option<PackageId>, IntMap<FileId, Vec<lsp_types::Diagnostic>>>>,
3538
pub(crate) check_fixes: CheckFixes,
3639
changes: IntSet<FileId>,
3740
/// Counter for supplying a new generation number for diagnostics.
@@ -50,18 +53,19 @@ pub(crate) struct Fix {
5053

5154
impl DiagnosticCollection {
5255
pub(crate) fn clear_check(&mut self, flycheck_id: usize) {
53-
if let Some(it) = Arc::make_mut(&mut self.check_fixes).get_mut(&flycheck_id) {
56+
if let Some(it) = self.check.get_mut(&flycheck_id) {
5457
it.clear();
5558
}
56-
if let Some(it) = self.check.get_mut(&flycheck_id) {
57-
self.changes.extend(it.drain().map(|(key, _value)| key));
59+
if let Some(fixes) = Arc::make_mut(&mut self.check_fixes).get_mut(&flycheck_id) {
60+
fixes.clear();
5861
}
5962
}
6063

6164
pub(crate) fn clear_check_all(&mut self) {
6265
Arc::make_mut(&mut self.check_fixes).clear();
63-
self.changes
64-
.extend(self.check.values_mut().flat_map(|it| it.drain().map(|(key, _value)| key)))
66+
self.changes.extend(
67+
self.check.values_mut().flat_map(|it| it.drain().flat_map(|(_, v)| v.into_keys())),
68+
)
6569
}
6670

6771
pub(crate) fn clear_native_for(&mut self, file_id: FileId) {
@@ -70,14 +74,29 @@ impl DiagnosticCollection {
7074
self.changes.insert(file_id);
7175
}
7276

77+
pub(crate) fn clear_check_for_package(&mut self, flycheck_id: usize, package_id: PackageId) {
78+
let Some(check) = self.check.get_mut(&flycheck_id) else {
79+
return;
80+
};
81+
check.remove(&Some(package_id));
82+
}
83+
7384
pub(crate) fn add_check_diagnostic(
7485
&mut self,
7586
flycheck_id: usize,
87+
package_id: &Option<PackageId>,
7688
file_id: FileId,
7789
diagnostic: lsp_types::Diagnostic,
7890
fix: Option<Box<Fix>>,
7991
) {
80-
let diagnostics = self.check.entry(flycheck_id).or_default().entry(file_id).or_default();
92+
let diagnostics = self
93+
.check
94+
.entry(flycheck_id)
95+
.or_default()
96+
.entry(package_id.clone())
97+
.or_default()
98+
.entry(file_id)
99+
.or_default();
81100
for existing_diagnostic in diagnostics.iter() {
82101
if are_diagnostics_equal(existing_diagnostic, &diagnostic) {
83102
return;
@@ -86,7 +105,14 @@ impl DiagnosticCollection {
86105

87106
if let Some(fix) = fix {
88107
let check_fixes = Arc::make_mut(&mut self.check_fixes);
89-
check_fixes.entry(flycheck_id).or_default().entry(file_id).or_default().push(*fix);
108+
check_fixes
109+
.entry(flycheck_id)
110+
.or_default()
111+
.entry(package_id.clone())
112+
.or_default()
113+
.entry(file_id)
114+
.or_default()
115+
.push(*fix);
90116
}
91117
diagnostics.push(diagnostic);
92118
self.changes.insert(file_id);
@@ -135,7 +161,12 @@ impl DiagnosticCollection {
135161
) -> impl Iterator<Item = &lsp_types::Diagnostic> {
136162
let native_syntax = self.native_syntax.get(&file_id).into_iter().flat_map(|(_, d)| d);
137163
let native_semantic = self.native_semantic.get(&file_id).into_iter().flat_map(|(_, d)| d);
138-
let check = self.check.values().filter_map(move |it| it.get(&file_id)).flatten();
164+
let check = self
165+
.check
166+
.values()
167+
.flat_map(|it| it.values())
168+
.filter_map(move |it| it.get(&file_id))
169+
.flatten();
139170
native_syntax.chain(native_semantic).chain(check)
140171
}
141172

src/tools/rust-analyzer/crates/rust-analyzer/src/flycheck.rs

+69-33
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
//! Flycheck provides the functionality needed to run `cargo check` to provide
22
//! LSP diagnostics based on the output of the command.
33
4-
use std::{fmt, io, process::Command, time::Duration};
4+
use std::{fmt, io, mem, process::Command, time::Duration};
55

6+
use cargo_metadata::PackageId;
67
use crossbeam_channel::{select_biased, unbounded, Receiver, Sender};
78
use paths::{AbsPath, AbsPathBuf, Utf8PathBuf};
89
use rustc_hash::FxHashMap;
@@ -150,10 +151,19 @@ impl FlycheckHandle {
150151

151152
pub(crate) enum FlycheckMessage {
152153
/// Request adding a diagnostic with fixes included to a file
153-
AddDiagnostic { id: usize, workspace_root: AbsPathBuf, diagnostic: Diagnostic },
154+
AddDiagnostic {
155+
id: usize,
156+
workspace_root: AbsPathBuf,
157+
diagnostic: Diagnostic,
158+
package_id: Option<PackageId>,
159+
},
154160

155-
/// Request clearing all previous diagnostics
156-
ClearDiagnostics { id: usize },
161+
/// Request clearing all outdated diagnostics.
162+
ClearDiagnostics {
163+
id: usize,
164+
/// The pacakge whose diagnostics to clear, or if unspecified, all diagnostics.
165+
package_id: Option<PackageId>,
166+
},
157167

158168
/// Request check progress notification to client
159169
Progress {
@@ -166,15 +176,18 @@ pub(crate) enum FlycheckMessage {
166176
impl fmt::Debug for FlycheckMessage {
167177
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168178
match self {
169-
FlycheckMessage::AddDiagnostic { id, workspace_root, diagnostic } => f
179+
FlycheckMessage::AddDiagnostic { id, workspace_root, diagnostic, package_id } => f
170180
.debug_struct("AddDiagnostic")
171181
.field("id", id)
172182
.field("workspace_root", workspace_root)
183+
.field("package_id", package_id)
173184
.field("diagnostic_code", &diagnostic.code.as_ref().map(|it| &it.code))
174185
.finish(),
175-
FlycheckMessage::ClearDiagnostics { id } => {
176-
f.debug_struct("ClearDiagnostics").field("id", id).finish()
177-
}
186+
FlycheckMessage::ClearDiagnostics { id, package_id } => f
187+
.debug_struct("ClearDiagnostics")
188+
.field("id", id)
189+
.field("package_id", package_id)
190+
.finish(),
178191
FlycheckMessage::Progress { id, progress } => {
179192
f.debug_struct("Progress").field("id", id).field("progress", progress).finish()
180193
}
@@ -200,6 +213,7 @@ enum StateChange {
200213
struct FlycheckActor {
201214
/// The workspace id of this flycheck instance.
202215
id: usize,
216+
203217
sender: Sender<FlycheckMessage>,
204218
config: FlycheckConfig,
205219
manifest_path: Option<AbsPathBuf>,
@@ -215,8 +229,13 @@ struct FlycheckActor {
215229
command_handle: Option<CommandHandle<CargoCheckMessage>>,
216230
/// The receiver side of the channel mentioned above.
217231
command_receiver: Option<Receiver<CargoCheckMessage>>,
232+
package_status: FxHashMap<PackageId, DiagnosticReceived>,
233+
}
218234

219-
status: FlycheckStatus,
235+
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
236+
enum DiagnosticReceived {
237+
Yes,
238+
No,
220239
}
221240

222241
#[allow(clippy::large_enum_variant)]
@@ -225,13 +244,6 @@ enum Event {
225244
CheckEvent(Option<CargoCheckMessage>),
226245
}
227246

228-
#[derive(PartialEq)]
229-
enum FlycheckStatus {
230-
Started,
231-
DiagnosticSent,
232-
Finished,
233-
}
234-
235247
pub(crate) const SAVED_FILE_PLACEHOLDER: &str = "$saved_file";
236248

237249
impl FlycheckActor {
@@ -253,7 +265,7 @@ impl FlycheckActor {
253265
manifest_path,
254266
command_handle: None,
255267
command_receiver: None,
256-
status: FlycheckStatus::Finished,
268+
package_status: FxHashMap::default(),
257269
}
258270
}
259271

@@ -306,13 +318,11 @@ impl FlycheckActor {
306318
self.command_handle = Some(command_handle);
307319
self.command_receiver = Some(receiver);
308320
self.report_progress(Progress::DidStart);
309-
self.status = FlycheckStatus::Started;
310321
}
311322
Err(error) => {
312323
self.report_progress(Progress::DidFailToRestart(format!(
313324
"Failed to run the following command: {formatted_command} error={error}"
314325
)));
315-
self.status = FlycheckStatus::Finished;
316326
}
317327
}
318328
}
@@ -332,11 +342,25 @@ impl FlycheckActor {
332342
error
333343
);
334344
}
335-
if self.status == FlycheckStatus::Started {
336-
self.send(FlycheckMessage::ClearDiagnostics { id: self.id });
345+
if self.package_status.is_empty() {
346+
// We finished without receiving any diagnostics.
347+
// That means all of them are stale.
348+
self.send(FlycheckMessage::ClearDiagnostics {
349+
id: self.id,
350+
package_id: None,
351+
});
352+
} else {
353+
for (package_id, status) in mem::take(&mut self.package_status) {
354+
if let DiagnosticReceived::No = status {
355+
self.send(FlycheckMessage::ClearDiagnostics {
356+
id: self.id,
357+
package_id: Some(package_id),
358+
});
359+
}
360+
}
337361
}
362+
338363
self.report_progress(Progress::DidFinish(res));
339-
self.status = FlycheckStatus::Finished;
340364
}
341365
Event::CheckEvent(Some(message)) => match message {
342366
CargoCheckMessage::CompilerArtifact(msg) => {
@@ -346,23 +370,30 @@ impl FlycheckActor {
346370
"artifact received"
347371
);
348372
self.report_progress(Progress::DidCheckCrate(msg.target.name));
373+
self.package_status.entry(msg.package_id).or_insert(DiagnosticReceived::No);
349374
}
350-
351-
CargoCheckMessage::Diagnostic(msg) => {
375+
CargoCheckMessage::Diagnostic { diagnostic, package_id } => {
352376
tracing::trace!(
353377
flycheck_id = self.id,
354-
message = msg.message,
378+
message = diagnostic.message,
355379
"diagnostic received"
356380
);
357-
if self.status == FlycheckStatus::Started {
358-
self.send(FlycheckMessage::ClearDiagnostics { id: self.id });
381+
if let Some(package_id) = &package_id {
382+
if !self.package_status.contains_key(package_id) {
383+
self.package_status
384+
.insert(package_id.clone(), DiagnosticReceived::Yes);
385+
self.send(FlycheckMessage::ClearDiagnostics {
386+
id: self.id,
387+
package_id: Some(package_id.clone()),
388+
});
389+
}
359390
}
360391
self.send(FlycheckMessage::AddDiagnostic {
361392
id: self.id,
393+
package_id,
362394
workspace_root: self.root.clone(),
363-
diagnostic: msg,
395+
diagnostic,
364396
});
365-
self.status = FlycheckStatus::DiagnosticSent;
366397
}
367398
},
368399
}
@@ -380,7 +411,7 @@ impl FlycheckActor {
380411
command_handle.cancel();
381412
self.command_receiver.take();
382413
self.report_progress(Progress::DidCancel);
383-
self.status = FlycheckStatus::Finished;
414+
self.package_status.clear();
384415
}
385416
}
386417

@@ -486,7 +517,7 @@ impl FlycheckActor {
486517
#[allow(clippy::large_enum_variant)]
487518
enum CargoCheckMessage {
488519
CompilerArtifact(cargo_metadata::Artifact),
489-
Diagnostic(Diagnostic),
520+
Diagnostic { diagnostic: Diagnostic, package_id: Option<PackageId> },
490521
}
491522

492523
impl ParseFromLine for CargoCheckMessage {
@@ -501,11 +532,16 @@ impl ParseFromLine for CargoCheckMessage {
501532
Some(CargoCheckMessage::CompilerArtifact(artifact))
502533
}
503534
cargo_metadata::Message::CompilerMessage(msg) => {
504-
Some(CargoCheckMessage::Diagnostic(msg.message))
535+
Some(CargoCheckMessage::Diagnostic {
536+
diagnostic: msg.message,
537+
package_id: Some(msg.package_id),
538+
})
505539
}
506540
_ => None,
507541
},
508-
JsonMessage::Rustc(message) => Some(CargoCheckMessage::Diagnostic(message)),
542+
JsonMessage::Rustc(message) => {
543+
Some(CargoCheckMessage::Diagnostic { diagnostic: message, package_id: None })
544+
}
509545
};
510546
}
511547

src/tools/rust-analyzer/crates/rust-analyzer/src/handlers/request.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -1441,7 +1441,13 @@ pub(crate) fn handle_code_action(
14411441
}
14421442

14431443
// Fixes from `cargo check`.
1444-
for fix in snap.check_fixes.values().filter_map(|it| it.get(&frange.file_id)).flatten() {
1444+
for fix in snap
1445+
.check_fixes
1446+
.values()
1447+
.flat_map(|it| it.values())
1448+
.filter_map(|it| it.get(&frange.file_id))
1449+
.flatten()
1450+
{
14451451
// FIXME: this mapping is awkward and shouldn't exist. Refactor
14461452
// `snap.check_fixes` to not convert to LSP prematurely.
14471453
let intersect_fix_range = fix

src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs

+8-4
Original file line numberDiff line numberDiff line change
@@ -956,7 +956,7 @@ impl GlobalState {
956956

957957
fn handle_flycheck_msg(&mut self, message: FlycheckMessage) {
958958
match message {
959-
FlycheckMessage::AddDiagnostic { id, workspace_root, diagnostic } => {
959+
FlycheckMessage::AddDiagnostic { id, workspace_root, diagnostic, package_id } => {
960960
let snap = self.snapshot();
961961
let diagnostics = crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
962962
&self.config.diagnostics_map(None),
@@ -968,6 +968,7 @@ impl GlobalState {
968968
match url_to_file_id(&self.vfs.read().0, &diag.url) {
969969
Ok(file_id) => self.diagnostics.add_check_diagnostic(
970970
id,
971+
&package_id,
971972
file_id,
972973
diag.diagnostic,
973974
diag.fix,
@@ -981,9 +982,12 @@ impl GlobalState {
981982
};
982983
}
983984
}
984-
985-
FlycheckMessage::ClearDiagnostics { id } => self.diagnostics.clear_check(id),
986-
985+
FlycheckMessage::ClearDiagnostics { id, package_id: None } => {
986+
self.diagnostics.clear_check(id)
987+
}
988+
FlycheckMessage::ClearDiagnostics { id, package_id: Some(package_id) } => {
989+
self.diagnostics.clear_check_for_package(id, package_id)
990+
}
987991
FlycheckMessage::Progress { id, progress } => {
988992
let (state, message) = match progress {
989993
flycheck::Progress::DidStart => (Progress::Begin, None),

0 commit comments

Comments
 (0)