Skip to main content

rust_analyzer/handlers/
notification.rs

1//! This module is responsible for implementing handlers for Language Server
2//! Protocol. This module specifically handles notifications.
3
4use std::{
5    ops::{Deref, Not as _},
6    panic::UnwindSafe,
7};
8
9use ide_db::base_db::TargetKind;
10use itertools::Itertools;
11use lsp_types::{
12    CancelParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
13    DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams,
14    DidOpenTextDocumentParams, DidSaveTextDocumentParams, WorkDoneProgressCancelParams,
15};
16use paths::Utf8PathBuf;
17use triomphe::Arc;
18use vfs::{AbsPathBuf, ChangeKind, VfsPath};
19
20use crate::{
21    config::{Config, ConfigChange},
22    flycheck::{InvocationStrategy, PackageSpecifier, Target},
23    global_state::{FetchWorkspaceRequest, GlobalState},
24    lsp::{from_proto, utils::apply_document_changes},
25    lsp_ext::{self, RunFlycheckParams},
26    mem_docs::DocumentData,
27    reload,
28    target_spec::TargetSpec,
29    try_default,
30};
31
32pub(crate) fn handle_cancel(state: &mut GlobalState, params: CancelParams) -> anyhow::Result<()> {
33    let id: lsp_server::RequestId = match params.id {
34        lsp_types::Id::Int(id) => id.into(),
35        lsp_types::Id::String(id) => id.into(),
36    };
37    state.cancel(id);
38    Ok(())
39}
40
41pub(crate) fn handle_work_done_progress_cancel(
42    state: &mut GlobalState,
43    params: WorkDoneProgressCancelParams,
44) -> anyhow::Result<()> {
45    if let lsp_types::ProgressToken::String(s) = &params.token
46        && let Some(id) = s.strip_prefix("rust-analyzer/flycheck/")
47        && let Ok(id) = id.parse::<u32>()
48        && let Some(flycheck) = state.flycheck.get(id as usize)
49    {
50        flycheck.cancel();
51    }
52
53    // Just ignore this. It is OK to continue sending progress
54    // notifications for this token, as the client can't know when
55    // we accepted notification.
56    Ok(())
57}
58
59pub(crate) fn handle_did_open_text_document(
60    state: &mut GlobalState,
61    params: DidOpenTextDocumentParams,
62) -> anyhow::Result<()> {
63    let _p = tracing::info_span!("handle_did_open_text_document").entered();
64
65    if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
66        let already_exists = state
67            .mem_docs
68            .insert(
69                path.clone(),
70                DocumentData::new(
71                    params.text_document.version,
72                    params.text_document.text.clone().into_bytes(),
73                ),
74            )
75            .is_err();
76        if already_exists {
77            tracing::error!("duplicate DidOpenTextDocument: {}", path);
78        }
79
80        if let Some(abs_path) = path.as_path()
81            && state.config.excluded().any(|excluded| abs_path.starts_with(&excluded))
82        {
83            tracing::trace!("opened excluded file {abs_path}");
84            state.vfs.write().0.insert_excluded_file(path);
85            return Ok(());
86        }
87
88        // Library files are immutable: the client never becomes authoritative over their
89        // contents, disk is the truth.
90        if !state.source_root_config.path_is_library(&path) {
91            let contents = params.text_document.text.into_bytes();
92            state.vfs.write().0.set_file_contents(path, Some(contents));
93        }
94        if state.config.discover_workspace_config().is_some() {
95            tracing::debug!("queuing task");
96            let _ = state
97                .deferred_task_queue
98                .sender
99                .send(crate::main_loop::DeferredTask::CheckIfIndexed(params.text_document.uri));
100        }
101    }
102    Ok(())
103}
104
105pub(crate) fn handle_did_change_text_document(
106    state: &mut GlobalState,
107    params: DidChangeTextDocumentParams,
108) -> anyhow::Result<()> {
109    let _p = tracing::info_span!("handle_did_change_text_document").entered();
110
111    if let Ok(path) = from_proto::vfs_path(&params.text_document.text_document_identifier.uri) {
112        let Some(DocumentData { version, data }) = state.mem_docs.get_mut(&path) else {
113            tracing::error!(?path, "unexpected DidChangeTextDocument");
114            return Ok(());
115        };
116        // The version passed in DidChangeTextDocument is the version after all edits are applied
117        // so we should apply it before the vfs is notified.
118        *version = params.text_document.version;
119
120        let new_contents = apply_document_changes(
121            state.config.negotiated_encoding(),
122            std::str::from_utf8(data).unwrap(),
123            params.content_changes,
124        )
125        .into_bytes();
126        if *data != new_contents {
127            data.clone_from(&new_contents);
128            // Library files are immutable, changes to them are ignored.
129            if !state.source_root_config.path_is_library(&path) {
130                state.vfs.write().0.set_file_contents(path, Some(new_contents));
131            }
132        }
133    }
134    Ok(())
135}
136
137pub(crate) fn handle_did_close_text_document(
138    state: &mut GlobalState,
139    params: DidCloseTextDocumentParams,
140) -> anyhow::Result<()> {
141    let _p = tracing::info_span!("handle_did_close_text_document").entered();
142
143    if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
144        if state.mem_docs.remove(&path).is_err() {
145            tracing::error!("orphan DidCloseTextDocument: {}", path);
146        }
147
148        // Clear diagnostics also for excluded files, just in case.
149        if let Some((file_id, _)) = state.vfs.read().0.file_id(&path) {
150            state.diagnostics.clear_native_for(file_id);
151        }
152
153        state.semantic_tokens_cache.lock().remove(&params.text_document.uri);
154
155        if let Some(path) = path.as_path() {
156            state.loader.handle.invalidate(path.to_path_buf());
157        }
158    }
159    Ok(())
160}
161
162pub(crate) fn handle_did_save_text_document(
163    state: &mut GlobalState,
164    params: DidSaveTextDocumentParams,
165) -> anyhow::Result<()> {
166    if let Ok(vfs_path) = from_proto::vfs_path(&params.text_document.uri) {
167        // Library files are immutable and not watched, so the save is the only chance to
168        // pick up the changed disk contents.
169        if state.source_root_config.path_is_library(&vfs_path)
170            && let Some(path) = vfs_path.as_path()
171        {
172            state.loader.handle.invalidate(path.to_path_buf());
173        }
174
175        let snap = state.snapshot();
176        let file_id = try_default!(snap.vfs_path_to_file_id(&vfs_path)?);
177        let sr = snap.analysis.source_root_id(file_id)?;
178
179        if state.config.script_rebuild_on_save(Some(sr)) && state.build_deps_changed {
180            state.build_deps_changed = false;
181            state
182                .fetch_build_data_queue
183                .request_op("build_deps_changed - save notification".to_owned(), ());
184        }
185
186        // Re-fetch workspaces if a workspace related file has changed
187        if let Some(path) = vfs_path.as_path() {
188            let additional_files = &state
189                .config
190                .discover_workspace_config()
191                .map(|cfg| cfg.files_to_watch.iter().map(String::as_str).collect::<Vec<&str>>())
192                .unwrap_or_default();
193
194            // FIXME: We should move this check into a QueuedTask and do semantic resolution of
195            // the files. There is only so much we can tell syntactically from the path.
196            if reload::should_refresh_for_change(path, ChangeKind::Modify, additional_files) {
197                state.fetch_workspaces_queue.request_op(
198                    format!("workspace vfs file change saved {path}"),
199                    FetchWorkspaceRequest {
200                        path: Some(path.to_owned()),
201                        force_crate_graph_reload: false,
202                    },
203                );
204            } else if state.detached_files.contains(path) {
205                state.fetch_workspaces_queue.request_op(
206                    format!("detached file saved {path}"),
207                    FetchWorkspaceRequest {
208                        path: Some(path.to_owned()),
209                        force_crate_graph_reload: false,
210                    },
211                );
212            }
213        }
214
215        if !state.config.check_on_save(Some(sr)) || run_flycheck(state, vfs_path) {
216            return Ok(());
217        }
218    } else if state.config.check_on_save(None) && state.config.flycheck_workspace(None) {
219        // No specific flycheck was triggered, so let's trigger all of them.
220        for flycheck in state.flycheck.iter() {
221            flycheck.restart_workspace(None);
222        }
223    }
224
225    Ok(())
226}
227
228pub(crate) fn handle_did_change_configuration(
229    state: &mut GlobalState,
230    _params: DidChangeConfigurationParams,
231) -> anyhow::Result<()> {
232    // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
233    // this notification's parameters should be ignored and the actual config queried separately.
234    state.send_request::<lsp_types::ConfigurationRequest>(
235        lsp_types::ConfigurationParams {
236            items: vec![lsp_types::ConfigurationItem {
237                scope_uri: None,
238                section: Some("rust-analyzer".to_owned()),
239            }],
240        },
241        |this, resp| {
242            tracing::debug!("config update response: '{:?}", resp);
243            let lsp_server::Response { error, result, .. } = resp;
244
245            match (error, result) {
246                (Some(err), _) => {
247                    tracing::error!("failed to fetch the server settings: {:?}", err)
248                }
249                (None, Some(mut configs)) => {
250                    if let Some(json) = configs.get_mut(0) {
251                        let config = Config::clone(&*this.config);
252                        let mut change = ConfigChange::default();
253                        change.change_client_config(json.take());
254
255                        let (config, e, _) = config.apply_change(change);
256                        this.config_errors = e.is_empty().not().then_some(e);
257
258                        // Client config changes necessitates .update_config method to be called.
259                        this.update_configuration(config);
260                    }
261                }
262                (None, None) => {
263                    tracing::error!("received empty server settings response from the client")
264                }
265            }
266        },
267    );
268
269    Ok(())
270}
271
272pub(crate) fn handle_did_change_workspace_folders(
273    state: &mut GlobalState,
274    params: DidChangeWorkspaceFoldersParams,
275) -> anyhow::Result<()> {
276    let config = Arc::make_mut(&mut state.config);
277
278    for workspace in params.event.removed {
279        let Ok(path) = workspace.uri.to_file_path() else { continue };
280        let Ok(path) = Utf8PathBuf::from_path_buf(path) else { continue };
281        let Ok(path) = AbsPathBuf::try_from(path) else { continue };
282        config.remove_workspace(&path);
283    }
284
285    let added = params
286        .event
287        .added
288        .into_iter()
289        .filter_map(|it| it.uri.to_file_path().ok())
290        .filter_map(|it| Utf8PathBuf::from_path_buf(it).ok())
291        .filter_map(|it| AbsPathBuf::try_from(it).ok());
292    config.add_workspaces(added);
293
294    if !config.has_linked_projects() && config.detached_files().is_empty() {
295        config.rediscover_workspaces();
296
297        let req = FetchWorkspaceRequest { path: None, force_crate_graph_reload: false };
298        state.fetch_workspaces_queue.request_op("client workspaces changed".to_owned(), req);
299    }
300
301    Ok(())
302}
303
304pub(crate) fn handle_did_change_watched_files(
305    state: &mut GlobalState,
306    params: DidChangeWatchedFilesParams,
307) -> anyhow::Result<()> {
308    // we want to trigger flycheck if a file outside of our workspaces has changed,
309    // as to reduce stale diagnostics when outside changes happen
310    let mut trigger_flycheck = false;
311    for change in params.changes.iter().unique_by(|&it| &it.uri) {
312        if let Ok(path) = from_proto::abs_path(&change.uri) {
313            if !trigger_flycheck {
314                // Trigger if no workspaces contain this file.
315                trigger_flycheck =
316                    state.config.workspace_roots().iter().all(|root| !path.starts_with(root));
317            }
318            state.loader.handle.invalidate(path);
319        }
320    }
321
322    if trigger_flycheck && state.config.check_on_save(None) {
323        for flycheck in state.flycheck.iter() {
324            flycheck.restart_workspace(None);
325        }
326    }
327    Ok(())
328}
329
330fn run_flycheck(state: &mut GlobalState, vfs_path: VfsPath) -> bool {
331    let _p = tracing::info_span!("run_flycheck").entered();
332
333    let file_id = state.vfs.read().0.file_id(&vfs_path);
334    if let Some((file_id, vfs::FileExcluded::No)) = file_id {
335        let world = state.snapshot();
336        let invocation_strategy = state.config.flycheck(None).invocation_strategy();
337        let may_flycheck_workspace = state.config.flycheck_workspace(None);
338
339        let task: Box<dyn FnOnce() -> ide::Cancellable<()> + Send + UnwindSafe> =
340            match invocation_strategy {
341                InvocationStrategy::Once => {
342                    Box::new(move || {
343                        // FIXME: Because triomphe::Arc's auto UnwindSafe impl requires that the inner type
344                        // be UnwindSafe, and FlycheckHandle is not UnwindSafe, `word.flycheck` cannot
345                        // be captured directly. std::sync::Arc has an UnwindSafe impl that only requires
346                        // that the inner type be RefUnwindSafe, so if we were using that one we wouldn't
347                        // have this problem. Remove the line below when triomphe::Arc has an UnwindSafe impl
348                        // like std::sync::Arc's.
349                        let world = world;
350                        let saved_file = vfs_path.as_path().map(ToOwned::to_owned);
351                        if let Some(flycheck) = world.flycheck.first() {
352                            flycheck.restart_workspace(saved_file);
353                        }
354                        Ok(())
355                    })
356                }
357                InvocationStrategy::PerWorkspace => {
358                    Box::new(move || {
359                        let saved_file = vfs_path.as_path().map(ToOwned::to_owned);
360                        let target = TargetSpec::for_file(&world, file_id)?.map(|it| {
361                            let tgt_kind = it.target_kind();
362                            let (tgt_name, root, package) = match it {
363                                TargetSpec::Cargo(c) => (
364                                    Some(c.target),
365                                    c.workspace_root,
366                                    PackageSpecifier::Cargo { package_id: c.package_id },
367                                ),
368                                TargetSpec::ProjectJson(p) => (
369                                    None,
370                                    p.project_root,
371                                    PackageSpecifier::BuildInfo { label: p.label.clone() },
372                                ),
373                            };
374
375                            let tgt = tgt_name.and_then(|tgt_name| {
376                                Some(match tgt_kind {
377                                    TargetKind::Bin => Target::Bin(tgt_name),
378                                    TargetKind::Example => Target::Example(tgt_name),
379                                    TargetKind::Test => Target::Test(tgt_name),
380                                    TargetKind::Bench => Target::Benchmark(tgt_name),
381                                    _ => return None,
382                                })
383                            });
384
385                            (tgt, root, package)
386                        });
387                        tracing::debug!(?target, "flycheck target");
388                        // we have a specific non-library target, attempt to only check that target, nothing
389                        // else will be affected
390                        let mut package_workspace_idx = None;
391                        if let Some((target, root, package)) = target {
392                            // trigger a package check if we have a non-library target as that can't affect
393                            // anything else in the workspace OR if we're not allowed to check the workspace as
394                            // the user opted into package checks then OR if this is not cargo.
395                            let package_check_allowed = target.is_some()
396                                || !may_flycheck_workspace
397                                || matches!(package, PackageSpecifier::BuildInfo { .. });
398                            if package_check_allowed {
399                                package_workspace_idx =
400                                    world.workspaces.iter().position(|ws| match &ws.kind {
401                                        project_model::ProjectWorkspaceKind::Cargo {
402                                            cargo,
403                                            ..
404                                        }
405                                        | project_model::ProjectWorkspaceKind::DetachedFile {
406                                            cargo: Some((cargo, _, _)),
407                                            ..
408                                        } => *cargo.workspace_root() == root,
409                                        project_model::ProjectWorkspaceKind::Json(p) => {
410                                            *p.project_root() == root
411                                        }
412                                        project_model::ProjectWorkspaceKind::DetachedFile {
413                                            cargo: None,
414                                            ..
415                                        } => false,
416                                    });
417                                if let Some(idx) = package_workspace_idx {
418                                    // flycheck handles are indexed by their ID (which is the workspace index),
419                                    // but not all workspaces have flycheck enabled (e.g., JSON projects without
420                                    // a flycheck template). Find the flycheck handle by its ID.
421                                    if let Some(flycheck) =
422                                        world.flycheck.iter().find(|fc| fc.id() == idx)
423                                    {
424                                        let workspace_deps =
425                                            world.all_workspace_dependencies_for_package(&package);
426                                        flycheck.restart_for_package(
427                                            package,
428                                            target,
429                                            workspace_deps,
430                                            saved_file.clone(),
431                                        );
432                                    }
433                                }
434                            }
435                        }
436
437                        if !may_flycheck_workspace {
438                            return Ok(());
439                        }
440
441                        // Trigger flychecks for all workspaces that depend on the saved file
442                        // Crates containing or depending on the saved file
443                        let crate_ids: Vec<_> = world
444                            .analysis
445                            .crates_for(file_id)?
446                            .into_iter()
447                            .flat_map(|id| world.analysis.transitive_rev_deps(id))
448                            .flatten()
449                            .unique()
450                            .collect();
451                        tracing::debug!(?crate_ids, "flycheck crate ids");
452                        let crate_root_paths: Vec<_> = crate_ids
453                            .iter()
454                            .filter_map(|&crate_id| {
455                                world
456                                    .analysis
457                                    .crate_root(crate_id)
458                                    .map(|file_id| {
459                                        world
460                                            .file_id_to_file_path(file_id)
461                                            .as_path()
462                                            .map(ToOwned::to_owned)
463                                    })
464                                    .transpose()
465                            })
466                            .collect::<ide::Cancellable<_>>()?;
467                        let crate_root_paths: Vec<_> =
468                            crate_root_paths.iter().map(Deref::deref).collect();
469                        tracing::debug!(?crate_root_paths, "flycheck crate roots");
470
471                        // Find all workspaces that have at least one target containing the saved file
472                        let workspace_ids =
473                            world.workspaces.iter().enumerate().filter(|&(idx, ws)| {
474                                let ws_contains_file = match &ws.kind {
475                                    project_model::ProjectWorkspaceKind::Cargo {
476                                        cargo, ..
477                                    }
478                                    | project_model::ProjectWorkspaceKind::DetachedFile {
479                                        cargo: Some((cargo, _, _)),
480                                        ..
481                                    } => cargo.packages().any(|pkg| {
482                                        cargo[pkg].targets.iter().any(|&it| {
483                                            crate_root_paths.contains(&cargo[it].root.as_path())
484                                        })
485                                    }),
486                                    project_model::ProjectWorkspaceKind::Json(project) => {
487                                        project.crates().any(|(_, krate)| {
488                                            crate_root_paths.contains(&krate.root_module.as_path())
489                                        })
490                                    }
491                                    project_model::ProjectWorkspaceKind::DetachedFile {
492                                        ..
493                                    } => false,
494                                };
495                                let is_pkg_ws = match package_workspace_idx {
496                                    Some(pkg_idx) => pkg_idx == idx,
497                                    None => false,
498                                };
499                                ws_contains_file && !is_pkg_ws
500                            });
501
502                        let mut workspace_check_triggered = false;
503                        // Find and trigger corresponding flychecks
504                        'flychecks: for flycheck in world.flycheck.iter() {
505                            for (id, _) in workspace_ids.clone() {
506                                if id == flycheck.id() {
507                                    workspace_check_triggered = true;
508                                    flycheck.restart_workspace(saved_file.clone());
509                                    continue 'flychecks;
510                                }
511                            }
512                        }
513
514                        // No specific flycheck was triggered, so let's trigger all of them.
515                        if !workspace_check_triggered && package_workspace_idx.is_none() {
516                            for flycheck in world.flycheck.iter() {
517                                flycheck.restart_workspace(saved_file.clone());
518                            }
519                        }
520                        Ok(())
521                    })
522                }
523            };
524
525        state.task_pool.handle.spawn_with_sender(stdx::thread::ThreadIntent::Worker, move |_| {
526            if let Err(e) = std::panic::catch_unwind(task) {
527                tracing::error!("flycheck task panicked: {e:?}")
528            }
529        });
530        true
531    } else {
532        false
533    }
534}
535
536pub(crate) fn handle_cancel_flycheck(state: &mut GlobalState, _: ()) -> anyhow::Result<()> {
537    let _p = tracing::info_span!("handle_cancel_flycheck").entered();
538    state.flycheck.iter().for_each(|flycheck| flycheck.cancel());
539    Ok(())
540}
541
542pub(crate) fn handle_clear_flycheck(state: &mut GlobalState, _: ()) -> anyhow::Result<()> {
543    let _p = tracing::info_span!("handle_clear_flycheck").entered();
544    state.diagnostics.clear_check_all();
545    Ok(())
546}
547
548pub(crate) fn handle_run_flycheck(
549    state: &mut GlobalState,
550    params: RunFlycheckParams,
551) -> anyhow::Result<()> {
552    let _p = tracing::info_span!("handle_run_flycheck").entered();
553    if let Some(text_document) = params.text_document
554        && let Ok(vfs_path) = from_proto::vfs_path(&text_document.uri)
555        && run_flycheck(state, vfs_path)
556    {
557        return Ok(());
558    }
559    // No specific flycheck was triggered, so let's trigger all of them.
560    if state.config.flycheck_workspace(None) {
561        for flycheck in state.flycheck.iter() {
562            flycheck.restart_workspace(None);
563        }
564    }
565    Ok(())
566}
567
568pub(crate) fn handle_abort_run_test(state: &mut GlobalState, _: ()) -> anyhow::Result<()> {
569    if state.test_run_session.take().is_some() {
570        state.send_notification::<lsp_ext::EndRunTestNotification>(());
571    }
572    Ok(())
573}