Skip to content

Commit 0fe3bcf

Browse files
committed
Auto merge of rust-lang#12808 - Veykril:check-workspace, r=Veykril
feat: Only flycheck workspace that belongs to saved file Supercedes rust-lang/rust-analyzer#11038 There is still the problem that all the diagnostics are cleared, only clearing diagnostics of the relevant workspace isn't easily doable though I think, will have to dig into that
2 parents c6a9fbf + df7f755 commit 0fe3bcf

File tree

7 files changed

+123
-23
lines changed

7 files changed

+123
-23
lines changed

crates/flycheck/src/lib.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ pub struct FlycheckHandle {
5757
// XXX: drop order is significant
5858
sender: Sender<Restart>,
5959
_thread: jod_thread::JoinHandle,
60+
id: usize,
6061
}
6162

6263
impl FlycheckHandle {
@@ -72,18 +73,22 @@ impl FlycheckHandle {
7273
.name("Flycheck".to_owned())
7374
.spawn(move || actor.run(receiver))
7475
.expect("failed to spawn thread");
75-
FlycheckHandle { sender, _thread: thread }
76+
FlycheckHandle { id, sender, _thread: thread }
7677
}
7778

7879
/// Schedule a re-start of the cargo check worker.
7980
pub fn update(&self) {
8081
self.sender.send(Restart).unwrap();
8182
}
83+
84+
pub fn id(&self) -> usize {
85+
self.id
86+
}
8287
}
8388

8489
pub enum Message {
8590
/// Request adding a diagnostic with fixes included to a file
86-
AddDiagnostic { workspace_root: AbsPathBuf, diagnostic: Diagnostic },
91+
AddDiagnostic { id: usize, workspace_root: AbsPathBuf, diagnostic: Diagnostic },
8792

8893
/// Request check progress notification to client
8994
Progress {
@@ -96,8 +101,9 @@ pub enum Message {
96101
impl fmt::Debug for Message {
97102
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98103
match self {
99-
Message::AddDiagnostic { workspace_root, diagnostic } => f
104+
Message::AddDiagnostic { id, workspace_root, diagnostic } => f
100105
.debug_struct("AddDiagnostic")
106+
.field("id", id)
101107
.field("workspace_root", workspace_root)
102108
.field("diagnostic_code", &diagnostic.code.as_ref().map(|it| &it.code))
103109
.finish(),
@@ -183,7 +189,7 @@ impl FlycheckActor {
183189
}
184190
}
185191
Event::CheckEvent(None) => {
186-
tracing::debug!("flycheck finished");
192+
tracing::debug!(flycheck_id = self.id, "flycheck finished");
187193

188194
// Watcher finished
189195
let cargo_handle = self.cargo_handle.take().unwrap();
@@ -203,6 +209,7 @@ impl FlycheckActor {
203209

204210
CargoMessage::Diagnostic(msg) => {
205211
self.send(Message::AddDiagnostic {
212+
id: self.id,
206213
workspace_root: self.workspace_root.clone(),
207214
diagnostic: msg,
208215
});

crates/paths/src/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,14 @@ impl AsRef<Path> for AbsPath {
106106
}
107107
}
108108

109+
impl ToOwned for AbsPath {
110+
type Owned = AbsPathBuf;
111+
112+
fn to_owned(&self) -> Self::Owned {
113+
AbsPathBuf(self.0.to_owned())
114+
}
115+
}
116+
109117
impl<'a> TryFrom<&'a Path> for &'a AbsPath {
110118
type Error = &'a Path;
111119
fn try_from(path: &'a Path) -> Result<&'a AbsPath, &'a Path> {

crates/rust-analyzer/src/diagnostics.rs

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_hash::{FxHashMap, FxHashSet};
88

99
use crate::lsp_ext;
1010

11-
pub(crate) type CheckFixes = Arc<FxHashMap<FileId, Vec<Fix>>>;
11+
pub(crate) type CheckFixes = Arc<FxHashMap<usize, FxHashMap<FileId, Vec<Fix>>>>;
1212

1313
#[derive(Debug, Default, Clone)]
1414
pub struct DiagnosticsMapConfig {
@@ -22,7 +22,7 @@ pub(crate) struct DiagnosticCollection {
2222
// FIXME: should be FxHashMap<FileId, Vec<ra_id::Diagnostic>>
2323
pub(crate) native: FxHashMap<FileId, Vec<lsp_types::Diagnostic>>,
2424
// FIXME: should be Vec<flycheck::Diagnostic>
25-
pub(crate) check: FxHashMap<FileId, Vec<lsp_types::Diagnostic>>,
25+
pub(crate) check: FxHashMap<usize, FxHashMap<FileId, Vec<lsp_types::Diagnostic>>>,
2626
pub(crate) check_fixes: CheckFixes,
2727
changes: FxHashSet<FileId>,
2828
}
@@ -35,9 +35,19 @@ pub(crate) struct Fix {
3535
}
3636

3737
impl DiagnosticCollection {
38-
pub(crate) fn clear_check(&mut self) {
38+
pub(crate) fn clear_check(&mut self, flycheck_id: usize) {
39+
if let Some(it) = Arc::make_mut(&mut self.check_fixes).get_mut(&flycheck_id) {
40+
it.clear();
41+
}
42+
if let Some(it) = self.check.get_mut(&flycheck_id) {
43+
self.changes.extend(it.drain().map(|(key, _value)| key));
44+
}
45+
}
46+
47+
pub(crate) fn clear_check_all(&mut self) {
3948
Arc::make_mut(&mut self.check_fixes).clear();
40-
self.changes.extend(self.check.drain().map(|(key, _value)| key))
49+
self.changes
50+
.extend(self.check.values_mut().flat_map(|it| it.drain().map(|(key, _value)| key)))
4151
}
4252

4353
pub(crate) fn clear_native_for(&mut self, file_id: FileId) {
@@ -47,19 +57,20 @@ impl DiagnosticCollection {
4757

4858
pub(crate) fn add_check_diagnostic(
4959
&mut self,
60+
flycheck_id: usize,
5061
file_id: FileId,
5162
diagnostic: lsp_types::Diagnostic,
5263
fix: Option<Fix>,
5364
) {
54-
let diagnostics = self.check.entry(file_id).or_default();
65+
let diagnostics = self.check.entry(flycheck_id).or_default().entry(file_id).or_default();
5566
for existing_diagnostic in diagnostics.iter() {
5667
if are_diagnostics_equal(existing_diagnostic, &diagnostic) {
5768
return;
5869
}
5970
}
6071

6172
let check_fixes = Arc::make_mut(&mut self.check_fixes);
62-
check_fixes.entry(file_id).or_default().extend(fix);
73+
check_fixes.entry(flycheck_id).or_default().entry(file_id).or_default().extend(fix);
6374
diagnostics.push(diagnostic);
6475
self.changes.insert(file_id);
6576
}
@@ -89,7 +100,8 @@ impl DiagnosticCollection {
89100
file_id: FileId,
90101
) -> impl Iterator<Item = &lsp_types::Diagnostic> {
91102
let native = self.native.get(&file_id).into_iter().flatten();
92-
let check = self.check.get(&file_id).into_iter().flatten();
103+
let check =
104+
self.check.values().filter_map(move |it| it.get(&file_id)).into_iter().flatten();
93105
native.chain(check)
94106
}
95107

crates/rust-analyzer/src/global_state.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ impl GlobalState {
192192
if let Some(path) = vfs.file_path(file.file_id).as_path() {
193193
let path = path.to_path_buf();
194194
if reload::should_refresh_for_change(&path, file.change_kind) {
195+
tracing::warn!("fetch-fiel_change");
195196
self.fetch_workspaces_queue
196197
.request_op(format!("vfs file change: {}", path.display()));
197198
}
@@ -201,6 +202,7 @@ impl GlobalState {
201202
}
202203
}
203204

205+
// Clear native diagnostics when their file gets deleted
204206
if !file.exists() {
205207
self.diagnostics.clear_native_for(file.file_id);
206208
}

crates/rust-analyzer/src/handlers.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1094,7 +1094,9 @@ pub(crate) fn handle_code_action(
10941094
}
10951095

10961096
// Fixes from `cargo check`.
1097-
for fix in snap.check_fixes.get(&frange.file_id).into_iter().flatten() {
1097+
for fix in
1098+
snap.check_fixes.values().filter_map(|it| it.get(&frange.file_id)).into_iter().flatten()
1099+
{
10981100
// FIXME: this mapping is awkward and shouldn't exist. Refactor
10991101
// `snap.check_fixes` to not convert to LSP prematurely.
11001102
let intersect_fix_range = fix

crates/rust-analyzer/src/main_loop.rs

Lines changed: 79 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22
//! requests/replies and notifications back to the client.
33
use std::{
44
fmt,
5+
ops::Deref,
56
sync::Arc,
67
time::{Duration, Instant},
78
};
89

910
use always_assert::always;
1011
use crossbeam_channel::{select, Receiver};
11-
use ide_db::base_db::{SourceDatabaseExt, VfsPath};
12+
use ide_db::base_db::{SourceDatabase, SourceDatabaseExt, VfsPath};
13+
use itertools::Itertools;
1214
use lsp_server::{Connection, Notification, Request};
1315
use lsp_types::notification::Notification as _;
1416
use vfs::{ChangeKind, FileId};
@@ -371,7 +373,7 @@ impl GlobalState {
371373
let _p = profile::span("GlobalState::handle_event/flycheck");
372374
loop {
373375
match task {
374-
flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
376+
flycheck::Message::AddDiagnostic { id, workspace_root, diagnostic } => {
375377
let snap = self.snapshot();
376378
let diagnostics =
377379
crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
@@ -383,6 +385,7 @@ impl GlobalState {
383385
for diag in diagnostics {
384386
match url_to_file_id(&self.vfs.read().0, &diag.url) {
385387
Ok(file_id) => self.diagnostics.add_check_diagnostic(
388+
id,
386389
file_id,
387390
diag.diagnostic,
388391
diag.fix,
@@ -400,7 +403,7 @@ impl GlobalState {
400403
flycheck::Message::Progress { id, progress } => {
401404
let (state, message) = match progress {
402405
flycheck::Progress::DidStart => {
403-
self.diagnostics.clear_check();
406+
self.diagnostics.clear_check(id);
404407
(Progress::Begin, None)
405408
}
406409
flycheck::Progress::DidCheckCrate(target) => {
@@ -444,7 +447,10 @@ impl GlobalState {
444447
let memdocs_added_or_removed = self.mem_docs.take_changes();
445448

446449
if self.is_quiescent() {
447-
if !was_quiescent {
450+
if !was_quiescent
451+
&& !self.fetch_workspaces_queue.op_requested()
452+
&& !self.fetch_build_data_queue.op_requested()
453+
{
448454
for flycheck in &self.flycheck {
449455
flycheck.update();
450456
}
@@ -734,13 +740,76 @@ impl GlobalState {
734740
Ok(())
735741
})?
736742
.on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
737-
for flycheck in &this.flycheck {
738-
flycheck.update();
743+
let mut updated = false;
744+
if let Ok(vfs_path) = from_proto::vfs_path(&params.text_document.uri) {
745+
let (vfs, _) = &*this.vfs.read();
746+
if let Some(file_id) = vfs.file_id(&vfs_path) {
747+
let analysis = this.analysis_host.analysis();
748+
// Crates containing or depending on the saved file
749+
let crate_ids: Vec<_> = analysis
750+
.crate_for(file_id)?
751+
.into_iter()
752+
.flat_map(|id| {
753+
this.analysis_host
754+
.raw_database()
755+
.crate_graph()
756+
.transitive_rev_deps(id)
757+
})
758+
.sorted()
759+
.unique()
760+
.collect();
761+
762+
let crate_root_paths: Vec<_> = crate_ids
763+
.iter()
764+
.filter_map(|&crate_id| {
765+
analysis
766+
.crate_root(crate_id)
767+
.map(|file_id| {
768+
vfs.file_path(file_id).as_path().map(ToOwned::to_owned)
769+
})
770+
.transpose()
771+
})
772+
.collect::<ide::Cancellable<_>>()?;
773+
let crate_root_paths: Vec<_> =
774+
crate_root_paths.iter().map(Deref::deref).collect();
775+
776+
// Find all workspaces that have at least one target containing the saved file
777+
let workspace_ids =
778+
this.workspaces.iter().enumerate().filter(|(_, ws)| match ws {
779+
project_model::ProjectWorkspace::Cargo { cargo, .. } => {
780+
cargo.packages().any(|pkg| {
781+
cargo[pkg].targets.iter().any(|&it| {
782+
crate_root_paths.contains(&cargo[it].root.as_path())
783+
})
784+
})
785+
}
786+
project_model::ProjectWorkspace::Json { project, .. } => project
787+
.crates()
788+
.any(|(c, _)| crate_ids.iter().any(|&crate_id| crate_id == c)),
789+
project_model::ProjectWorkspace::DetachedFiles { .. } => false,
790+
});
791+
792+
// Find and trigger corresponding flychecks
793+
for flycheck in &this.flycheck {
794+
for (id, _) in workspace_ids.clone() {
795+
if id == flycheck.id() {
796+
updated = true;
797+
flycheck.update();
798+
continue;
799+
}
800+
}
801+
}
802+
}
803+
if let Some(abs_path) = vfs_path.as_path() {
804+
if reload::should_refresh_for_change(&abs_path, ChangeKind::Modify) {
805+
this.fetch_workspaces_queue
806+
.request_op(format!("DidSaveTextDocument {}", abs_path.display()));
807+
}
808+
}
739809
}
740-
if let Ok(abs_path) = from_proto::abs_path(&params.text_document.uri) {
741-
if reload::should_refresh_for_change(&abs_path, ChangeKind::Modify) {
742-
this.fetch_workspaces_queue
743-
.request_op(format!("DidSaveTextDocument {}", abs_path.display()));
810+
if !updated {
811+
for flycheck in &this.flycheck {
812+
flycheck.update();
744813
}
745814
}
746815
Ok(())

crates/rust-analyzer/src/reload.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,7 @@ impl GlobalState {
458458
Some(it) => it,
459459
None => {
460460
self.flycheck = Vec::new();
461-
self.diagnostics.clear_check();
461+
self.diagnostics.clear_check_all();
462462
return;
463463
}
464464
};

0 commit comments

Comments
 (0)